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], xBX, 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 (words[op_w][4] == 'b')
1104 else if (words[op_w][4] == 'w')
1106 else if (words[op_w][4] == 'd')
1109 op->regmask_src = 0;
1110 setup_reg_opr(&op->operand[j++], op->op == OP_LODS ? xSI : xDI,
1111 OPLM_DWORD, &op->regmask_src);
1112 op->regmask_dst = op->regmask_src;
1113 setup_reg_opr(&op->operand[j++], xAX, lmod,
1114 op->op == OP_LODS ? &op->regmask_dst : &op->regmask_src);
1115 if (op->flags & OPF_REP) {
1116 setup_reg_opr(&op->operand[j++], xCX, OPLM_DWORD, &op->regmask_src);
1117 op->regmask_dst |= 1 << xCX;
1119 op->operand_cnt = j;
1124 if (words[op_w][4] == 'b')
1126 else if (words[op_w][4] == 'w')
1128 else if (words[op_w][4] == 'd')
1131 op->regmask_src = 0;
1132 // note: lmod is not correct, don't have where to place it
1133 setup_reg_opr(&op->operand[j++], xDI, lmod, &op->regmask_src);
1134 setup_reg_opr(&op->operand[j++], xSI, OPLM_DWORD, &op->regmask_src);
1135 if (op->flags & OPF_REP)
1136 setup_reg_opr(&op->operand[j++], xCX, OPLM_DWORD, &op->regmask_src);
1137 op->operand_cnt = j;
1138 op->regmask_dst = op->regmask_src;
1142 op->regmask_dst = 1 << xCX;
1145 op->operand_cnt = 2;
1146 op->regmask_src = 1 << xCX;
1147 op->operand[1].type = OPT_REG;
1148 op->operand[1].reg = xCX;
1149 op->operand[1].lmod = OPLM_DWORD;
1153 if (op->operand_cnt == 2) {
1154 if (op->operand[0].type != OPT_REG)
1155 aerr("reg expected\n");
1156 op->regmask_src |= 1 << op->operand[0].reg;
1158 if (op->operand_cnt != 1)
1163 op->regmask_src |= op->regmask_dst;
1164 op->regmask_dst = (1 << xDX) | (1 << xAX);
1165 if (op->operand[0].lmod == OPLM_UNSPEC)
1166 op->operand[0].lmod = OPLM_DWORD;
1171 // we could set up operands for edx:eax, but there is no real need to
1172 // (see is_opr_modified())
1173 op->regmask_src |= op->regmask_dst;
1174 op->regmask_dst = (1 << xDX) | (1 << xAX);
1175 if (op->operand[0].lmod == OPLM_UNSPEC)
1176 op->operand[0].lmod = OPLM_DWORD;
1184 op->regmask_src |= op->regmask_dst;
1185 if (op->operand[1].lmod == OPLM_UNSPEC)
1186 op->operand[1].lmod = OPLM_BYTE;
1191 op->regmask_src |= op->regmask_dst;
1192 if (op->operand[2].lmod == OPLM_UNSPEC)
1193 op->operand[2].lmod = OPLM_BYTE;
1197 op->regmask_src |= op->regmask_dst;
1198 op->regmask_dst = 0;
1199 if (op->operand[0].lmod == OPLM_UNSPEC
1200 && (op->operand[0].type == OPT_CONST
1201 || op->operand[0].type == OPT_OFFSET
1202 || op->operand[0].type == OPT_LABEL))
1203 op->operand[0].lmod = OPLM_DWORD;
1209 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1210 && op->operand[0].lmod == op->operand[1].lmod
1211 && op->operand[0].reg == op->operand[1].reg
1212 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1214 op->flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
1215 op->regmask_src = op->regmask_dst = 0;
1220 if (op->operand[0].type == OPT_REG
1221 && op->operand[1].type == OPT_REGMEM)
1224 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1225 if (IS(buf, op->operand[1].name))
1226 op->flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
1231 // trashed regs must be explicitly detected later
1232 op->regmask_dst = 0;
1236 op->regmask_dst = (1 << xBP) | (1 << xSP);
1237 op->regmask_src = 1 << xBP;
1244 if (op->operand[0].type == OPT_REG
1245 && op->operand[1].type == OPT_CONST)
1247 struct parsed_opr *op1 = &op->operand[1];
1248 if ((op->op == OP_AND && op1->val == 0)
1251 || (op->operand[0].lmod == OPLM_WORD && op1->val == 0xffff)
1252 || (op->operand[0].lmod == OPLM_BYTE && op1->val == 0xff))))
1254 op->regmask_src = 0;
1259 static const char *op_name(struct parsed_op *po)
1261 static char buf[16];
1265 if (po->op == OP_JCC || po->op == OP_SCC) {
1267 *p++ = (po->op == OP_JCC) ? 'j' : 's';
1270 strcpy(p, parsed_flag_op_names[po->pfo]);
1274 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1275 if (op_table[i].op == po->op)
1276 return op_table[i].name;
1282 static const char *dump_op(struct parsed_op *po)
1284 static char out[128];
1291 snprintf(out, sizeof(out), "%s", op_name(po));
1292 for (i = 0; i < po->operand_cnt; i++) {
1296 snprintf(p, sizeof(out) - (p - out),
1297 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1298 po->operand[i].name);
1304 static const char *lmod_type_u(struct parsed_op *po,
1305 enum opr_lenmod lmod)
1317 ferr(po, "invalid lmod: %d\n", lmod);
1318 return "(_invalid_)";
1322 static const char *lmod_cast_u(struct parsed_op *po,
1323 enum opr_lenmod lmod)
1335 ferr(po, "invalid lmod: %d\n", lmod);
1336 return "(_invalid_)";
1340 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1341 enum opr_lenmod lmod)
1353 ferr(po, "invalid lmod: %d\n", lmod);
1354 return "(_invalid_)";
1358 static const char *lmod_cast_s(struct parsed_op *po,
1359 enum opr_lenmod lmod)
1371 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1372 return "(_invalid_)";
1376 static const char *lmod_cast(struct parsed_op *po,
1377 enum opr_lenmod lmod, int is_signed)
1380 lmod_cast_s(po, lmod) :
1381 lmod_cast_u(po, lmod);
1384 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1396 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1401 static const char *opr_name(struct parsed_op *po, int opr_num)
1403 if (opr_num >= po->operand_cnt)
1404 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1405 return po->operand[opr_num].name;
1408 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1410 if (opr_num >= po->operand_cnt)
1411 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1412 if (po->operand[opr_num].type != OPT_CONST)
1413 ferr(po, "opr %d: const expected\n", opr_num);
1414 return po->operand[opr_num].val;
1417 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1419 if ((unsigned int)popr->reg >= ARRAY_SIZE(regs_r32))
1420 ferr(po, "invalid reg: %d\n", popr->reg);
1421 return regs_r32[popr->reg];
1424 static int check_simple_cast(const char *cast, int *bits, int *is_signed)
1426 if (IS_START(cast, "(s8)") || IS_START(cast, "(u8)"))
1428 else if (IS_START(cast, "(s16)") || IS_START(cast, "(u16)"))
1430 else if (IS_START(cast, "(s32)") || IS_START(cast, "(u32)"))
1432 else if (IS_START(cast, "(s64)") || IS_START(cast, "(u64)"))
1437 *is_signed = cast[1] == 's' ? 1 : 0;
1441 static int check_deref_cast(const char *cast, int *bits)
1443 if (IS_START(cast, "*(u8 *)"))
1445 else if (IS_START(cast, "*(u16 *)"))
1447 else if (IS_START(cast, "*(u32 *)"))
1449 else if (IS_START(cast, "*(u64 *)"))
1457 // cast1 is the "final" cast
1458 static const char *simplify_cast(const char *cast1, const char *cast2)
1460 static char buf[256];
1468 if (IS(cast1, cast2))
1471 if (check_simple_cast(cast1, &bits1, &s1) == 0
1472 && check_simple_cast(cast2, &bits2, &s2) == 0)
1477 if (check_simple_cast(cast1, &bits1, &s1) == 0
1478 && check_deref_cast(cast2, &bits2) == 0)
1480 if (bits1 == bits2) {
1481 snprintf(buf, sizeof(buf), "*(%c%d *)", s1 ? 's' : 'u', bits1);
1486 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1489 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1493 static const char *simplify_cast_num(const char *cast, unsigned int val)
1495 if (IS(cast, "(u8)") && val < 0x100)
1497 if (IS(cast, "(s8)") && val < 0x80)
1499 if (IS(cast, "(u16)") && val < 0x10000)
1501 if (IS(cast, "(s16)") && val < 0x8000)
1503 if (IS(cast, "(s32)") && val < 0x80000000)
1509 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1518 namelen = strlen(name);
1520 p = strchr(name, '+');
1524 ferr(po, "equ parse failed for '%s'\n", name);
1526 if (IS_START(p, "0x"))
1528 *extra_offs = strtol(p, &endp, 16);
1530 ferr(po, "equ parse failed for '%s'\n", name);
1533 for (i = 0; i < g_eqcnt; i++)
1534 if (strncmp(g_eqs[i].name, name, namelen) == 0
1535 && g_eqs[i].name[namelen] == 0)
1539 ferr(po, "unresolved equ name: '%s'\n", name);
1546 static int is_stack_access(struct parsed_op *po,
1547 const struct parsed_opr *popr)
1549 return (parse_stack_el(popr->name, NULL, 0)
1550 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1551 && IS_START(popr->name, "ebp")));
1554 static void parse_stack_access(struct parsed_op *po,
1555 const char *name, char *ofs_reg, int *offset_out,
1556 int *stack_ra_out, const char **bp_arg_out, int is_lea)
1558 const char *bp_arg = "";
1559 const char *p = NULL;
1560 struct parsed_equ *eq;
1567 if (IS_START(name, "ebp-")
1568 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1571 if (IS_START(p, "0x"))
1573 offset = strtoul(p, &endp, 16);
1577 ferr(po, "ebp- parse of '%s' failed\n", name);
1580 bp_arg = parse_stack_el(name, ofs_reg, 0);
1581 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1582 eq = equ_find(po, bp_arg, &offset);
1584 ferr(po, "detected but missing eq\n");
1585 offset += eq->offset;
1588 if (!strncmp(name, "ebp", 3))
1591 // yes it sometimes LEAs ra for compares..
1592 if (!is_lea && ofs_reg[0] == 0
1593 && stack_ra <= offset && offset < stack_ra + 4)
1595 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1598 *offset_out = offset;
1599 *stack_ra_out = stack_ra;
1601 *bp_arg_out = bp_arg;
1604 static int stack_frame_access(struct parsed_op *po,
1605 struct parsed_opr *popr, char *buf, size_t buf_size,
1606 const char *name, const char *cast, int is_src, int is_lea)
1608 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1609 const char *prefix = "";
1610 const char *bp_arg = NULL;
1611 char ofs_reg[16] = { 0, };
1612 int i, arg_i, arg_s;
1620 if (po->flags & OPF_EBP_S)
1621 ferr(po, "stack_frame_access while ebp is scratch\n");
1623 parse_stack_access(po, name, ofs_reg, &offset,
1624 &stack_ra, &bp_arg, is_lea);
1626 if (offset > stack_ra)
1628 arg_i = (offset - stack_ra - 4) / 4;
1629 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1631 if (g_func_pp->is_vararg
1632 && arg_i == g_func_pp->argc_stack && is_lea)
1634 // should be va_list
1637 snprintf(buf, buf_size, "%sap", cast);
1640 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1641 offset, bp_arg, arg_i);
1643 if (ofs_reg[0] != 0)
1644 ferr(po, "offset reg on arg access?\n");
1646 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1647 if (g_func_pp->arg[i].reg != NULL)
1653 if (i == g_func_pp->argc)
1654 ferr(po, "arg %d not in prototype?\n", arg_i);
1656 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1663 ferr(po, "lea/byte to arg?\n");
1664 if (is_src && (offset & 3) == 0)
1665 snprintf(buf, buf_size, "%sa%d",
1666 simplify_cast(cast, "(u8)"), i + 1);
1668 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1669 cast, offset & 3, i + 1);
1674 ferr(po, "lea/word to arg?\n");
1679 ferr(po, "problematic arg store\n");
1680 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1681 simplify_cast(cast, "*(u16 *)"), i + 1);
1684 ferr(po, "unaligned arg word load\n");
1686 else if (is_src && (offset & 2) == 0)
1687 snprintf(buf, buf_size, "%sa%d",
1688 simplify_cast(cast, "(u16)"), i + 1);
1690 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1691 cast, (offset & 2) ? "HI" : "LO", i + 1);
1703 snprintf(buf, buf_size, "(u32)&a%d + %d",
1706 ferr(po, "unaligned arg store\n");
1708 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1709 snprintf(buf, buf_size, "%s(a%d >> %d)",
1710 prefix, i + 1, (offset & 3) * 8);
1714 snprintf(buf, buf_size, "%s%sa%d",
1715 prefix, is_lea ? "&" : "", i + 1);
1720 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1724 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1727 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1728 if (tmp_lmod != OPLM_DWORD
1729 && (unaligned || (!is_src && lmod_bytes(po, tmp_lmod)
1730 < lmod_bytes(po, popr->lmod) + (offset & 3))))
1732 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1733 i + 1, offset, g_func_pp->arg[i].type.name);
1735 // can't check this because msvc likes to reuse
1736 // arg space for scratch..
1737 //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1738 // ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1742 if (g_stack_fsz == 0)
1743 ferr(po, "stack var access without stackframe\n");
1744 g_stack_frame_used = 1;
1746 sf_ofs = g_stack_fsz + offset;
1747 lim = (ofs_reg[0] != 0) ? -4 : 0;
1748 if (offset > 0 || sf_ofs < lim)
1749 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1759 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1760 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1764 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1765 // known unaligned or possibly unaligned
1766 strcat(g_comment, " unaligned");
1768 prefix = "*(u16 *)&";
1769 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1770 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1773 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1777 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1778 // known unaligned or possibly unaligned
1779 strcat(g_comment, " unaligned");
1781 prefix = "*(u32 *)&";
1782 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1783 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1786 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1790 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1797 static void check_func_pp(struct parsed_op *po,
1798 const struct parsed_proto *pp, const char *pfx)
1800 enum opr_lenmod tmp_lmod;
1804 if (pp->argc_reg != 0) {
1805 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1806 pp_print(buf, sizeof(buf), pp);
1807 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1809 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1810 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1811 pfx, pp->argc_reg, pp->argc_stack);
1814 // fptrs must use 32bit args, callsite might have no information and
1815 // lack a cast to smaller types, which results in incorrectly masked
1816 // args passed (callee may assume masked args, it does on ARM)
1817 if (!pp->is_osinc) {
1818 for (i = 0; i < pp->argc; i++) {
1819 ret = guess_lmod_from_c_type(&tmp_lmod, &pp->arg[i].type);
1820 if (ret && tmp_lmod != OPLM_DWORD)
1821 ferr(po, "reference to %s with arg%d '%s'\n", pp->name,
1822 i + 1, pp->arg[i].type.name);
1827 static const char *check_label_read_ref(struct parsed_op *po,
1830 const struct parsed_proto *pp;
1832 pp = proto_parse(g_fhdr, name, 0);
1834 ferr(po, "proto_parse failed for ref '%s'\n", name);
1837 check_func_pp(po, pp, "ref");
1842 static char *out_src_opr(char *buf, size_t buf_size,
1843 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1846 char tmp1[256], tmp2[256];
1855 switch (popr->type) {
1858 ferr(po, "lea from reg?\n");
1860 switch (popr->lmod) {
1862 snprintf(buf, buf_size, "%s%s.q", cast, opr_reg_p(po, popr));
1865 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1868 snprintf(buf, buf_size, "%s%s",
1869 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1872 if (popr->name[1] == 'h') // XXX..
1873 snprintf(buf, buf_size, "%s(%s >> 8)",
1874 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1876 snprintf(buf, buf_size, "%s%s",
1877 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1880 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1885 if (is_stack_access(po, popr)) {
1886 stack_frame_access(po, popr, buf, buf_size,
1887 popr->name, cast, 1, is_lea);
1891 strcpy(expr, popr->name);
1892 if (strchr(expr, '[')) {
1893 // special case: '[' can only be left for label[reg] form
1894 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1896 ferr(po, "parse failure for '%s'\n", expr);
1897 if (tmp1[0] == '(') {
1898 // (off_4FFF50+3)[eax]
1899 p = strchr(tmp1 + 1, ')');
1900 if (p == NULL || p[1] != 0)
1901 ferr(po, "parse failure (2) for '%s'\n", expr);
1903 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1905 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1908 // XXX: do we need more parsing?
1910 snprintf(buf, buf_size, "%s", expr);
1914 snprintf(buf, buf_size, "%s(%s)",
1915 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1919 name = check_label_read_ref(po, popr->name);
1920 if (cast[0] == 0 && popr->is_ptr)
1924 snprintf(buf, buf_size, "(u32)&%s", name);
1925 else if (popr->size_lt)
1926 snprintf(buf, buf_size, "%s%s%s%s", cast,
1927 lmod_cast_u_ptr(po, popr->lmod),
1928 popr->is_array ? "" : "&", name);
1930 snprintf(buf, buf_size, "%s%s%s", cast, name,
1931 popr->is_array ? "[0]" : "");
1935 name = check_label_read_ref(po, popr->name);
1939 ferr(po, "lea an offset?\n");
1940 snprintf(buf, buf_size, "%s&%s", cast, name);
1945 ferr(po, "lea from const?\n");
1947 printf_number(tmp1, sizeof(tmp1), popr->val);
1948 if (popr->val == 0 && strchr(cast, '*'))
1949 snprintf(buf, buf_size, "NULL");
1951 snprintf(buf, buf_size, "%s%s",
1952 simplify_cast_num(cast, popr->val), tmp1);
1956 ferr(po, "invalid src type: %d\n", popr->type);
1962 // note: may set is_ptr (we find that out late for ebp frame..)
1963 static char *out_dst_opr(char *buf, size_t buf_size,
1964 struct parsed_op *po, struct parsed_opr *popr)
1966 switch (popr->type) {
1968 switch (popr->lmod) {
1970 snprintf(buf, buf_size, "%s.q", opr_reg_p(po, popr));
1973 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1977 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1981 if (popr->name[1] == 'h') // XXX..
1982 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1984 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1987 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1992 if (is_stack_access(po, popr)) {
1993 stack_frame_access(po, popr, buf, buf_size,
1994 popr->name, "", 0, 0);
1998 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
2001 if (popr->size_mismatch)
2002 snprintf(buf, buf_size, "%s%s%s",
2003 lmod_cast_u_ptr(po, popr->lmod),
2004 popr->is_array ? "" : "&", popr->name);
2006 snprintf(buf, buf_size, "%s%s", popr->name,
2007 popr->is_array ? "[0]" : "");
2011 ferr(po, "invalid dst type: %d\n", popr->type);
2017 static char *out_src_opr_u32(char *buf, size_t buf_size,
2018 struct parsed_op *po, struct parsed_opr *popr)
2020 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
2023 static void out_test_for_cc(char *buf, size_t buf_size,
2024 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
2025 enum opr_lenmod lmod, const char *expr)
2027 const char *cast, *scast;
2029 cast = lmod_cast_u(po, lmod);
2030 scast = lmod_cast_s(po, lmod);
2034 case PFO_BE: // CF=1||ZF=1; CF=0
2035 snprintf(buf, buf_size, "(%s%s %s 0)",
2036 cast, expr, is_inv ? "!=" : "==");
2040 case PFO_L: // SF!=OF; OF=0
2041 snprintf(buf, buf_size, "(%s%s %s 0)",
2042 scast, expr, is_inv ? ">=" : "<");
2045 case PFO_LE: // ZF=1||SF!=OF; OF=0
2046 snprintf(buf, buf_size, "(%s%s %s 0)",
2047 scast, expr, is_inv ? ">" : "<=");
2051 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
2055 static void out_cmp_for_cc(char *buf, size_t buf_size,
2056 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
2058 const char *cast, *scast, *cast_use;
2059 char buf1[256], buf2[256];
2060 enum opr_lenmod lmod;
2062 if (po->op != OP_DEC && po->operand[0].lmod != po->operand[1].lmod)
2063 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
2064 po->operand[0].lmod, po->operand[1].lmod);
2065 lmod = po->operand[0].lmod;
2067 cast = lmod_cast_u(po, lmod);
2068 scast = lmod_cast_s(po, lmod);
2084 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
2087 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
2088 if (po->op == OP_DEC)
2089 snprintf(buf2, sizeof(buf2), "1");
2091 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
2095 // note: must be unsigned compare
2096 snprintf(buf, buf_size, "(%s %s %s)",
2097 buf1, is_inv ? ">=" : "<", buf2);
2101 snprintf(buf, buf_size, "(%s %s %s)",
2102 buf1, is_inv ? "!=" : "==", buf2);
2106 // note: must be unsigned compare
2107 snprintf(buf, buf_size, "(%s %s %s)",
2108 buf1, is_inv ? ">" : "<=", buf2);
2111 if (is_inv && lmod == OPLM_BYTE
2112 && po->operand[1].type == OPT_CONST
2113 && po->operand[1].val == 0xff)
2115 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
2116 snprintf(buf, buf_size, "(0)");
2120 // note: must be signed compare
2122 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
2123 scast, buf1, buf2, is_inv ? ">=" : "<");
2127 snprintf(buf, buf_size, "(%s %s %s)",
2128 buf1, is_inv ? ">=" : "<", buf2);
2132 snprintf(buf, buf_size, "(%s %s %s)",
2133 buf1, is_inv ? ">" : "<=", buf2);
2141 static void out_cmp_test(char *buf, size_t buf_size,
2142 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
2144 char buf1[256], buf2[256], buf3[256];
2146 if (po->op == OP_TEST) {
2147 if (IS(opr_name(po, 0), opr_name(po, 1))) {
2148 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
2151 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
2152 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
2153 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
2155 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
2156 po->operand[0].lmod, buf3);
2158 else if (po->op == OP_CMP) {
2159 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
2162 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
2165 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
2166 struct parsed_opr *popr2)
2168 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
2169 ferr(po, "missing lmod for both operands\n");
2171 if (popr1->lmod == OPLM_UNSPEC)
2172 popr1->lmod = popr2->lmod;
2173 else if (popr2->lmod == OPLM_UNSPEC)
2174 popr2->lmod = popr1->lmod;
2175 else if (popr1->lmod != popr2->lmod) {
2176 if (popr1->type_from_var) {
2177 popr1->size_mismatch = 1;
2178 if (popr1->lmod < popr2->lmod)
2180 popr1->lmod = popr2->lmod;
2182 else if (popr2->type_from_var) {
2183 popr2->size_mismatch = 1;
2184 if (popr2->lmod < popr1->lmod)
2186 popr2->lmod = popr1->lmod;
2189 ferr(po, "conflicting lmods: %d vs %d\n",
2190 popr1->lmod, popr2->lmod);
2194 static const char *op_to_c(struct parsed_op *po)
2218 ferr(po, "op_to_c was supplied with %d\n", po->op);
2222 // last op in stream - unconditional branch or ret
2223 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
2224 || ((ops[_i].flags & (OPF_JMP|OPF_CJMP|OPF_RMD)) == OPF_JMP \
2225 && ops[_i].op != OP_CALL))
2227 #define check_i(po, i) \
2229 ferr(po, "bad " #i ": %d\n", i)
2231 // note: this skips over calls and rm'd stuff assuming they're handled
2232 // so it's intended to use at one of final passes
2233 static int scan_for_pop(int i, int opcnt, int magic, int reg,
2234 int depth, int flags_set)
2236 struct parsed_op *po;
2241 for (; i < opcnt; i++) {
2243 if (po->cc_scratch == magic)
2244 return ret; // already checked
2245 po->cc_scratch = magic;
2247 if (po->flags & OPF_TAIL) {
2248 if (po->op == OP_CALL) {
2249 if (po->pp != NULL && po->pp->is_noreturn)
2250 // assume no stack cleanup for noreturn
2253 return -1; // deadend
2256 if (po->flags & (OPF_RMD|OPF_DONE|OPF_FARG))
2259 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2260 if (po->btj != NULL) {
2262 for (j = 0; j < po->btj->count; j++) {
2263 check_i(po, po->btj->d[j].bt_i);
2264 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, magic, reg,
2267 return ret; // dead end
2272 check_i(po, po->bt_i);
2273 if (po->flags & OPF_CJMP) {
2274 ret |= scan_for_pop(po->bt_i, opcnt, magic, reg,
2277 return ret; // dead end
2286 if ((po->op == OP_POP || po->op == OP_PUSH)
2287 && po->operand[0].type == OPT_REG && po->operand[0].reg == reg)
2292 if (po->op == OP_PUSH) {
2295 else if (po->op == OP_POP) {
2296 if (relevant && depth == 0) {
2297 po->flags |= flags_set;
2307 // scan for 'reg' pop backwards starting from i
2308 // intended to use for register restore search, so other reg
2309 // references are considered an error
2310 static int scan_for_rsave_pop_reg(int i, int magic, int reg, int set_flags)
2312 struct parsed_op *po;
2313 struct label_ref *lr;
2316 ops[i].cc_scratch = magic;
2320 if (g_labels[i] != NULL) {
2321 lr = &g_label_refs[i];
2322 for (; lr != NULL; lr = lr->next) {
2323 check_i(&ops[i], lr->i);
2324 ret |= scan_for_rsave_pop_reg(lr->i, magic, reg, set_flags);
2328 if (i > 0 && LAST_OP(i - 1))
2336 if (ops[i].cc_scratch == magic)
2338 ops[i].cc_scratch = magic;
2341 if (po->op == OP_POP && po->operand[0].reg == reg) {
2342 if (po->flags & (OPF_RMD|OPF_DONE))
2345 po->flags |= set_flags;
2349 // this also covers the case where we reach corresponding push
2350 if ((po->regmask_dst | po->regmask_src) & (1 << reg))
2354 // nothing interesting on this path
2358 static void find_reachable_exits(int i, int opcnt, int magic,
2359 int *exits, int *exit_count)
2361 struct parsed_op *po;
2364 for (; i < opcnt; i++)
2367 if (po->cc_scratch == magic)
2369 po->cc_scratch = magic;
2371 if (po->flags & OPF_TAIL) {
2372 ferr_assert(po, *exit_count < MAX_EXITS);
2373 exits[*exit_count] = i;
2378 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2379 if (po->flags & OPF_RMD)
2382 if (po->btj != NULL) {
2383 for (j = 0; j < po->btj->count; j++) {
2384 check_i(po, po->btj->d[j].bt_i);
2385 find_reachable_exits(po->btj->d[j].bt_i, opcnt, magic,
2391 check_i(po, po->bt_i);
2392 if (po->flags & OPF_CJMP)
2393 find_reachable_exits(po->bt_i, opcnt, magic, exits, exit_count);
2401 // scan for 'reg' pop backwards starting from exits (all paths)
2402 static int scan_for_pop_ret(int i, int opcnt, int reg, int set_flags)
2404 static int exits[MAX_EXITS];
2405 static int exit_count;
2410 find_reachable_exits(i, opcnt, i + opcnt * 15, exits,
2412 ferr_assert(&ops[i], exit_count > 0);
2415 for (j = 0; j < exit_count; j++) {
2416 ret = scan_for_rsave_pop_reg(exits[j], i + opcnt * 16 + set_flags,
2425 // scan for one or more pop of push <const>
2426 static int scan_for_pop_const_r(int i, int opcnt, int magic,
2427 int push_i, int is_probe)
2429 struct parsed_op *po;
2430 struct label_ref *lr;
2434 for (; i < opcnt; i++)
2437 if (po->cc_scratch == magic)
2438 return ret; // already checked
2439 po->cc_scratch = magic;
2441 if (po->flags & OPF_JMP) {
2442 if (po->flags & OPF_RMD)
2444 if (po->op == OP_CALL)
2447 if (po->btj != NULL) {
2448 for (j = 0; j < po->btj->count; j++) {
2449 check_i(po, po->btj->d[j].bt_i);
2450 ret |= scan_for_pop_const_r(po->btj->d[j].bt_i, opcnt, magic,
2458 check_i(po, po->bt_i);
2459 if (po->flags & OPF_CJMP) {
2460 ret |= scan_for_pop_const_r(po->bt_i, opcnt, magic, push_i,
2471 if ((po->flags & (OPF_TAIL|OPF_RSAVE)) || po->op == OP_PUSH)
2474 if (g_labels[i] != NULL) {
2475 // all refs must be visited
2476 lr = &g_label_refs[i];
2477 for (; lr != NULL; lr = lr->next) {
2479 if (ops[lr->i].cc_scratch != magic)
2482 if (i > 0 && !LAST_OP(i - 1) && ops[i - 1].cc_scratch != magic)
2486 if (po->op == OP_POP)
2488 if (po->flags & (OPF_RMD|OPF_DONE))
2492 po->flags |= OPF_DONE;
2493 po->datap = &ops[push_i];
2502 static void scan_for_pop_const(int i, int opcnt, int magic)
2506 ret = scan_for_pop_const_r(i + 1, opcnt, magic, i, 1);
2508 ops[i].flags |= OPF_RMD | OPF_DONE;
2509 scan_for_pop_const_r(i + 1, opcnt, magic + 1, i, 0);
2513 // check if all branch targets within a marked path are also marked
2514 // note: the path checked must not be empty or end with a branch
2515 static int check_path_branches(int opcnt, int magic)
2517 struct parsed_op *po;
2520 for (i = 0; i < opcnt; i++) {
2522 if (po->cc_scratch != magic)
2525 if (po->flags & OPF_JMP) {
2526 if ((po->flags & OPF_RMD) || po->op == OP_CALL)
2529 if (po->btj != NULL) {
2530 for (j = 0; j < po->btj->count; j++) {
2531 check_i(po, po->btj->d[j].bt_i);
2532 if (ops[po->btj->d[j].bt_i].cc_scratch != magic)
2537 check_i(po, po->bt_i);
2538 if (ops[po->bt_i].cc_scratch != magic)
2540 if ((po->flags & OPF_CJMP) && ops[i + 1].cc_scratch != magic)
2548 // scan for multiple pushes for given pop
2549 static int scan_pushes_for_pop_r(int i, int magic, int pop_i,
2552 int reg = ops[pop_i].operand[0].reg;
2553 struct parsed_op *po;
2554 struct label_ref *lr;
2557 ops[i].cc_scratch = magic;
2561 if (g_labels[i] != NULL) {
2562 lr = &g_label_refs[i];
2563 for (; lr != NULL; lr = lr->next) {
2564 check_i(&ops[i], lr->i);
2565 ret |= scan_pushes_for_pop_r(lr->i, magic, pop_i, is_probe);
2569 if (i > 0 && LAST_OP(i - 1))
2577 if (ops[i].cc_scratch == magic)
2579 ops[i].cc_scratch = magic;
2582 if (po->op == OP_CALL)
2584 if ((po->flags & (OPF_TAIL|OPF_RSAVE)) || po->op == OP_POP)
2587 if (po->op == OP_PUSH)
2589 if (po->datap != NULL)
2591 if (po->operand[0].type == OPT_REG && po->operand[0].reg == reg)
2592 // leave this case for reg save/restore handlers
2596 po->flags |= OPF_PPUSH | OPF_DONE;
2597 po->datap = &ops[pop_i];
2606 static void scan_pushes_for_pop(int i, int opcnt, int *regmask_pp)
2608 int magic = i + opcnt * 14;
2611 ret = scan_pushes_for_pop_r(i, magic, i, 1);
2613 ret = check_path_branches(opcnt, magic);
2615 ops[i].flags |= OPF_PPUSH | OPF_DONE;
2616 *regmask_pp |= 1 << ops[i].operand[0].reg;
2617 scan_pushes_for_pop_r(i, magic + 1, i, 0);
2622 static void scan_propagate_df(int i, int opcnt)
2624 struct parsed_op *po = &ops[i];
2627 for (; i < opcnt; i++) {
2629 if (po->flags & OPF_DF)
2630 return; // already resolved
2631 po->flags |= OPF_DF;
2633 if (po->op == OP_CALL)
2634 ferr(po, "call with DF set?\n");
2636 if (po->flags & OPF_JMP) {
2637 if (po->btj != NULL) {
2639 for (j = 0; j < po->btj->count; j++) {
2640 check_i(po, po->btj->d[j].bt_i);
2641 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2646 if (po->flags & OPF_RMD)
2648 check_i(po, po->bt_i);
2649 if (po->flags & OPF_CJMP)
2650 scan_propagate_df(po->bt_i, opcnt);
2656 if (po->flags & OPF_TAIL)
2659 if (po->op == OP_CLD) {
2660 po->flags |= OPF_RMD | OPF_DONE;
2665 ferr(po, "missing DF clear?\n");
2668 // is operand 'opr' referenced by parsed_op 'po'?
2669 static int is_opr_referenced(const struct parsed_opr *opr,
2670 const struct parsed_op *po)
2674 if (opr->type == OPT_REG) {
2675 mask = po->regmask_dst | po->regmask_src;
2676 if (po->op == OP_CALL)
2677 mask |= (1 << xAX) | (1 << xCX) | (1 << xDX);
2678 if ((1 << opr->reg) & mask)
2684 for (i = 0; i < po->operand_cnt; i++)
2685 if (IS(po->operand[0].name, opr->name))
2691 // is operand 'opr' read by parsed_op 'po'?
2692 static int is_opr_read(const struct parsed_opr *opr,
2693 const struct parsed_op *po)
2695 if (opr->type == OPT_REG) {
2696 if (po->regmask_src & (1 << opr->reg))
2706 // is operand 'opr' modified by parsed_op 'po'?
2707 static int is_opr_modified(const struct parsed_opr *opr,
2708 const struct parsed_op *po)
2712 if (opr->type == OPT_REG) {
2713 if (po->op == OP_CALL) {
2714 mask = po->regmask_dst;
2715 mask |= (1 << xAX) | (1 << xCX) | (1 << xDX); // ?
2716 if (mask & (1 << opr->reg))
2722 if (po->regmask_dst & (1 << opr->reg))
2728 return IS(po->operand[0].name, opr->name);
2731 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2732 static int is_any_opr_modified(const struct parsed_op *po_test,
2733 const struct parsed_op *po, int c_mode)
2738 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2741 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2744 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2747 // in reality, it can wreck any register, but in decompiled C
2748 // version it can only overwrite eax or edx:eax
2749 mask = (1 << xAX) | (1 << xDX);
2753 if (po->op == OP_CALL
2754 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2757 for (i = 0; i < po_test->operand_cnt; i++)
2758 if (IS(po_test->operand[i].name, po->operand[0].name))
2764 // scan for any po_test operand modification in range given
2765 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2768 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2771 for (; i < opcnt; i++) {
2772 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2779 // scan for po_test operand[0] modification in range given
2780 static int scan_for_mod_opr0(struct parsed_op *po_test,
2783 for (; i < opcnt; i++) {
2784 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2791 static int scan_for_flag_set(int i, int magic, int *branched,
2792 int *setters, int *setter_cnt)
2794 struct label_ref *lr;
2798 if (ops[i].cc_scratch == magic) {
2799 // is this a problem?
2800 //ferr(&ops[i], "%s looped\n", __func__);
2803 ops[i].cc_scratch = magic;
2805 if (g_labels[i] != NULL) {
2808 lr = &g_label_refs[i];
2809 for (; lr->next; lr = lr->next) {
2810 check_i(&ops[i], lr->i);
2811 ret = scan_for_flag_set(lr->i, magic,
2812 branched, setters, setter_cnt);
2817 check_i(&ops[i], lr->i);
2818 if (i > 0 && LAST_OP(i - 1)) {
2822 ret = scan_for_flag_set(lr->i, magic,
2823 branched, setters, setter_cnt);
2829 if (ops[i].flags & OPF_FLAGS) {
2830 setters[*setter_cnt] = i;
2835 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2842 // scan back for cdq, if anything modifies edx, fail
2843 static int scan_for_cdq_edx(int i)
2846 if (g_labels[i] != NULL) {
2847 if (g_label_refs[i].next != NULL)
2849 if (i > 0 && LAST_OP(i - 1)) {
2850 i = g_label_refs[i].i;
2857 if (ops[i].op == OP_CDQ)
2860 if (ops[i].regmask_dst & (1 << xDX))
2867 static int scan_for_reg_clear(int i, int reg)
2870 if (g_labels[i] != NULL) {
2871 if (g_label_refs[i].next != NULL)
2873 if (i > 0 && LAST_OP(i - 1)) {
2874 i = g_label_refs[i].i;
2881 if (ops[i].op == OP_XOR
2882 && ops[i].operand[0].lmod == OPLM_DWORD
2883 && ops[i].operand[0].reg == ops[i].operand[1].reg
2884 && ops[i].operand[0].reg == reg)
2887 if (ops[i].regmask_dst & (1 << reg))
2894 static void patch_esp_adjust(struct parsed_op *po, int adj)
2896 ferr_assert(po, po->op == OP_ADD);
2897 ferr_assert(po, IS(opr_name(po, 0), "esp"));
2898 ferr_assert(po, po->operand[1].type == OPT_CONST);
2900 // this is a bit of a hack, but deals with use of
2901 // single adj for multiple calls
2902 po->operand[1].val -= adj;
2903 po->flags |= OPF_RMD;
2904 if (po->operand[1].val == 0)
2905 po->flags |= OPF_DONE;
2906 ferr_assert(po, (int)po->operand[1].val >= 0);
2909 // scan for positive, constant esp adjust
2910 // multipath case is preliminary
2911 static int scan_for_esp_adjust(int i, int opcnt,
2912 int adj_expect, int *adj, int *is_multipath, int do_update)
2914 int adj_expect_unknown = 0;
2915 struct parsed_op *po;
2919 *adj = *is_multipath = 0;
2920 if (adj_expect < 0) {
2921 adj_expect_unknown = 1;
2922 adj_expect = 32 * 4; // enough?
2925 for (; i < opcnt && *adj < adj_expect; i++) {
2926 if (g_labels[i] != NULL)
2930 if (po->flags & OPF_DONE)
2933 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2934 if (po->operand[1].type != OPT_CONST)
2935 ferr(&ops[i], "non-const esp adjust?\n");
2936 *adj += po->operand[1].val;
2938 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2941 patch_esp_adjust(po, adj_expect);
2943 po->flags |= OPF_RMD;
2947 else if (po->op == OP_PUSH) {
2948 //if (first_pop == -1)
2949 // first_pop = -2; // none
2950 *adj -= lmod_bytes(po, po->operand[0].lmod);
2952 else if (po->op == OP_POP) {
2953 if (!(po->flags & OPF_DONE)) {
2954 // seems like msvc only uses 'pop ecx' for stack realignment..
2955 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2957 if (first_pop == -1 && *adj >= 0)
2960 if (do_update && *adj >= 0) {
2961 po->flags |= OPF_RMD;
2963 po->flags |= OPF_DONE | OPF_NOREGS;
2966 *adj += lmod_bytes(po, po->operand[0].lmod);
2967 if (*adj > adj_best)
2970 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2971 if (po->op == OP_JMP && po->btj == NULL) {
2977 if (po->op != OP_CALL)
2979 if (po->operand[0].type != OPT_LABEL)
2981 if (po->pp != NULL && po->pp->is_stdcall)
2983 if (adj_expect_unknown && first_pop >= 0)
2985 // assume it's another cdecl call
2989 if (first_pop >= 0) {
2990 // probably only 'pop ecx' was used
2998 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
3000 struct parsed_op *po;
3004 ferr(ops, "%s: followed bad branch?\n", __func__);
3006 for (; i < opcnt; i++) {
3008 if (po->cc_scratch == magic)
3010 po->cc_scratch = magic;
3013 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
3014 if (po->btj != NULL) {
3016 for (j = 0; j < po->btj->count; j++)
3017 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
3021 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
3022 if (!(po->flags & OPF_CJMP))
3025 if (po->flags & OPF_TAIL)
3030 static const struct parsed_proto *try_recover_pp(
3031 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
3033 const struct parsed_proto *pp = NULL;
3037 // maybe an arg of g_func?
3038 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
3040 char ofs_reg[16] = { 0, };
3041 int arg, arg_s, arg_i;
3048 parse_stack_access(po, opr->name, ofs_reg,
3049 &offset, &stack_ra, NULL, 0);
3050 if (ofs_reg[0] != 0)
3051 ferr(po, "offset reg on arg access?\n");
3052 if (offset <= stack_ra) {
3053 // search who set the stack var instead
3054 if (search_instead != NULL)
3055 *search_instead = 1;
3059 arg_i = (offset - stack_ra - 4) / 4;
3060 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
3061 if (g_func_pp->arg[arg].reg != NULL)
3067 if (arg == g_func_pp->argc)
3068 ferr(po, "stack arg %d not in prototype?\n", arg_i);
3070 pp = g_func_pp->arg[arg].fptr;
3072 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
3073 check_func_pp(po, pp, "icall arg");
3075 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
3077 p = strchr(opr->name + 1, '[');
3078 memcpy(buf, opr->name, p - opr->name);
3079 buf[p - opr->name] = 0;
3080 pp = proto_parse(g_fhdr, buf, g_quiet_pp);
3082 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
3083 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
3086 ferr(po, "proto_parse failed for icall to '%s'\n", opr->name);
3089 check_func_pp(po, pp, "reg-fptr ref");
3095 static void scan_for_call_type(int i, const struct parsed_opr *opr,
3096 int magic, const struct parsed_proto **pp_found, int *pp_i,
3099 const struct parsed_proto *pp = NULL;
3100 struct parsed_op *po;
3101 struct label_ref *lr;
3103 ops[i].cc_scratch = magic;
3106 if (g_labels[i] != NULL) {
3107 lr = &g_label_refs[i];
3108 for (; lr != NULL; lr = lr->next) {
3109 check_i(&ops[i], lr->i);
3110 scan_for_call_type(lr->i, opr, magic, pp_found, pp_i, multi);
3112 if (i > 0 && LAST_OP(i - 1))
3120 if (ops[i].cc_scratch == magic)
3122 ops[i].cc_scratch = magic;
3124 if (!(ops[i].flags & OPF_DATA))
3126 if (!is_opr_modified(opr, &ops[i]))
3128 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
3129 // most probably trashed by some processing
3134 opr = &ops[i].operand[1];
3135 if (opr->type != OPT_REG)
3139 po = (i >= 0) ? &ops[i] : ops;
3142 // reached the top - can only be an arg-reg
3143 if (opr->type != OPT_REG || g_func_pp == NULL)
3146 for (i = 0; i < g_func_pp->argc; i++) {
3147 if (g_func_pp->arg[i].reg == NULL)
3149 if (IS(opr->name, g_func_pp->arg[i].reg))
3152 if (i == g_func_pp->argc)
3154 pp = g_func_pp->arg[i].fptr;
3156 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
3157 i + 1, g_func_pp->arg[i].reg);
3158 check_func_pp(po, pp, "icall reg-arg");
3161 pp = try_recover_pp(po, opr, NULL);
3163 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
3164 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
3165 || (*pp_found)->is_stdcall != pp->is_stdcall
3166 || (*pp_found)->is_fptr != pp->is_fptr
3167 || (*pp_found)->argc != pp->argc
3168 || (*pp_found)->argc_reg != pp->argc_reg
3169 || (*pp_found)->argc_stack != pp->argc_stack)
3171 ferr(po, "icall: parsed_proto mismatch\n");
3181 static void add_label_ref(struct label_ref *lr, int op_i)
3183 struct label_ref *lr_new;
3190 lr_new = calloc(1, sizeof(*lr_new));
3192 lr_new->next = lr->next;
3196 static struct parsed_data *try_resolve_jumptab(int i, int opcnt)
3198 struct parsed_op *po = &ops[i];
3199 struct parsed_data *pd;
3200 char label[NAMELEN], *p;
3203 p = strchr(po->operand[0].name, '[');
3207 len = p - po->operand[0].name;
3208 strncpy(label, po->operand[0].name, len);
3211 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3212 if (IS(g_func_pd[j].label, label)) {
3218 //ferr(po, "label '%s' not parsed?\n", label);
3221 if (pd->type != OPT_OFFSET)
3222 ferr(po, "label '%s' with non-offset data?\n", label);
3224 // find all labels, link
3225 for (j = 0; j < pd->count; j++) {
3226 for (l = 0; l < opcnt; l++) {
3227 if (g_labels[l] != NULL && IS(g_labels[l], pd->d[j].u.label)) {
3228 add_label_ref(&g_label_refs[l], i);
3238 static void clear_labels(int count)
3242 for (i = 0; i < count; i++) {
3243 if (g_labels[i] != NULL) {
3250 static int get_pp_arg_regmask_src(const struct parsed_proto *pp)
3255 for (i = 0; i < pp->argc; i++) {
3256 if (pp->arg[i].reg != NULL) {
3257 reg = char_array_i(regs_r32,
3258 ARRAY_SIZE(regs_r32), pp->arg[i].reg);
3260 ferr(ops, "arg '%s' of func '%s' is not a reg?\n",
3261 pp->arg[i].reg, pp->name);
3262 regmask |= 1 << reg;
3269 static int get_pp_arg_regmask_dst(const struct parsed_proto *pp)
3271 if (strstr(pp->ret_type.name, "int64"))
3272 return (1 << xAX) | (1 << xDX);
3273 if (strcasecmp(pp->ret_type.name, "void") == 0)
3279 static void resolve_branches_parse_calls(int opcnt)
3281 const struct parsed_proto *pp_c;
3282 struct parsed_proto *pp;
3283 struct parsed_data *pd;
3284 struct parsed_op *po;
3285 const char *tmpname;
3289 for (i = 0; i < opcnt; i++)
3295 if (po->op == OP_CALL) {
3298 if (po->operand[0].type == OPT_LABEL) {
3299 tmpname = opr_name(po, 0);
3300 if (IS_START(tmpname, "loc_"))
3301 ferr(po, "call to loc_*\n");
3302 pp_c = proto_parse(g_fhdr, tmpname, g_header_mode);
3303 if (!g_header_mode && pp_c == NULL)
3304 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3307 pp = proto_clone(pp_c);
3308 my_assert_not(pp, NULL);
3311 else if (po->datap != NULL) {
3312 pp = calloc(1, sizeof(*pp));
3313 my_assert_not(pp, NULL);
3315 ret = parse_protostr(po->datap, pp);
3317 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3324 check_func_pp(po, pp, "fptr var call");
3325 if (pp->is_noreturn)
3326 po->flags |= OPF_TAIL;
3332 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3335 if (po->operand[0].type == OPT_REGMEM) {
3336 pd = try_resolve_jumptab(i, opcnt);
3344 for (l = 0; l < opcnt; l++) {
3345 if (g_labels[l] != NULL
3346 && IS(po->operand[0].name, g_labels[l]))
3348 if (l == i + 1 && po->op == OP_JMP) {
3349 // yet another alignment type..
3350 po->flags |= OPF_RMD|OPF_DONE;
3353 add_label_ref(&g_label_refs[l], i);
3359 if (po->bt_i != -1 || (po->flags & OPF_RMD))
3362 if (po->operand[0].type == OPT_LABEL)
3366 ferr(po, "unhandled branch\n");
3370 po->flags |= OPF_TAIL;
3371 if (i > 0 && ops[i - 1].op == OP_POP)
3372 po->flags |= OPF_ATAIL;
3377 static void scan_prologue_epilogue(int opcnt)
3379 int ecx_push = 0, esp_sub = 0;
3383 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
3384 && ops[1].op == OP_MOV
3385 && IS(opr_name(&ops[1], 0), "ebp")
3386 && IS(opr_name(&ops[1], 1), "esp"))
3389 ops[0].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3390 ops[1].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3393 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
3394 g_stack_fsz = opr_const(&ops[2], 1);
3395 ops[2].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3399 // another way msvc builds stack frame..
3401 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3403 ops[i].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3407 // and another way..
3408 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
3409 && ops[i].operand[1].type == OPT_CONST
3410 && ops[i + 1].op == OP_CALL
3411 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
3413 g_stack_fsz += ops[i].operand[1].val;
3414 ops[i].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3416 ops[i].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3423 for (; i < opcnt; i++)
3424 if (ops[i].flags & OPF_TAIL)
3427 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3428 if (ops[j].bt_i != -1 || ops[j].btj != NULL)
3434 if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
3435 || ops[j].op == OP_LEAVE)
3437 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3439 else if (ops[i].op == OP_CALL && ops[i].pp != NULL
3440 && ops[i].pp->is_noreturn)
3442 // on noreturn, msvc sometimes cleans stack, sometimes not
3447 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3448 ferr(&ops[j], "'pop ebp' expected\n");
3450 if (g_stack_fsz != 0) {
3451 if (ops[j].op == OP_LEAVE)
3453 else if (ops[j].op == OP_POP
3454 && ops[j - 1].op == OP_MOV
3455 && IS(opr_name(&ops[j - 1], 0), "esp")
3456 && IS(opr_name(&ops[j - 1], 1), "ebp"))
3458 ops[j - 1].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3461 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3463 ferr(&ops[j], "esp restore expected\n");
3466 if (ecx_push && j >= 0 && ops[j].op == OP_POP
3467 && IS(opr_name(&ops[j], 0), "ecx"))
3469 ferr(&ops[j], "unexpected ecx pop\n");
3475 } while (i < opcnt);
3478 ferr(ops, "missing ebp epilogue\n");
3484 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3485 ops[i].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3491 for (; i < opcnt; i++) {
3492 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
3494 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
3495 && ops[i].operand[1].type == OPT_CONST)
3497 g_stack_fsz = ops[i].operand[1].val;
3498 ops[i].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3504 if (ecx_push && !esp_sub) {
3505 // could actually be args for a call..
3506 for (; i < opcnt; i++)
3507 if (ops[i].op != OP_PUSH)
3510 if (ops[i].op == OP_CALL && ops[i].operand[0].type == OPT_LABEL) {
3511 const struct parsed_proto *pp;
3512 pp = proto_parse(g_fhdr, opr_name(&ops[i], 0), 1);
3513 j = pp ? pp->argc_stack : 0;
3514 while (i > 0 && j > 0) {
3516 if (ops[i].op == OP_PUSH) {
3517 ops[i].flags &= ~(OPF_RMD | OPF_DONE | OPF_NOREGS);
3522 ferr(&ops[i], "unhandled prologue\n");
3525 i = g_stack_fsz = ecx_push = 0;
3526 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3527 if (!(ops[i].flags & OPF_RMD))
3537 if (ecx_push || esp_sub)
3543 for (; i < opcnt; i++)
3544 if (ops[i].flags & OPF_TAIL)
3547 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3548 if (ops[j].bt_i != -1 || ops[j].btj != NULL)
3555 for (l = 0; l < ecx_push; l++) {
3556 if (ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ecx"))
3558 else if (ops[j].op == OP_ADD
3559 && IS(opr_name(&ops[j], 0), "esp")
3560 && ops[j].operand[1].type == OPT_CONST)
3563 l += ops[j].operand[1].val / 4 - 1;
3566 ferr(&ops[j], "'pop ecx' expected\n");
3568 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3572 ferr(&ops[j], "epilogue scan failed\n");
3578 if (ops[j].op != OP_ADD
3579 || !IS(opr_name(&ops[j], 0), "esp")
3580 || ops[j].operand[1].type != OPT_CONST
3581 || ops[j].operand[1].val != g_stack_fsz)
3582 ferr(&ops[j], "'add esp' expected\n");
3584 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_NOREGS;
3585 ops[j].operand[1].val = 0; // hack for stack arg scanner
3590 } while (i < opcnt);
3593 ferr(ops, "missing esp epilogue\n");
3597 static const struct parsed_proto *resolve_icall(int i, int opcnt,
3598 int *pp_i, int *multi_src)
3600 const struct parsed_proto *pp = NULL;
3601 int search_advice = 0;
3606 switch (ops[i].operand[0].type) {
3610 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
3615 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
3623 // find an instruction that changed opr before i op
3624 // *op_i must be set to -1 by the caller
3625 // *entry is set to 1 if one source is determined to be the caller
3626 // returns 1 if found, *op_i is then set to origin
3627 static int resolve_origin(int i, const struct parsed_opr *opr,
3628 int magic, int *op_i, int *is_caller)
3630 struct label_ref *lr;
3633 if (ops[i].cc_scratch == magic)
3635 ops[i].cc_scratch = magic;
3638 if (g_labels[i] != NULL) {
3639 lr = &g_label_refs[i];
3640 for (; lr != NULL; lr = lr->next) {
3641 check_i(&ops[i], lr->i);
3642 ret |= resolve_origin(lr->i, opr, magic, op_i, is_caller);
3644 if (i > 0 && LAST_OP(i - 1))
3650 if (is_caller != NULL)
3655 if (ops[i].cc_scratch == magic)
3657 ops[i].cc_scratch = magic;
3659 if (!(ops[i].flags & OPF_DATA))
3661 if (!is_opr_modified(opr, &ops[i]))
3668 // XXX: could check if the other op does the same
3677 // find an instruction that previously referenced opr
3678 // if multiple results are found - fail
3679 // *op_i must be set to -1 by the caller
3680 // returns 1 if found, *op_i is then set to referencer insn
3681 static int resolve_last_ref(int i, const struct parsed_opr *opr,
3682 int magic, int *op_i)
3684 struct label_ref *lr;
3687 if (ops[i].cc_scratch == magic)
3689 ops[i].cc_scratch = magic;
3692 if (g_labels[i] != NULL) {
3693 lr = &g_label_refs[i];
3694 for (; lr != NULL; lr = lr->next) {
3695 check_i(&ops[i], lr->i);
3696 ret |= resolve_last_ref(lr->i, opr, magic, op_i);
3698 if (i > 0 && LAST_OP(i - 1))
3706 if (ops[i].cc_scratch == magic)
3708 ops[i].cc_scratch = magic;
3710 if (!is_opr_referenced(opr, &ops[i]))
3721 // find next instruction that reads opr
3722 // *op_i must be set to -1 by the caller
3723 // on return, *op_i is set to first referencer insn
3724 // returns 1 if exactly 1 referencer is found
3725 static int find_next_read(int i, int opcnt,
3726 const struct parsed_opr *opr, int magic, int *op_i)
3728 struct parsed_op *po;
3731 for (; i < opcnt; i++)
3733 if (ops[i].cc_scratch == magic)
3735 ops[i].cc_scratch = magic;
3738 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
3739 if (po->btj != NULL) {
3741 for (j = 0; j < po->btj->count; j++) {
3742 check_i(po, po->btj->d[j].bt_i);
3743 ret |= find_next_read(po->btj->d[j].bt_i, opcnt, opr,
3749 if (po->flags & OPF_RMD)
3751 check_i(po, po->bt_i);
3752 if (po->flags & OPF_CJMP) {
3753 ret |= find_next_read(po->bt_i, opcnt, opr, magic, op_i);
3762 if (!is_opr_read(opr, po)) {
3763 if (is_opr_modified(opr, po)
3764 && (po->op == OP_CALL
3765 || ((po->flags & OPF_DATA)
3766 && po->operand[0].lmod == OPLM_DWORD)))
3771 if (po->flags & OPF_TAIL)
3786 static int try_resolve_const(int i, const struct parsed_opr *opr,
3787 int magic, unsigned int *val)
3792 ret = resolve_origin(i, opr, magic, &s_i, NULL);
3795 if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
3798 *val = ops[i].operand[1].val;
3805 static struct parsed_proto *process_call_early(int i, int opcnt,
3808 struct parsed_op *po = &ops[i];
3809 struct parsed_proto *pp;
3815 if (pp == NULL || pp->is_vararg || pp->argc_reg != 0)
3819 // look for and make use of esp adjust
3821 if (!pp->is_stdcall && pp->argc_stack > 0)
3822 ret = scan_for_esp_adjust(i + 1, opcnt,
3823 pp->argc_stack * 4, &adj, &multipath, 0);
3825 if (pp->argc_stack > adj / 4)
3829 if (ops[ret].op == OP_POP) {
3830 for (j = 1; j < adj / 4; j++) {
3831 if (ops[ret + j].op != OP_POP
3832 || ops[ret + j].operand[0].reg != xCX)
3844 static struct parsed_proto *process_call(int i, int opcnt)
3846 struct parsed_op *po = &ops[i];
3847 const struct parsed_proto *pp_c;
3848 struct parsed_proto *pp;
3849 const char *tmpname;
3850 int call_i = -1, ref_i = -1;
3851 int adj = 0, multipath = 0;
3854 tmpname = opr_name(po, 0);
3859 pp_c = resolve_icall(i, opcnt, &call_i, &multipath);
3861 if (!pp_c->is_func && !pp_c->is_fptr)
3862 ferr(po, "call to non-func: %s\n", pp_c->name);
3863 pp = proto_clone(pp_c);
3864 my_assert_not(pp, NULL);
3866 // not resolved just to single func
3869 switch (po->operand[0].type) {
3871 // we resolved this call and no longer need the register
3872 po->regmask_src &= ~(1 << po->operand[0].reg);
3874 if (!multipath && i != call_i && ops[call_i].op == OP_MOV
3875 && ops[call_i].operand[1].type == OPT_LABEL)
3877 // no other source users?
3878 ret = resolve_last_ref(i, &po->operand[0], i + opcnt * 10,
3880 if (ret == 1 && call_i == ref_i) {
3881 // and nothing uses it after us?
3883 find_next_read(i + 1, opcnt, &po->operand[0],
3884 i + opcnt * 11, &ref_i);
3886 // then also don't need the source mov
3887 ops[call_i].flags |= OPF_RMD | OPF_NOREGS;
3899 pp = calloc(1, sizeof(*pp));
3900 my_assert_not(pp, NULL);
3903 ret = scan_for_esp_adjust(i + 1, opcnt,
3904 -1, &adj, &multipath, 0);
3905 if (ret < 0 || adj < 0) {
3906 if (!g_allow_regfunc)
3907 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3908 pp->is_unresolved = 1;
3912 if (adj > ARRAY_SIZE(pp->arg))
3913 ferr(po, "esp adjust too large: %d\n", adj);
3914 pp->ret_type.name = strdup("int");
3915 pp->argc = pp->argc_stack = adj;
3916 for (arg = 0; arg < pp->argc; arg++)
3917 pp->arg[arg].type.name = strdup("int");
3922 // look for and make use of esp adjust
3925 if (!pp->is_stdcall && pp->argc_stack > 0) {
3926 int adj_expect = pp->is_vararg ? -1 : pp->argc_stack * 4;
3927 ret = scan_for_esp_adjust(i + 1, opcnt,
3928 adj_expect, &adj, &multipath, 0);
3931 if (pp->is_vararg) {
3932 if (adj / 4 < pp->argc_stack) {
3933 fnote(po, "(this call)\n");
3934 ferr(&ops[ret], "esp adjust is too small: %x < %x\n",
3935 adj, pp->argc_stack * 4);
3937 // modify pp to make it have varargs as normal args
3939 pp->argc += adj / 4 - pp->argc_stack;
3940 for (; arg < pp->argc; arg++) {
3941 pp->arg[arg].type.name = strdup("int");
3944 if (pp->argc > ARRAY_SIZE(pp->arg))
3945 ferr(po, "too many args for '%s'\n", tmpname);
3947 if (pp->argc_stack > adj / 4) {
3948 fnote(po, "(this call)\n");
3949 ferr(&ops[ret], "stack tracking failed for '%s': %x %x\n",
3950 tmpname, pp->argc_stack * 4, adj);
3953 scan_for_esp_adjust(i + 1, opcnt,
3954 pp->argc_stack * 4, &adj, &multipath, 1);
3956 else if (pp->is_vararg)
3957 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3963 static int collect_call_args_early(struct parsed_op *po, int i,
3964 struct parsed_proto *pp, int *regmask)
3969 for (arg = 0; arg < pp->argc; arg++)
3970 if (pp->arg[arg].reg == NULL)
3973 // first see if it can be easily done
3974 for (j = i; j > 0 && arg < pp->argc; )
3976 if (g_labels[j] != NULL)
3980 if (ops[j].op == OP_CALL)
3982 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP)
3984 else if (ops[j].op == OP_POP)
3986 else if (ops[j].flags & OPF_CJMP)
3988 else if (ops[j].op == OP_PUSH) {
3989 if (ops[j].flags & (OPF_FARG|OPF_FARGNR))
3991 ret = scan_for_mod(&ops[j], j + 1, i, 1);
3995 if (pp->arg[arg].type.is_va_list)
3999 for (arg++; arg < pp->argc; arg++)
4000 if (pp->arg[arg].reg == NULL)
4009 for (arg = 0; arg < pp->argc; arg++)
4010 if (pp->arg[arg].reg == NULL)
4013 for (j = i; j > 0 && arg < pp->argc; )
4017 if (ops[j].op == OP_PUSH)
4019 ops[j].p_argnext = -1;
4020 ferr_assert(&ops[j], pp->arg[arg].datap == NULL);
4021 pp->arg[arg].datap = &ops[j];
4023 if (ops[j].operand[0].type == OPT_REG)
4024 *regmask |= 1 << ops[j].operand[0].reg;
4026 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_FARGNR | OPF_FARG;
4027 ops[j].flags &= ~OPF_RSAVE;
4030 for (arg++; arg < pp->argc; arg++)
4031 if (pp->arg[arg].reg == NULL)
4039 static int collect_call_args_r(struct parsed_op *po, int i,
4040 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
4041 int *arg_grp, int arg, int magic, int need_op_saving, int may_reuse)
4043 struct parsed_proto *pp_tmp;
4044 struct parsed_op *po_tmp;
4045 struct label_ref *lr;
4046 int need_to_save_current;
4047 int arg_grp_current = 0;
4048 int save_args_seen = 0;
4056 ferr(po, "dead label encountered\n");
4060 for (; arg < pp->argc; arg++)
4061 if (pp->arg[arg].reg == NULL)
4063 magic = (magic & 0xffffff) | (arg << 24);
4065 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
4067 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
4068 if (ops[j].cc_scratch != magic) {
4069 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
4073 // ok: have already been here
4076 ops[j].cc_scratch = magic;
4078 if (g_labels[j] != NULL && g_label_refs[j].i != -1) {
4079 lr = &g_label_refs[j];
4080 if (lr->next != NULL)
4082 for (; lr->next; lr = lr->next) {
4083 check_i(&ops[j], lr->i);
4084 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
4086 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
4087 arg_grp, arg, magic, need_op_saving, may_reuse);
4092 check_i(&ops[j], lr->i);
4093 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
4095 if (j > 0 && LAST_OP(j - 1)) {
4096 // follow last branch in reverse
4101 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
4102 arg_grp, arg, magic, need_op_saving, may_reuse);
4108 if (ops[j].op == OP_CALL)
4110 if (pp->is_unresolved)
4115 ferr(po, "arg collect hit unparsed call '%s'\n",
4116 ops[j].operand[0].name);
4117 if (may_reuse && pp_tmp->argc_stack > 0)
4118 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
4119 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
4121 // esp adjust of 0 means we collected it before
4122 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP
4123 && (ops[j].operand[1].type != OPT_CONST
4124 || ops[j].operand[1].val != 0))
4126 if (pp->is_unresolved)
4129 fnote(po, "(this call)\n");
4130 ferr(&ops[j], "arg collect %d/%d hit esp adjust of %d\n",
4131 arg, pp->argc, ops[j].operand[1].val);
4133 else if (ops[j].op == OP_POP && !(ops[j].flags & OPF_DONE))
4135 if (pp->is_unresolved)
4138 fnote(po, "(this call)\n");
4139 ferr(&ops[j], "arg collect %d/%d hit pop\n", arg, pp->argc);
4141 else if (ops[j].flags & OPF_CJMP)
4143 if (pp->is_unresolved)
4148 else if (ops[j].op == OP_PUSH
4149 && !(ops[j].flags & (OPF_FARGNR|OPF_DONE)))
4151 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
4154 ops[j].p_argnext = -1;
4155 po_tmp = pp->arg[arg].datap;
4157 ops[j].p_argnext = po_tmp - ops;
4158 pp->arg[arg].datap = &ops[j];
4160 need_to_save_current = 0;
4163 if (ops[j].operand[0].type == OPT_REG)
4164 reg = ops[j].operand[0].reg;
4166 if (!need_op_saving) {
4167 ret = scan_for_mod(&ops[j], j + 1, i, 1);
4168 need_to_save_current = (ret >= 0);
4170 if (need_op_saving || need_to_save_current) {
4171 // mark this push as one that needs operand saving
4172 ops[j].flags &= ~OPF_RMD;
4173 if (ops[j].p_argnum == 0) {
4174 ops[j].p_argnum = arg + 1;
4175 save_args |= 1 << arg;
4177 else if (ops[j].p_argnum < arg + 1) {
4178 // XXX: might kill valid var..
4179 //*save_arg_vars &= ~(1 << (ops[j].p_argnum - 1));
4180 ops[j].p_argnum = arg + 1;
4181 save_args |= 1 << arg;
4184 if (save_args_seen & (1 << (ops[j].p_argnum - 1))) {
4187 if (arg_grp_current >= MAX_ARG_GRP)
4188 ferr(&ops[j], "out of arg groups (arg%d), f %s\n",
4189 ops[j].p_argnum, pp->name);
4192 else if (ops[j].p_argnum == 0)
4193 ops[j].flags |= OPF_RMD;
4195 // some PUSHes are reused by different calls on other branches,
4196 // but that can't happen if we didn't branch, so they
4197 // can be removed from future searches (handles nested calls)
4199 ops[j].flags |= OPF_FARGNR;
4201 ops[j].flags |= OPF_FARG;
4202 ops[j].flags &= ~OPF_RSAVE;
4204 // check for __VALIST
4205 if (!pp->is_unresolved && g_func_pp != NULL
4206 && pp->arg[arg].type.is_va_list)
4209 ret = resolve_origin(j, &ops[j].operand[0],
4210 magic + 1, &k, NULL);
4211 if (ret == 1 && k >= 0)
4213 if (ops[k].op == OP_LEA) {
4214 if (!g_func_pp->is_vararg)
4215 ferr(&ops[k], "lea <arg> used, but %s is not vararg?\n",
4218 snprintf(buf, sizeof(buf), "arg_%X",
4219 g_func_pp->argc_stack * 4);
4220 if (strstr(ops[k].operand[1].name, buf)
4221 || strstr(ops[k].operand[1].name, "arglist"))
4223 ops[k].flags |= OPF_RMD | OPF_NOREGS | OPF_DONE;
4224 ops[j].flags |= OPF_RMD | OPF_NOREGS | OPF_VAPUSH;
4225 save_args &= ~(1 << arg);
4229 ferr(&ops[k], "va_list arg detection failed\n");
4231 // check for va_list from g_func_pp arg too
4232 else if (ops[k].op == OP_MOV
4233 && is_stack_access(&ops[k], &ops[k].operand[1]))
4235 ret = stack_frame_access(&ops[k], &ops[k].operand[1],
4236 buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
4238 ops[k].flags |= OPF_RMD | OPF_DONE;
4239 ops[j].flags |= OPF_RMD;
4240 ops[j].p_argpass = ret + 1;
4241 save_args &= ~(1 << arg);
4248 *save_arg_vars |= save_args;
4250 // tracking reg usage
4252 *regmask |= 1 << reg;
4255 if (!pp->is_unresolved) {
4257 for (; arg < pp->argc; arg++)
4258 if (pp->arg[arg].reg == NULL)
4261 magic = (magic & 0xffffff) | (arg << 24);
4264 if (ops[j].p_arggrp > arg_grp_current) {
4266 arg_grp_current = ops[j].p_arggrp;
4268 if (ops[j].p_argnum > 0)
4269 save_args_seen |= 1 << (ops[j].p_argnum - 1);
4272 if (arg < pp->argc) {
4273 ferr(po, "arg collect failed for '%s': %d/%d\n",
4274 pp->name, arg, pp->argc);
4278 if (arg_grp_current > *arg_grp)
4279 *arg_grp = arg_grp_current;
4284 static int collect_call_args(struct parsed_op *po, int i,
4285 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
4288 // arg group is for cases when pushes for
4289 // multiple funcs are going on
4290 struct parsed_op *po_tmp;
4291 int save_arg_vars_current = 0;
4296 ret = collect_call_args_r(po, i, pp, regmask,
4297 &save_arg_vars_current, &arg_grp, 0, magic, 0, 0);
4302 // propagate arg_grp
4303 for (a = 0; a < pp->argc; a++) {
4304 if (pp->arg[a].reg != NULL)
4307 po_tmp = pp->arg[a].datap;
4308 while (po_tmp != NULL) {
4309 po_tmp->p_arggrp = arg_grp;
4310 if (po_tmp->p_argnext > 0)
4311 po_tmp = &ops[po_tmp->p_argnext];
4317 save_arg_vars[arg_grp] |= save_arg_vars_current;
4319 if (pp->is_unresolved) {
4321 pp->argc_stack += ret;
4322 for (a = 0; a < pp->argc; a++)
4323 if (pp->arg[a].type.name == NULL)
4324 pp->arg[a].type.name = strdup("int");
4330 static void reg_use_pass(int i, int opcnt, unsigned char *cbits,
4331 int regmask_now, int *regmask,
4332 int regmask_save_now, int *regmask_save,
4333 int *regmask_init, int regmask_arg)
4335 struct parsed_op *po;
4343 for (; i < opcnt; i++)
4346 if (cbits[i >> 3] & (1 << (i & 7)))
4348 cbits[i >> 3] |= (1 << (i & 7));
4350 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
4351 if (po->flags & (OPF_RMD|OPF_DONE))
4353 if (po->btj != NULL) {
4354 for (j = 0; j < po->btj->count; j++) {
4355 check_i(po, po->btj->d[j].bt_i);
4356 reg_use_pass(po->btj->d[j].bt_i, opcnt, cbits,
4357 regmask_now, regmask, regmask_save_now, regmask_save,
4358 regmask_init, regmask_arg);
4363 check_i(po, po->bt_i);
4364 if (po->flags & OPF_CJMP)
4365 reg_use_pass(po->bt_i, opcnt, cbits,
4366 regmask_now, regmask, regmask_save_now, regmask_save,
4367 regmask_init, regmask_arg);
4373 if (po->op == OP_PUSH && !(po->flags & (OPF_FARG|OPF_DONE))
4374 && !g_func_pp->is_userstack
4375 && po->operand[0].type == OPT_REG)
4377 reg = po->operand[0].reg;
4378 ferr_assert(po, reg >= 0);
4381 flags_set = OPF_RSAVE | OPF_RMD | OPF_DONE;
4382 if (regmask_now & (1 << reg)) {
4383 already_saved = regmask_save_now & (1 << reg);
4384 flags_set = OPF_RSAVE | OPF_DONE;
4387 ret = scan_for_pop(i + 1, opcnt, i + opcnt * 3, reg, 0, 0);
4389 scan_for_pop(i + 1, opcnt, i + opcnt * 4, reg, 0, flags_set);
4392 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg, 0);
4394 scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg,
4399 ferr_assert(po, !already_saved);
4400 po->flags |= flags_set;
4402 if (regmask_now & (1 << reg)) {
4403 regmask_save_now |= (1 << reg);
4404 *regmask_save |= regmask_save_now;
4409 else if (po->op == OP_POP && (po->flags & OPF_RSAVE)) {
4410 reg = po->operand[0].reg;
4411 ferr_assert(po, reg >= 0);
4413 if (regmask_save_now & (1 << reg))
4414 regmask_save_now &= ~(1 << reg);
4416 regmask_now &= ~(1 << reg);
4419 else if (po->op == OP_CALL) {
4420 if ((po->regmask_dst & (1 << xAX))
4421 && !(po->regmask_dst & (1 << xDX)))
4423 if (po->flags & OPF_TAIL)
4424 // don't need eax, will do "return f();" or "f(); return;"
4425 po->regmask_dst &= ~(1 << xAX);
4427 struct parsed_opr opr = OPR_INIT(OPT_REG, OPLM_DWORD, xAX);
4429 find_next_read(i + 1, opcnt, &opr, i + opcnt * 17, &j);
4432 po->regmask_dst &= ~(1 << xAX);
4437 if (po->flags & OPF_NOREGS)
4440 // if incomplete register is used, clear it on init to avoid
4441 // later use of uninitialized upper part in some situations
4442 if ((po->flags & OPF_DATA) && po->operand[0].type == OPT_REG
4443 && po->operand[0].lmod != OPLM_DWORD)
4445 reg = po->operand[0].reg;
4446 ferr_assert(po, reg >= 0);
4448 if (!(regmask_now & (1 << reg)))
4449 *regmask_init |= 1 << reg;
4452 regmask_op = po->regmask_src | po->regmask_dst;
4454 regmask_new = po->regmask_src & ~regmask_now & ~regmask_arg;
4455 regmask_new &= ~(1 << xSP);
4456 if (g_bp_frame && !(po->flags & OPF_EBP_S))
4457 regmask_new &= ~(1 << xBP);
4459 if (po->op == OP_CALL) {
4460 // allow fastcall calls from anywhere, calee may be also sitting
4461 // in some fastcall table even when it's not using reg args
4462 if (regmask_new & po->regmask_src & (1 << xCX)) {
4463 *regmask_init |= (1 << xCX);
4464 regmask_now |= (1 << xCX);
4465 regmask_new &= ~(1 << xCX);
4467 if (regmask_new & po->regmask_src & (1 << xDX)) {
4468 *regmask_init |= (1 << xDX);
4469 regmask_now |= (1 << xDX);
4470 regmask_new &= ~(1 << xDX);
4474 if (regmask_new != 0)
4475 fnote(po, "uninitialized reg mask: %x\n", regmask_new);
4477 if (regmask_op & (1 << xBP)) {
4478 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
4479 if (po->regmask_dst & (1 << xBP))
4480 // compiler decided to drop bp frame and use ebp as scratch
4481 scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
4483 regmask_op &= ~(1 << xBP);
4487 regmask_now |= regmask_op;
4488 *regmask |= regmask_now;
4490 if (po->flags & OPF_TAIL)
4495 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
4499 for (i = 0; i < pp->argc; i++)
4500 if (pp->arg[i].reg == NULL)
4504 memmove(&pp->arg[i + 1], &pp->arg[i],
4505 sizeof(pp->arg[0]) * pp->argc_stack);
4506 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
4507 pp->arg[i].reg = strdup(reg);
4508 pp->arg[i].type.name = strdup("int");
4513 static void output_std_flags(FILE *fout, struct parsed_op *po,
4514 int *pfomask, const char *dst_opr_text)
4516 if (*pfomask & (1 << PFO_Z)) {
4517 fprintf(fout, "\n cond_z = (%s%s == 0);",
4518 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
4519 *pfomask &= ~(1 << PFO_Z);
4521 if (*pfomask & (1 << PFO_S)) {
4522 fprintf(fout, "\n cond_s = (%s%s < 0);",
4523 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
4524 *pfomask &= ~(1 << PFO_S);
4529 OPP_FORCE_NORETURN = (1 << 0),
4530 OPP_SIMPLE_ARGS = (1 << 1),
4531 OPP_ALIGN = (1 << 2),
4534 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
4537 const char *cconv = "";
4539 if (pp->is_fastcall)
4540 cconv = "__fastcall ";
4541 else if (pp->is_stdcall && pp->argc_reg == 0)
4542 cconv = "__stdcall ";
4544 fprintf(fout, (flags & OPP_ALIGN) ? "%-16s" : "%s", cconv);
4546 if (pp->is_noreturn || (flags & OPP_FORCE_NORETURN))
4547 fprintf(fout, "noreturn ");
4550 static void output_pp(FILE *fout, const struct parsed_proto *pp,
4555 fprintf(fout, (flags & OPP_ALIGN) ? "%-5s" : "%s ",
4559 output_pp_attrs(fout, pp, flags);
4562 fprintf(fout, "%s", pp->name);
4567 for (i = 0; i < pp->argc; i++) {
4569 fprintf(fout, ", ");
4570 if (pp->arg[i].fptr != NULL && !(flags & OPP_SIMPLE_ARGS)) {
4572 output_pp(fout, pp->arg[i].fptr, 0);
4574 else if (pp->arg[i].type.is_retreg) {
4575 fprintf(fout, "u32 *r_%s", pp->arg[i].reg);
4578 fprintf(fout, "%s", pp->arg[i].type.name);
4580 fprintf(fout, " a%d", i + 1);
4583 if (pp->is_vararg) {
4585 fprintf(fout, ", ");
4586 fprintf(fout, "...");
4591 static char *saved_arg_name(char *buf, size_t buf_size, int grp, int num)
4597 snprintf(buf1, sizeof(buf1), "%d", grp);
4598 snprintf(buf, buf_size, "s%s_a%d", buf1, num);
4603 static void gen_x_cleanup(int opcnt);
4605 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
4607 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
4608 struct parsed_opr *last_arith_dst = NULL;
4609 char buf1[256], buf2[256], buf3[256], cast[64];
4610 struct parsed_proto *pp, *pp_tmp;
4611 struct parsed_data *pd;
4613 int save_arg_vars[MAX_ARG_GRP] = { 0, };
4614 unsigned char cbits[MAX_OPS / 8];
4616 int need_tmp_var = 0;
4619 int label_pending = 0;
4620 int regmask_save = 0; // regs saved/restored in this func
4621 int regmask_arg; // regs from this function args (fastcall, etc)
4622 int regmask_ret; // regs needed on ret
4623 int regmask_now; // temp
4624 int regmask_init = 0; // regs that need zero initialization
4625 int regmask_pp = 0; // regs used in complex push-pop graph
4626 int regmask = 0; // used regs
4635 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
4636 g_stack_frame_used = 0;
4638 g_func_pp = proto_parse(fhdr, funcn, 0);
4639 if (g_func_pp == NULL)
4640 ferr(ops, "proto_parse failed for '%s'\n", funcn);
4642 regmask_arg = get_pp_arg_regmask_src(g_func_pp);
4643 regmask_ret = get_pp_arg_regmask_dst(g_func_pp);
4645 if (g_func_pp->has_retreg) {
4646 for (arg = 0; arg < g_func_pp->argc; arg++) {
4647 if (g_func_pp->arg[arg].type.is_retreg) {
4648 reg = char_array_i(regs_r32,
4649 ARRAY_SIZE(regs_r32), g_func_pp->arg[arg].reg);
4650 ferr_assert(ops, reg >= 0);
4651 regmask_ret |= 1 << reg;
4657 // - resolve all branches
4658 // - parse calls with labels
4659 resolve_branches_parse_calls(opcnt);
4662 // - handle ebp/esp frame, remove ops related to it
4663 scan_prologue_epilogue(opcnt);
4666 // - remove dead labels
4667 // - set regs needed at ret
4668 for (i = 0; i < opcnt; i++)
4670 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
4675 if (ops[i].op == OP_RET)
4676 ops[i].regmask_src |= regmask_ret;
4680 // - process trivial calls
4681 for (i = 0; i < opcnt; i++)
4684 if (po->flags & (OPF_RMD|OPF_DONE))
4687 if (po->op == OP_CALL)
4689 pp = process_call_early(i, opcnt, &j);
4691 if (!(po->flags & OPF_ATAIL))
4692 // since we know the args, try to collect them
4693 if (collect_call_args_early(po, i, pp, ®mask) != 0)
4699 // commit esp adjust
4700 if (ops[j].op != OP_POP)
4701 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
4703 for (l = 0; l < pp->argc_stack; l++)
4704 ops[j + l].flags |= OPF_DONE | OPF_RMD | OPF_NOREGS;
4708 if (strstr(pp->ret_type.name, "int64"))
4711 po->flags |= OPF_DONE;
4717 // - process calls, stage 2
4718 // - handle some push/pop pairs
4719 // - scan for STD/CLD, propagate DF
4720 for (i = 0; i < opcnt; i++)
4723 if (po->flags & OPF_RMD)
4726 if (po->op == OP_CALL)
4728 if (!(po->flags & OPF_DONE)) {
4729 pp = process_call(i, opcnt);
4731 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
4732 // since we know the args, collect them
4733 collect_call_args(po, i, pp, ®mask, save_arg_vars,
4736 // for unresolved, collect after other passes
4740 ferr_assert(po, pp != NULL);
4742 po->regmask_src |= get_pp_arg_regmask_src(pp);
4743 po->regmask_dst |= get_pp_arg_regmask_dst(pp);
4745 if (strstr(pp->ret_type.name, "int64"))
4751 if (po->flags & OPF_DONE)
4754 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4755 && !(po->flags & OPF_RSAVE) && po->operand[0].type == OPT_CONST)
4757 scan_for_pop_const(i, opcnt, i + opcnt * 12);
4759 else if (po->op == OP_POP)
4760 scan_pushes_for_pop(i, opcnt, ®mask_pp);
4761 else if (po->op == OP_STD) {
4762 po->flags |= OPF_DF | OPF_RMD | OPF_DONE;
4763 scan_propagate_df(i + 1, opcnt);
4768 // - find POPs for PUSHes, rm both
4769 // - scan for all used registers
4770 memset(cbits, 0, sizeof(cbits));
4771 reg_use_pass(0, opcnt, cbits, 0, ®mask,
4772 0, ®mask_save, ®mask_init, regmask_arg);
4775 // - find flag set ops for their users
4776 // - do unresolved calls
4777 // - declare indirect functions
4778 for (i = 0; i < opcnt; i++)
4781 if (po->flags & (OPF_RMD|OPF_DONE))
4784 if (po->flags & OPF_CC)
4786 int setters[16], cnt = 0, branched = 0;
4788 ret = scan_for_flag_set(i, i + opcnt * 6,
4789 &branched, setters, &cnt);
4790 if (ret < 0 || cnt <= 0)
4791 ferr(po, "unable to trace flag setter(s)\n");
4792 if (cnt > ARRAY_SIZE(setters))
4793 ferr(po, "too many flag setters\n");
4795 for (j = 0; j < cnt; j++)
4797 tmp_op = &ops[setters[j]]; // flag setter
4800 // to get nicer code, we try to delay test and cmp;
4801 // if we can't because of operand modification, or if we
4802 // have arith op, or branch, make it calculate flags explicitly
4803 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
4805 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
4806 pfomask = 1 << po->pfo;
4808 else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
4809 pfomask = 1 << po->pfo;
4812 // see if we'll be able to handle based on op result
4813 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
4814 && po->pfo != PFO_Z && po->pfo != PFO_S
4815 && po->pfo != PFO_P)
4817 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
4819 pfomask = 1 << po->pfo;
4822 if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
4823 propagate_lmod(tmp_op, &tmp_op->operand[0],
4824 &tmp_op->operand[1]);
4825 if (tmp_op->operand[0].lmod == OPLM_DWORD)
4830 tmp_op->pfomask |= pfomask;
4831 cond_vars |= pfomask;
4833 // note: may overwrite, currently not a problem
4837 if (po->op == OP_RCL || po->op == OP_RCR
4838 || po->op == OP_ADC || po->op == OP_SBB)
4839 cond_vars |= 1 << PFO_C;
4842 if (po->op == OP_CMPS || po->op == OP_SCAS) {
4843 cond_vars |= 1 << PFO_Z;
4845 else if (po->op == OP_MUL
4846 || (po->op == OP_IMUL && po->operand_cnt == 1))
4848 if (po->operand[0].lmod == OPLM_DWORD)
4851 else if (po->op == OP_CALL) {
4852 // note: resolved non-reg calls are OPF_DONE already
4854 ferr_assert(po, pp != NULL);
4856 if (pp->is_unresolved) {
4857 int regmask_stack = 0;
4858 collect_call_args(po, i, pp, ®mask, save_arg_vars,
4861 // this is pretty rough guess:
4862 // see ecx and edx were pushed (and not their saved versions)
4863 for (arg = 0; arg < pp->argc; arg++) {
4864 if (pp->arg[arg].reg != NULL)
4867 tmp_op = pp->arg[arg].datap;
4869 ferr(po, "parsed_op missing for arg%d\n", arg);
4870 if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
4871 regmask_stack |= 1 << tmp_op->operand[0].reg;
4874 if (!((regmask_stack & (1 << xCX))
4875 && (regmask_stack & (1 << xDX))))
4877 if (pp->argc_stack != 0
4878 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
4880 pp_insert_reg_arg(pp, "ecx");
4881 pp->is_fastcall = 1;
4882 regmask_init |= 1 << xCX;
4883 regmask |= 1 << xCX;
4885 if (pp->argc_stack != 0
4886 || ((regmask | regmask_arg) & (1 << xDX)))
4888 pp_insert_reg_arg(pp, "edx");
4889 regmask_init |= 1 << xDX;
4890 regmask |= 1 << xDX;
4894 // note: __cdecl doesn't fall into is_unresolved category
4895 if (pp->argc_stack > 0)
4899 else if (po->op == OP_MOV && po->operand[0].pp != NULL
4900 && po->operand[1].pp != NULL)
4902 // <var> = offset <something>
4903 if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
4904 && !IS_START(po->operand[1].name, "off_"))
4906 if (!po->operand[0].pp->is_fptr)
4907 ferr(po, "%s not declared as fptr when it should be\n",
4908 po->operand[0].name);
4909 if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
4910 pp_print(buf1, sizeof(buf1), po->operand[0].pp);
4911 pp_print(buf2, sizeof(buf2), po->operand[1].pp);
4912 fnote(po, "var: %s\n", buf1);
4913 fnote(po, "func: %s\n", buf2);
4914 ferr(po, "^ mismatch\n");
4918 else if (po->op == OP_DIV || po->op == OP_IDIV) {
4919 if (po->operand[0].lmod == OPLM_DWORD) {
4920 // 32bit division is common, look for it
4921 if (po->op == OP_DIV)
4922 ret = scan_for_reg_clear(i, xDX);
4924 ret = scan_for_cdq_edx(i);
4926 po->flags |= OPF_32BIT;
4933 else if (po->op == OP_CLD)
4934 po->flags |= OPF_RMD | OPF_DONE;
4936 if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG)
4940 // output starts here
4942 // define userstack size
4943 if (g_func_pp->is_userstack) {
4944 fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
4945 fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
4946 fprintf(fout, "#endif\n");
4949 // the function itself
4950 ferr_assert(ops, !g_func_pp->is_fptr);
4951 output_pp(fout, g_func_pp,
4952 (g_ida_func_attr & IDAFA_NORETURN) ? OPP_FORCE_NORETURN : 0);
4953 fprintf(fout, "\n{\n");
4955 // declare indirect functions
4956 for (i = 0; i < opcnt; i++) {
4958 if (po->flags & OPF_RMD)
4961 if (po->op == OP_CALL) {
4964 ferr(po, "NULL pp\n");
4966 if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
4967 if (pp->name[0] != 0) {
4968 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
4969 memcpy(pp->name, "i_", 2);
4971 // might be declared already
4973 for (j = 0; j < i; j++) {
4974 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
4975 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
4985 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
4988 output_pp(fout, pp, OPP_SIMPLE_ARGS);
4989 fprintf(fout, ";\n");
4994 // output LUTs/jumptables
4995 for (i = 0; i < g_func_pd_cnt; i++) {
4997 fprintf(fout, " static const ");
4998 if (pd->type == OPT_OFFSET) {
4999 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
5001 for (j = 0; j < pd->count; j++) {
5003 fprintf(fout, ", ");
5004 fprintf(fout, "&&%s", pd->d[j].u.label);
5008 fprintf(fout, "%s %s[] =\n { ",
5009 lmod_type_u(ops, pd->lmod), pd->label);
5011 for (j = 0; j < pd->count; j++) {
5013 fprintf(fout, ", ");
5014 fprintf(fout, "%u", pd->d[j].u.val);
5017 fprintf(fout, " };\n");
5021 // declare stack frame, va_arg
5023 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
5024 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
5028 if (g_func_pp->is_userstack) {
5029 fprintf(fout, " u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
5030 fprintf(fout, " u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
5034 if (g_func_pp->is_vararg) {
5035 fprintf(fout, " va_list ap;\n");
5039 // declare arg-registers
5040 for (i = 0; i < g_func_pp->argc; i++) {
5041 if (g_func_pp->arg[i].reg != NULL) {
5042 reg = char_array_i(regs_r32,
5043 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
5044 if (regmask & (1 << reg)) {
5045 if (g_func_pp->arg[i].type.is_retreg)
5046 fprintf(fout, " u32 %s = *r_%s;\n",
5047 g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
5049 fprintf(fout, " u32 %s = (u32)a%d;\n",
5050 g_func_pp->arg[i].reg, i + 1);
5053 if (g_func_pp->arg[i].type.is_retreg)
5054 ferr(ops, "retreg '%s' is unused?\n",
5055 g_func_pp->arg[i].reg);
5056 fprintf(fout, " // %s = a%d; // unused\n",
5057 g_func_pp->arg[i].reg, i + 1);
5063 // declare normal registers
5064 regmask_now = regmask & ~regmask_arg;
5065 regmask_now &= ~(1 << xSP);
5066 if (regmask_now & 0x00ff) {
5067 for (reg = 0; reg < 8; reg++) {
5068 if (regmask_now & (1 << reg)) {
5069 fprintf(fout, " u32 %s", regs_r32[reg]);
5070 if (regmask_init & (1 << reg))
5071 fprintf(fout, " = 0");
5072 fprintf(fout, ";\n");
5077 if (regmask_now & 0xff00) {
5078 for (reg = 8; reg < 16; reg++) {
5079 if (regmask_now & (1 << reg)) {
5080 fprintf(fout, " mmxr %s", regs_r32[reg]);
5081 if (regmask_init & (1 << reg))
5082 fprintf(fout, " = { 0, }");
5083 fprintf(fout, ";\n");
5090 for (reg = 0; reg < 8; reg++) {
5091 if (regmask_save & (1 << reg)) {
5092 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
5098 for (i = 0; i < ARRAY_SIZE(save_arg_vars); i++) {
5099 if (save_arg_vars[i] == 0)
5101 for (reg = 0; reg < 32; reg++) {
5102 if (save_arg_vars[i] & (1 << reg)) {
5103 fprintf(fout, " u32 %s;\n",
5104 saved_arg_name(buf1, sizeof(buf1), i, reg + 1));
5110 // declare push-pop temporaries
5112 for (reg = 0; reg < 8; reg++) {
5113 if (regmask_pp & (1 << reg)) {
5114 fprintf(fout, " u32 pp_%s;\n", regs_r32[reg]);
5121 for (i = 0; i < 8; i++) {
5122 if (cond_vars & (1 << i)) {
5123 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
5130 fprintf(fout, " u32 tmp;\n");
5135 fprintf(fout, " u64 tmp64;\n");
5140 fprintf(fout, "\n");
5142 if (g_func_pp->is_vararg) {
5143 if (g_func_pp->argc_stack == 0)
5144 ferr(ops, "vararg func without stack args?\n");
5145 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
5149 for (i = 0; i < opcnt; i++)
5151 if (g_labels[i] != NULL) {
5152 fprintf(fout, "\n%s:\n", g_labels[i]);
5155 delayed_flag_op = NULL;
5156 last_arith_dst = NULL;
5160 if (po->flags & OPF_RMD)
5165 #define assert_operand_cnt(n_) \
5166 if (po->operand_cnt != n_) \
5167 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
5169 // conditional/flag using op?
5170 if (po->flags & OPF_CC)
5176 // we go through all this trouble to avoid using parsed_flag_op,
5177 // which makes generated code much nicer
5178 if (delayed_flag_op != NULL)
5180 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
5181 po->pfo, po->pfo_inv);
5184 else if (last_arith_dst != NULL
5185 && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
5186 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
5189 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
5190 out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
5191 last_arith_dst->lmod, buf3);
5194 else if (tmp_op != NULL) {
5195 // use preprocessed flag calc results
5196 if (!(tmp_op->pfomask & (1 << po->pfo)))
5197 ferr(po, "not prepared for pfo %d\n", po->pfo);
5199 // note: pfo_inv was not yet applied
5200 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
5201 po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
5204 ferr(po, "all methods of finding comparison failed\n");
5207 if (po->flags & OPF_JMP) {
5208 fprintf(fout, " if %s", buf1);
5210 else if (po->op == OP_RCL || po->op == OP_RCR
5211 || po->op == OP_ADC || po->op == OP_SBB)
5214 fprintf(fout, " cond_%s = %s;\n",
5215 parsed_flag_op_names[po->pfo], buf1);
5217 else if (po->flags & OPF_DATA) { // SETcc
5218 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
5219 fprintf(fout, " %s = %s;", buf2, buf1);
5222 ferr(po, "unhandled conditional op\n");
5226 pfomask = po->pfomask;
5228 if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
5229 struct parsed_opr opr = OPR_INIT(OPT_REG, OPLM_DWORD, xCX);
5230 ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
5232 if (ret != 1 || uval == 0) {
5233 // we need initial flags for ecx=0 case..
5234 if (i > 0 && ops[i - 1].op == OP_XOR
5235 && IS(ops[i - 1].operand[0].name,
5236 ops[i - 1].operand[1].name))
5238 fprintf(fout, " cond_z = ");
5239 if (pfomask & (1 << PFO_C))
5240 fprintf(fout, "cond_c = ");
5241 fprintf(fout, "0;\n");
5243 else if (last_arith_dst != NULL) {
5244 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
5245 out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
5246 last_arith_dst->lmod, buf3);
5247 fprintf(fout, " cond_z = %s;\n", buf1);
5250 ferr(po, "missing initial ZF\n");
5257 assert_operand_cnt(2);
5258 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5259 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5260 default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
5261 fprintf(fout, " %s = %s;", buf1,
5262 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5267 assert_operand_cnt(2);
5268 po->operand[1].lmod = OPLM_DWORD; // always
5269 fprintf(fout, " %s = %s;",
5270 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5271 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5276 assert_operand_cnt(2);
5277 fprintf(fout, " %s = %s;",
5278 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5279 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5283 assert_operand_cnt(2);
5284 switch (po->operand[1].lmod) {
5286 strcpy(buf3, "(s8)");
5289 strcpy(buf3, "(s16)");
5292 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
5294 fprintf(fout, " %s = %s;",
5295 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5296 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5301 assert_operand_cnt(2);
5302 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5303 fprintf(fout, " tmp = %s;",
5304 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
5305 fprintf(fout, " %s = %s;",
5306 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5307 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5308 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5309 fprintf(fout, " %s = %stmp;",
5310 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
5311 default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
5312 snprintf(g_comment, sizeof(g_comment), "xchg");
5316 assert_operand_cnt(1);
5317 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5318 fprintf(fout, " %s = ~%s;", buf1, buf1);
5322 assert_operand_cnt(2);
5323 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5324 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5325 fprintf(fout, " %s = *(u8 *)(%s + %s);", buf1, buf2, buf1);
5326 strcpy(g_comment, "xlat");
5330 assert_operand_cnt(2);
5331 fprintf(fout, " %s = (s32)%s >> 31;",
5332 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5333 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5334 strcpy(g_comment, "cdq");
5338 if (po->flags & OPF_REP) {
5339 assert_operand_cnt(3);
5344 assert_operand_cnt(2);
5345 fprintf(fout, " %s = %sesi; esi %c= %d;",
5346 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
5347 lmod_cast_u_ptr(po, po->operand[1].lmod),
5348 (po->flags & OPF_DF) ? '-' : '+',
5349 lmod_bytes(po, po->operand[1].lmod));
5350 strcpy(g_comment, "lods");
5355 if (po->flags & OPF_REP) {
5356 assert_operand_cnt(3);
5357 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
5358 (po->flags & OPF_DF) ? '-' : '+',
5359 lmod_bytes(po, po->operand[1].lmod));
5360 fprintf(fout, " %sedi = eax;",
5361 lmod_cast_u_ptr(po, po->operand[1].lmod));
5362 strcpy(g_comment, "rep stos");
5365 assert_operand_cnt(2);
5366 fprintf(fout, " %sedi = eax; edi %c= %d;",
5367 lmod_cast_u_ptr(po, po->operand[1].lmod),
5368 (po->flags & OPF_DF) ? '-' : '+',
5369 lmod_bytes(po, po->operand[1].lmod));
5370 strcpy(g_comment, "stos");
5375 j = lmod_bytes(po, po->operand[0].lmod);
5376 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
5377 l = (po->flags & OPF_DF) ? '-' : '+';
5378 if (po->flags & OPF_REP) {
5379 assert_operand_cnt(3);
5381 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
5384 " %sedi = %sesi;", buf1, buf1);
5385 strcpy(g_comment, "rep movs");
5388 assert_operand_cnt(2);
5389 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
5390 buf1, buf1, l, j, l, j);
5391 strcpy(g_comment, "movs");
5396 // repe ~ repeat while ZF=1
5397 j = lmod_bytes(po, po->operand[0].lmod);
5398 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
5399 l = (po->flags & OPF_DF) ? '-' : '+';
5400 if (po->flags & OPF_REP) {
5401 assert_operand_cnt(3);
5403 " for (; ecx != 0; ecx--) {\n");
5404 if (pfomask & (1 << PFO_C)) {
5407 " cond_c = %sesi < %sedi;\n", buf1, buf1);
5408 pfomask &= ~(1 << PFO_C);
5411 " cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
5412 buf1, buf1, l, j, l, j);
5414 " if (cond_z %s 0) break;\n",
5415 (po->flags & OPF_REPZ) ? "==" : "!=");
5418 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
5419 (po->flags & OPF_REPZ) ? "e" : "ne");
5422 assert_operand_cnt(2);
5424 " cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
5425 buf1, buf1, l, j, l, j);
5426 strcpy(g_comment, "cmps");
5428 pfomask &= ~(1 << PFO_Z);
5429 last_arith_dst = NULL;
5430 delayed_flag_op = NULL;
5434 // only does ZF (for now)
5435 // repe ~ repeat while ZF=1
5436 j = lmod_bytes(po, po->operand[1].lmod);
5437 l = (po->flags & OPF_DF) ? '-' : '+';
5438 if (po->flags & OPF_REP) {
5439 assert_operand_cnt(3);
5441 " for (; ecx != 0; ecx--) {\n");
5443 " cond_z = (%seax == %sedi); edi %c= %d;\n",
5444 lmod_cast_u(po, po->operand[1].lmod),
5445 lmod_cast_u_ptr(po, po->operand[1].lmod), l, j);
5447 " if (cond_z %s 0) break;\n",
5448 (po->flags & OPF_REPZ) ? "==" : "!=");
5451 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
5452 (po->flags & OPF_REPZ) ? "e" : "ne");
5455 assert_operand_cnt(2);
5456 fprintf(fout, " cond_z = (%seax == %sedi); edi %c= %d;",
5457 lmod_cast_u(po, po->operand[1].lmod),
5458 lmod_cast_u_ptr(po, po->operand[1].lmod), l, j);
5459 strcpy(g_comment, "scas");
5461 pfomask &= ~(1 << PFO_Z);
5462 last_arith_dst = NULL;
5463 delayed_flag_op = NULL;
5466 // arithmetic w/flags
5468 if (po->operand[1].type == OPT_CONST && !po->operand[1].val)
5469 goto dualop_arith_const;
5470 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5474 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5475 if (po->operand[1].type == OPT_CONST) {
5476 j = lmod_bytes(po, po->operand[0].lmod);
5477 if (((1ull << j * 8) - 1) == po->operand[1].val)
5478 goto dualop_arith_const;
5483 assert_operand_cnt(2);
5484 fprintf(fout, " %s %s= %s;",
5485 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5487 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5488 output_std_flags(fout, po, &pfomask, buf1);
5489 last_arith_dst = &po->operand[0];
5490 delayed_flag_op = NULL;
5494 // and 0, or ~0 used instead mov
5495 assert_operand_cnt(2);
5496 fprintf(fout, " %s = %s;",
5497 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5498 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5499 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5500 output_std_flags(fout, po, &pfomask, buf1);
5501 last_arith_dst = &po->operand[0];
5502 delayed_flag_op = NULL;
5507 assert_operand_cnt(2);
5508 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5509 if (pfomask & (1 << PFO_C)) {
5510 if (po->operand[1].type == OPT_CONST) {
5511 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5512 j = po->operand[1].val;
5515 if (po->op == OP_SHL)
5519 fprintf(fout, " cond_c = (%s >> %d) & 1;\n",
5523 ferr(po, "zero shift?\n");
5527 pfomask &= ~(1 << PFO_C);
5529 fprintf(fout, " %s %s= %s", buf1, op_to_c(po),
5530 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5531 if (po->operand[1].type != OPT_CONST)
5532 fprintf(fout, " & 0x1f");
5534 output_std_flags(fout, po, &pfomask, buf1);
5535 last_arith_dst = &po->operand[0];
5536 delayed_flag_op = NULL;
5540 assert_operand_cnt(2);
5541 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5542 fprintf(fout, " %s = %s%s >> %s;", buf1,
5543 lmod_cast_s(po, po->operand[0].lmod), buf1,
5544 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5545 output_std_flags(fout, po, &pfomask, buf1);
5546 last_arith_dst = &po->operand[0];
5547 delayed_flag_op = NULL;
5552 assert_operand_cnt(3);
5553 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5554 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5555 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[2]);
5556 if (po->operand[2].type != OPT_CONST) {
5557 // no handling for "undefined" case, hopefully not needed
5558 snprintf(buf2, sizeof(buf2), "(%s & 0x1f)", buf3);
5561 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5562 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5563 if (po->op == OP_SHLD) {
5564 fprintf(fout, " %s <<= %s; %s |= %s >> (%d - %s);",
5565 buf1, buf3, buf1, buf2, l, buf3);
5566 strcpy(g_comment, "shld");
5569 fprintf(fout, " %s >>= %s; %s |= %s << (%d - %s);",
5570 buf1, buf3, buf1, buf2, l, buf3);
5571 strcpy(g_comment, "shrd");
5573 output_std_flags(fout, po, &pfomask, buf1);
5574 last_arith_dst = &po->operand[0];
5575 delayed_flag_op = NULL;
5580 assert_operand_cnt(2);
5581 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5582 if (po->operand[1].type == OPT_CONST) {
5583 j = po->operand[1].val;
5584 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
5585 fprintf(fout, po->op == OP_ROL ?
5586 " %s = (%s << %d) | (%s >> %d);" :
5587 " %s = (%s >> %d) | (%s << %d);",
5588 buf1, buf1, j, buf1,
5589 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
5593 output_std_flags(fout, po, &pfomask, buf1);
5594 last_arith_dst = &po->operand[0];
5595 delayed_flag_op = NULL;
5600 assert_operand_cnt(2);
5601 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5602 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5603 if (po->operand[1].type == OPT_CONST) {
5604 j = po->operand[1].val % l;
5606 ferr(po, "zero rotate\n");
5607 fprintf(fout, " tmp = (%s >> %d) & 1;\n",
5608 buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
5609 if (po->op == OP_RCL) {
5611 " %s = (%s << %d) | (cond_c << %d)",
5612 buf1, buf1, j, j - 1);
5614 fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
5618 " %s = (%s >> %d) | (cond_c << %d)",
5619 buf1, buf1, j, l - j);
5621 fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
5623 fprintf(fout, ";\n");
5624 fprintf(fout, " cond_c = tmp;");
5628 strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
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 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5637 if (IS(opr_name(po, 0), opr_name(po, 1))) {
5638 // special case for XOR
5639 if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
5640 fprintf(fout, " cond_be = 1;\n");
5641 pfomask &= ~(1 << PFO_BE);
5643 fprintf(fout, " %s = 0;",
5644 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5645 last_arith_dst = &po->operand[0];
5646 delayed_flag_op = NULL;
5652 assert_operand_cnt(2);
5653 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5654 if (pfomask & (1 << PFO_C)) {
5655 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5656 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5657 if (po->operand[0].lmod == OPLM_DWORD) {
5658 fprintf(fout, " tmp64 = (u64)%s + %s;\n", buf1, buf2);
5659 fprintf(fout, " cond_c = tmp64 >> 32;\n");
5660 fprintf(fout, " %s = (u32)tmp64;",
5661 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5662 strcat(g_comment, "add64");
5665 fprintf(fout, " cond_c = ((u32)%s + %s) >> %d;\n",
5666 buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
5667 fprintf(fout, " %s += %s;",
5668 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5671 pfomask &= ~(1 << PFO_C);
5672 output_std_flags(fout, po, &pfomask, buf1);
5673 last_arith_dst = &po->operand[0];
5674 delayed_flag_op = NULL;
5680 assert_operand_cnt(2);
5681 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5682 if (pfomask & ~((1 << PFO_Z) | (1 << PFO_S))) {
5683 for (j = 0; j <= PFO_LE; j++) {
5684 if (!(pfomask & (1 << j)))
5686 if (j == PFO_Z || j == PFO_S)
5689 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5690 fprintf(fout, " cond_%s = %s;\n",
5691 parsed_flag_op_names[j], buf1);
5692 pfomask &= ~(1 << j);
5699 assert_operand_cnt(2);
5700 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5701 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5702 if (po->op == OP_SBB
5703 && IS(po->operand[0].name, po->operand[1].name))
5705 // avoid use of unitialized var
5706 fprintf(fout, " %s = -cond_c;", buf1);
5707 // carry remains what it was
5708 pfomask &= ~(1 << PFO_C);
5711 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
5712 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5714 output_std_flags(fout, po, &pfomask, buf1);
5715 last_arith_dst = &po->operand[0];
5716 delayed_flag_op = NULL;
5720 assert_operand_cnt(2);
5721 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5722 fprintf(fout, " %s = %s ? __builtin_ffs(%s) - 1 : 0;",
5723 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5725 output_std_flags(fout, po, &pfomask, buf1);
5726 last_arith_dst = &po->operand[0];
5727 delayed_flag_op = NULL;
5728 strcat(g_comment, "bsf");
5732 if (pfomask & ~(PFOB_S | PFOB_S | PFOB_C)) {
5733 for (j = 0; j <= PFO_LE; j++) {
5734 if (!(pfomask & (1 << j)))
5736 if (j == PFO_Z || j == PFO_S || j == PFO_C)
5739 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5740 fprintf(fout, " cond_%s = %s;\n",
5741 parsed_flag_op_names[j], buf1);
5742 pfomask &= ~(1 << j);
5748 if (pfomask & (1 << PFO_C))
5749 // carry is unaffected by inc/dec.. wtf?
5750 ferr(po, "carry propagation needed\n");
5752 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5753 if (po->operand[0].type == OPT_REG) {
5754 strcpy(buf2, po->op == OP_INC ? "++" : "--");
5755 fprintf(fout, " %s%s;", buf1, buf2);
5758 strcpy(buf2, po->op == OP_INC ? "+" : "-");
5759 fprintf(fout, " %s %s= 1;", buf1, buf2);
5761 output_std_flags(fout, po, &pfomask, buf1);
5762 last_arith_dst = &po->operand[0];
5763 delayed_flag_op = NULL;
5767 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5768 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
5769 fprintf(fout, " %s = -%s%s;", buf1,
5770 lmod_cast_s(po, po->operand[0].lmod), buf2);
5771 last_arith_dst = &po->operand[0];
5772 delayed_flag_op = NULL;
5773 if (pfomask & (1 << PFO_C)) {
5774 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
5775 pfomask &= ~(1 << PFO_C);
5780 if (po->operand_cnt == 2) {
5781 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5784 if (po->operand_cnt == 3)
5785 ferr(po, "TODO imul3\n");
5788 assert_operand_cnt(1);
5789 switch (po->operand[0].lmod) {
5791 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
5792 fprintf(fout, " tmp64 = %seax * %s%s;\n", buf1, buf1,
5793 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
5794 fprintf(fout, " edx = tmp64 >> 32;\n");
5795 fprintf(fout, " eax = tmp64;");
5798 strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
5799 fprintf(fout, " LOWORD(eax) = %seax * %s;", buf1,
5800 out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
5804 ferr(po, "TODO: unhandled mul type\n");
5807 last_arith_dst = NULL;
5808 delayed_flag_op = NULL;
5813 assert_operand_cnt(1);
5814 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5815 strcpy(cast, lmod_cast(po, po->operand[0].lmod,
5816 po->op == OP_IDIV));
5817 switch (po->operand[0].lmod) {
5819 if (po->flags & OPF_32BIT)
5820 snprintf(buf2, sizeof(buf2), "%seax", cast);
5822 fprintf(fout, " tmp64 = ((u64)edx << 32) | eax;\n");
5823 snprintf(buf2, sizeof(buf2), "%stmp64",
5824 (po->op == OP_IDIV) ? "(s64)" : "");
5826 if (po->operand[0].type == OPT_REG
5827 && po->operand[0].reg == xDX)
5829 fprintf(fout, " eax = %s / %s%s;\n", buf2, cast, buf1);
5830 fprintf(fout, " edx = %s %% %s%s;", buf2, cast, buf1);
5833 fprintf(fout, " edx = %s %% %s%s;\n", buf2, cast, buf1);
5834 fprintf(fout, " eax = %s / %s%s;", buf2, cast, buf1);
5838 fprintf(fout, " tmp = (edx << 16) | (eax & 0xffff);\n");
5839 snprintf(buf2, sizeof(buf2), "%stmp",
5840 (po->op == OP_IDIV) ? "(s32)" : "");
5841 if (po->operand[0].type == OPT_REG
5842 && po->operand[0].reg == xDX)
5844 fprintf(fout, " LOWORD(eax) = %s / %s%s;\n",
5846 fprintf(fout, " LOWORD(edx) = %s %% %s%s;",
5850 fprintf(fout, " LOWORD(edx) = %s %% %s%s;\n",
5852 fprintf(fout, " LOWORD(eax) = %s / %s%s;",
5855 strcat(g_comment, "div16");
5858 ferr(po, "unhandled div lmod %d\n", po->operand[0].lmod);
5860 last_arith_dst = NULL;
5861 delayed_flag_op = NULL;
5866 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5868 for (j = 0; j < 8; j++) {
5869 if (pfomask & (1 << j)) {
5870 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
5871 fprintf(fout, " cond_%s = %s;",
5872 parsed_flag_op_names[j], buf1);
5879 last_arith_dst = NULL;
5880 delayed_flag_op = po;
5884 // SETcc - should already be handled
5887 // note: we reuse OP_Jcc for SETcc, only flags differ
5889 fprintf(fout, "\n goto %s;", po->operand[0].name);
5893 fprintf(fout, " if (ecx == 0)\n");
5894 fprintf(fout, " goto %s;", po->operand[0].name);
5895 strcat(g_comment, "jecxz");
5899 fprintf(fout, " if (--ecx != 0)\n");
5900 fprintf(fout, " goto %s;", po->operand[0].name);
5901 strcat(g_comment, "loop");
5905 assert_operand_cnt(1);
5906 last_arith_dst = NULL;
5907 delayed_flag_op = NULL;
5909 if (po->operand[0].type == OPT_REGMEM) {
5910 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
5913 ferr(po, "parse failure for jmp '%s'\n",
5914 po->operand[0].name);
5915 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
5918 else if (po->operand[0].type != OPT_LABEL)
5919 ferr(po, "unhandled jmp type\n");
5921 fprintf(fout, " goto %s;", po->operand[0].name);
5925 assert_operand_cnt(1);
5927 my_assert_not(pp, NULL);
5930 if (po->flags & OPF_CC) {
5931 // we treat conditional branch to another func
5932 // (yes such code exists..) as conditional tailcall
5934 fprintf(fout, " {\n");
5937 if (pp->is_fptr && !pp->is_arg) {
5938 fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
5939 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
5941 if (pp->is_unresolved)
5942 fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
5943 buf3, asmfn, po->asmln, pp->name);
5946 fprintf(fout, "%s", buf3);
5947 if (strstr(pp->ret_type.name, "int64")) {
5948 if (po->flags & OPF_TAIL)
5949 ferr(po, "int64 and tail?\n");
5950 fprintf(fout, "tmp64 = ");
5952 else if (!IS(pp->ret_type.name, "void")) {
5953 if (po->flags & OPF_TAIL) {
5954 if (regmask_ret & (1 << xAX)) {
5955 fprintf(fout, "return ");
5956 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
5957 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
5960 else if (po->regmask_dst & (1 << xAX)) {
5961 fprintf(fout, "eax = ");
5962 if (pp->ret_type.is_ptr)
5963 fprintf(fout, "(u32)");
5967 if (pp->name[0] == 0)
5968 ferr(po, "missing pp->name\n");
5969 fprintf(fout, "%s%s(", pp->name,
5970 pp->has_structarg ? "_sa" : "");
5972 if (po->flags & OPF_ATAIL) {
5973 if (pp->argc_stack != g_func_pp->argc_stack
5974 || (pp->argc_stack > 0
5975 && pp->is_stdcall != g_func_pp->is_stdcall))
5976 ferr(po, "incompatible tailcall\n");
5977 if (g_func_pp->has_retreg)
5978 ferr(po, "TODO: retreg+tailcall\n");
5980 for (arg = j = 0; arg < pp->argc; arg++) {
5982 fprintf(fout, ", ");
5985 if (pp->arg[arg].type.is_ptr)
5986 snprintf(cast, sizeof(cast), "(%s)",
5987 pp->arg[arg].type.name);
5989 if (pp->arg[arg].reg != NULL) {
5990 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5994 for (; j < g_func_pp->argc; j++)
5995 if (g_func_pp->arg[j].reg == NULL)
5997 fprintf(fout, "%sa%d", cast, j + 1);
6002 for (arg = 0; arg < pp->argc; arg++) {
6004 fprintf(fout, ", ");
6007 if (pp->arg[arg].type.is_ptr)
6008 snprintf(cast, sizeof(cast), "(%s)",
6009 pp->arg[arg].type.name);
6011 if (pp->arg[arg].reg != NULL) {
6012 if (pp->arg[arg].type.is_retreg)
6013 fprintf(fout, "&%s", pp->arg[arg].reg);
6015 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
6020 tmp_op = pp->arg[arg].datap;
6022 ferr(po, "parsed_op missing for arg%d\n", arg);
6024 if (tmp_op->flags & OPF_VAPUSH) {
6025 fprintf(fout, "ap");
6027 else if (tmp_op->p_argpass != 0) {
6028 fprintf(fout, "a%d", tmp_op->p_argpass);
6030 else if (tmp_op->p_argnum != 0) {
6031 fprintf(fout, "%s%s", cast,
6032 saved_arg_name(buf1, sizeof(buf1),
6033 tmp_op->p_arggrp, tmp_op->p_argnum));
6037 out_src_opr(buf1, sizeof(buf1),
6038 tmp_op, &tmp_op->operand[0], cast, 0));
6042 fprintf(fout, ");");
6044 if (strstr(pp->ret_type.name, "int64")) {
6045 fprintf(fout, "\n");
6046 fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
6047 fprintf(fout, "%seax = tmp64;", buf3);
6050 if (pp->is_unresolved) {
6051 snprintf(buf2, sizeof(buf2), " unresolved %dreg",
6053 strcat(g_comment, buf2);
6056 if (po->flags & OPF_TAIL) {
6058 if (i == opcnt - 1 || pp->is_noreturn)
6060 else if (IS(pp->ret_type.name, "void"))
6062 else if (!(regmask_ret & (1 << xAX)))
6064 // else already handled as 'return f()'
6067 fprintf(fout, "\n%sreturn;", buf3);
6068 strcat(g_comment, " ^ tailcall");
6071 strcat(g_comment, " tailcall");
6073 if ((regmask_ret & (1 << xAX))
6074 && IS(pp->ret_type.name, "void") && !pp->is_noreturn)
6076 ferr(po, "int func -> void func tailcall?\n");
6079 if (pp->is_noreturn)
6080 strcat(g_comment, " noreturn");
6081 if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
6082 strcat(g_comment, " argframe");
6083 if (po->flags & OPF_CC)
6084 strcat(g_comment, " cond");
6086 if (po->flags & OPF_CC)
6087 fprintf(fout, "\n }");
6089 delayed_flag_op = NULL;
6090 last_arith_dst = NULL;
6094 if (g_func_pp->is_vararg)
6095 fprintf(fout, " va_end(ap);\n");
6096 if (g_func_pp->has_retreg) {
6097 for (arg = 0; arg < g_func_pp->argc; arg++)
6098 if (g_func_pp->arg[arg].type.is_retreg)
6099 fprintf(fout, " *r_%s = %s;\n",
6100 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
6103 if (!(regmask_ret & (1 << xAX))) {
6104 if (i != opcnt - 1 || label_pending)
6105 fprintf(fout, " return;");
6107 else if (g_func_pp->ret_type.is_ptr) {
6108 fprintf(fout, " return (%s)eax;",
6109 g_func_pp->ret_type.name);
6111 else if (IS(g_func_pp->ret_type.name, "__int64"))
6112 fprintf(fout, " return ((u64)edx << 32) | eax;");
6114 fprintf(fout, " return eax;");
6116 last_arith_dst = NULL;
6117 delayed_flag_op = NULL;
6121 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
6122 if (po->p_argnum != 0) {
6123 // special case - saved func arg
6124 fprintf(fout, " %s = %s;",
6125 saved_arg_name(buf2, sizeof(buf2),
6126 po->p_arggrp, po->p_argnum), buf1);
6129 else if (po->flags & OPF_RSAVE) {
6130 fprintf(fout, " s_%s = %s;", buf1, buf1);
6133 else if (po->flags & OPF_PPUSH) {
6135 ferr_assert(po, tmp_op != NULL);
6136 out_dst_opr(buf2, sizeof(buf2), po, &tmp_op->operand[0]);
6137 fprintf(fout, " pp_%s = %s;", buf2, buf1);
6140 else if (g_func_pp->is_userstack) {
6141 fprintf(fout, " *(--esp) = %s;", buf1);
6144 if (!(g_ida_func_attr & IDAFA_NORETURN))
6145 ferr(po, "stray push encountered\n");
6150 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
6151 if (po->flags & OPF_RSAVE) {
6152 fprintf(fout, " %s = s_%s;", buf1, buf1);
6155 else if (po->flags & OPF_PPUSH) {
6156 // push/pop graph / non-const
6157 ferr_assert(po, po->datap == NULL);
6158 fprintf(fout, " %s = pp_%s;", buf1, buf1);
6161 else if (po->datap != NULL) {
6164 fprintf(fout, " %s = %s;", buf1,
6165 out_src_opr(buf2, sizeof(buf2),
6166 tmp_op, &tmp_op->operand[0],
6167 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
6170 else if (g_func_pp->is_userstack) {
6171 fprintf(fout, " %s = *esp++;", buf1);
6175 ferr(po, "stray pop encountered\n");
6184 strcpy(g_comment, "(emms)");
6189 ferr(po, "unhandled op type %d, flags %x\n",
6194 if (g_comment[0] != 0) {
6195 char *p = g_comment;
6196 while (my_isblank(*p))
6198 fprintf(fout, " // %s", p);
6203 fprintf(fout, "\n");
6205 // some sanity checking
6206 if (po->flags & OPF_REP) {
6207 if (po->op != OP_STOS && po->op != OP_MOVS
6208 && po->op != OP_CMPS && po->op != OP_SCAS)
6209 ferr(po, "unexpected rep\n");
6210 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
6211 && (po->op == OP_CMPS || po->op == OP_SCAS))
6212 ferr(po, "cmps/scas with plain rep\n");
6214 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
6215 && po->op != OP_CMPS && po->op != OP_SCAS)
6216 ferr(po, "unexpected repz/repnz\n");
6219 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
6221 // see is delayed flag stuff is still valid
6222 if (delayed_flag_op != NULL && delayed_flag_op != po) {
6223 if (is_any_opr_modified(delayed_flag_op, po, 0))
6224 delayed_flag_op = NULL;
6227 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
6228 if (is_opr_modified(last_arith_dst, po))
6229 last_arith_dst = NULL;
6235 if (g_stack_fsz && !g_stack_frame_used)
6236 fprintf(fout, " (void)sf;\n");
6238 fprintf(fout, "}\n\n");
6240 gen_x_cleanup(opcnt);
6243 static void gen_x_cleanup(int opcnt)
6247 for (i = 0; i < opcnt; i++) {
6248 struct label_ref *lr, *lr_del;
6250 lr = g_label_refs[i].next;
6251 while (lr != NULL) {
6256 g_label_refs[i].i = -1;
6257 g_label_refs[i].next = NULL;
6259 if (ops[i].op == OP_CALL) {
6261 proto_release(ops[i].pp);
6267 struct func_proto_dep;
6269 struct func_prototype {
6274 int has_ret:3; // -1, 0, 1: unresolved, no, yes
6275 unsigned int dep_resolved:1;
6276 unsigned int is_stdcall:1;
6277 struct func_proto_dep *dep_func;
6279 const struct parsed_proto *pp; // seed pp, if any
6282 struct func_proto_dep {
6284 struct func_prototype *proto;
6285 int regmask_live; // .. at the time of call
6286 unsigned int ret_dep:1; // return from this is caller's return
6289 static struct func_prototype *hg_fp;
6290 static int hg_fp_cnt;
6292 static struct scanned_var {
6294 enum opr_lenmod lmod;
6295 unsigned int is_seeded:1;
6296 unsigned int is_c_str:1;
6297 const struct parsed_proto *pp; // seed pp, if any
6299 static int hg_var_cnt;
6301 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
6304 struct func_prototype *hg_fp_add(const char *funcn)
6306 struct func_prototype *fp;
6308 if ((hg_fp_cnt & 0xff) == 0) {
6309 hg_fp = realloc(hg_fp, sizeof(hg_fp[0]) * (hg_fp_cnt + 0x100));
6310 my_assert_not(hg_fp, NULL);
6311 memset(hg_fp + hg_fp_cnt, 0, sizeof(hg_fp[0]) * 0x100);
6314 fp = &hg_fp[hg_fp_cnt];
6315 snprintf(fp->name, sizeof(fp->name), "%s", funcn);
6317 fp->argc_stack = -1;
6323 static struct func_proto_dep *hg_fp_find_dep(struct func_prototype *fp,
6328 for (i = 0; i < fp->dep_func_cnt; i++)
6329 if (IS(fp->dep_func[i].name, name))
6330 return &fp->dep_func[i];
6335 static void hg_fp_add_dep(struct func_prototype *fp, const char *name)
6338 if (hg_fp_find_dep(fp, name))
6341 if ((fp->dep_func_cnt & 0xff) == 0) {
6342 fp->dep_func = realloc(fp->dep_func,
6343 sizeof(fp->dep_func[0]) * (fp->dep_func_cnt + 0x100));
6344 my_assert_not(fp->dep_func, NULL);
6345 memset(&fp->dep_func[fp->dep_func_cnt], 0,
6346 sizeof(fp->dep_func[0]) * 0x100);
6348 fp->dep_func[fp->dep_func_cnt].name = strdup(name);
6352 static int hg_fp_cmp_name(const void *p1_, const void *p2_)
6354 const struct func_prototype *p1 = p1_, *p2 = p2_;
6355 return strcmp(p1->name, p2->name);
6359 static int hg_fp_cmp_id(const void *p1_, const void *p2_)
6361 const struct func_prototype *p1 = p1_, *p2 = p2_;
6362 return p1->id - p2->id;
6366 // recursive register dep pass
6367 // - track saved regs (part 2)
6368 // - try to figure out arg-regs
6369 // - calculate reg deps
6370 static void gen_hdr_dep_pass(int i, int opcnt, unsigned char *cbits,
6371 struct func_prototype *fp, int regmask_save, int regmask_dst,
6372 int *regmask_dep, int *has_ret)
6374 struct func_proto_dep *dep;
6375 struct parsed_op *po;
6376 int from_caller = 0;
6381 for (; i < opcnt; i++)
6383 if (cbits[i >> 3] & (1 << (i & 7)))
6385 cbits[i >> 3] |= (1 << (i & 7));
6389 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
6390 if (po->flags & OPF_RMD)
6393 if (po->btj != NULL) {
6395 for (j = 0; j < po->btj->count; j++) {
6396 check_i(po, po->btj->d[j].bt_i);
6397 gen_hdr_dep_pass(po->btj->d[j].bt_i, opcnt, cbits, fp,
6398 regmask_save, regmask_dst, regmask_dep, has_ret);
6403 check_i(po, po->bt_i);
6404 if (po->flags & OPF_CJMP) {
6405 gen_hdr_dep_pass(po->bt_i, opcnt, cbits, fp,
6406 regmask_save, regmask_dst, regmask_dep, has_ret);
6414 if (po->flags & OPF_FARG)
6415 /* (just calculate register deps) */;
6416 else if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
6418 reg = po->operand[0].reg;
6419 ferr_assert(po, reg >= 0);
6421 if (po->flags & OPF_RSAVE) {
6422 regmask_save |= 1 << reg;
6425 if (po->flags & OPF_DONE)
6428 ret = scan_for_pop(i + 1, opcnt, i + opcnt * 2, reg, 0, 0);
6430 regmask_save |= 1 << reg;
6431 po->flags |= OPF_RMD;
6432 scan_for_pop(i + 1, opcnt, i + opcnt * 3, reg, 0, OPF_RMD);
6436 else if (po->flags & OPF_RMD)
6438 else if (po->op == OP_CALL) {
6439 po->regmask_dst |= 1 << xAX;
6441 dep = hg_fp_find_dep(fp, po->operand[0].name);
6443 dep->regmask_live = regmask_save | regmask_dst;
6445 else if (po->op == OP_RET) {
6446 if (po->operand_cnt > 0) {
6448 if (fp->argc_stack >= 0
6449 && fp->argc_stack != po->operand[0].val / 4)
6450 ferr(po, "ret mismatch? (%d)\n", fp->argc_stack * 4);
6451 fp->argc_stack = po->operand[0].val / 4;
6455 // if has_ret is 0, there is uninitialized eax path,
6456 // which means it's most likely void func
6457 if (*has_ret != 0 && (po->flags & OPF_TAIL)) {
6458 if (po->op == OP_CALL) {
6463 struct parsed_opr opr = OPR_INIT(OPT_REG, OPLM_DWORD, xAX);
6466 ret = resolve_origin(i, &opr, i + opcnt * 4, &j, &from_caller);
6469 if (ret != 1 && from_caller) {
6470 // unresolved eax - probably void func
6474 if (j >= 0 && ops[j].op == OP_CALL) {
6475 dep = hg_fp_find_dep(fp, ops[j].operand[0].name);
6486 l = regmask_save | regmask_dst;
6487 if (g_bp_frame && !(po->flags & OPF_EBP_S))
6490 l = po->regmask_src & ~l;
6493 fnote(po, "dep |= %04x, dst %04x, save %04x (f %x)\n",
6494 l, regmask_dst, regmask_save, po->flags);
6497 regmask_dst |= po->regmask_dst;
6499 if (po->flags & OPF_TAIL)
6504 static void gen_hdr(const char *funcn, int opcnt)
6506 int save_arg_vars[MAX_ARG_GRP] = { 0, };
6507 unsigned char cbits[MAX_OPS / 8];
6508 const struct parsed_proto *pp_c;
6509 struct parsed_proto *pp;
6510 struct func_prototype *fp;
6511 struct parsed_op *po;
6512 int regmask_dummy = 0;
6514 int max_bp_offset = 0;
6519 pp_c = proto_parse(g_fhdr, funcn, 1);
6521 // already in seed, will add to hg_fp later
6524 fp = hg_fp_add(funcn);
6526 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
6527 g_stack_frame_used = 0;
6530 // - resolve all branches
6531 // - parse calls with labels
6532 resolve_branches_parse_calls(opcnt);
6535 // - handle ebp/esp frame, remove ops related to it
6536 scan_prologue_epilogue(opcnt);
6539 // - remove dead labels
6541 for (i = 0; i < opcnt; i++)
6543 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
6549 if (po->flags & (OPF_RMD|OPF_DONE))
6552 if (po->op == OP_CALL) {
6553 if (po->operand[0].type == OPT_LABEL)
6554 hg_fp_add_dep(fp, opr_name(po, 0));
6555 else if (po->pp != NULL)
6556 hg_fp_add_dep(fp, po->pp->name);
6561 // - remove dead labels
6562 // - handle push <const>/pop pairs
6563 for (i = 0; i < opcnt; i++)
6565 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
6571 if (po->flags & (OPF_RMD|OPF_DONE))
6574 if (po->op == OP_PUSH && po->operand[0].type == OPT_CONST)
6575 scan_for_pop_const(i, opcnt, i + opcnt * 13);
6579 // - process trivial calls
6580 for (i = 0; i < opcnt; i++)
6583 if (po->flags & (OPF_RMD|OPF_DONE))
6586 if (po->op == OP_CALL)
6588 pp = process_call_early(i, opcnt, &j);
6590 if (!(po->flags & OPF_ATAIL))
6591 // since we know the args, try to collect them
6592 if (collect_call_args_early(po, i, pp, ®mask_dummy) != 0)
6598 // commit esp adjust
6599 if (ops[j].op != OP_POP)
6600 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
6602 for (l = 0; l < pp->argc_stack; l++)
6603 ops[j + l].flags |= OPF_DONE | OPF_RMD | OPF_NOREGS;
6607 po->flags |= OPF_DONE;
6613 // - track saved regs (simple)
6615 for (i = 0; i < opcnt; i++)
6618 if (po->flags & (OPF_RMD|OPF_DONE))
6621 if (po->op == OP_PUSH && po->operand[0].type == OPT_REG
6622 && po->operand[0].reg != xCX)
6624 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg, 0);
6626 // regmask_save |= 1 << po->operand[0].reg; // do it later
6627 po->flags |= OPF_RSAVE | OPF_RMD | OPF_DONE;
6628 scan_for_pop_ret(i + 1, opcnt, po->operand[0].reg, OPF_RMD);
6631 else if (po->op == OP_CALL)
6633 pp = process_call(i, opcnt);
6635 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
6636 // since we know the args, collect them
6637 ret = collect_call_args(po, i, pp, ®mask_dummy, save_arg_vars,
6644 memset(cbits, 0, sizeof(cbits));
6648 gen_hdr_dep_pass(0, opcnt, cbits, fp, 0, 0, ®mask_dep, &has_ret);
6650 // find unreachable code - must be fixed in IDA
6651 for (i = 0; i < opcnt; i++)
6653 if (cbits[i >> 3] & (1 << (i & 7)))
6656 if (g_labels[i] == NULL && i > 0 && ops[i - 1].op == OP_CALL
6657 && ops[i - 1].pp != NULL && ops[i - 1].pp->is_osinc)
6659 // the compiler sometimes still generates code after
6660 // noreturn OS functions
6663 if (ops[i].op != OP_NOP)
6664 ferr(&ops[i], "unreachable code\n");
6667 for (i = 0; i < g_eqcnt; i++) {
6668 if (g_eqs[i].offset > max_bp_offset && g_eqs[i].offset < 4*32)
6669 max_bp_offset = g_eqs[i].offset;
6672 if (fp->argc_stack < 0) {
6673 max_bp_offset = (max_bp_offset + 3) & ~3;
6674 fp->argc_stack = max_bp_offset / 4;
6675 if ((g_ida_func_attr & IDAFA_BP_FRAME) && fp->argc_stack > 0)
6679 fp->regmask_dep = regmask_dep & ~(1 << xSP);
6680 fp->has_ret = has_ret;
6682 printf("// has_ret %d, regmask_dep %x\n",
6683 fp->has_ret, fp->regmask_dep);
6684 output_hdr_fp(stdout, fp, 1);
6685 if (IS(funcn, "sub_10007F72")) exit(1);
6688 gen_x_cleanup(opcnt);
6691 static void hg_fp_resolve_deps(struct func_prototype *fp)
6693 struct func_prototype fp_s;
6697 // this thing is recursive, so mark first..
6698 fp->dep_resolved = 1;
6700 for (i = 0; i < fp->dep_func_cnt; i++) {
6701 strcpy(fp_s.name, fp->dep_func[i].name);
6702 fp->dep_func[i].proto = bsearch(&fp_s, hg_fp, hg_fp_cnt,
6703 sizeof(hg_fp[0]), hg_fp_cmp_name);
6704 if (fp->dep_func[i].proto != NULL) {
6705 if (!fp->dep_func[i].proto->dep_resolved)
6706 hg_fp_resolve_deps(fp->dep_func[i].proto);
6708 dep = ~fp->dep_func[i].regmask_live
6709 & fp->dep_func[i].proto->regmask_dep;
6710 fp->regmask_dep |= dep;
6711 // printf("dep %s %s |= %x\n", fp->name,
6712 // fp->dep_func[i].name, dep);
6714 if (fp->has_ret == -1 && fp->dep_func[i].ret_dep)
6715 fp->has_ret = fp->dep_func[i].proto->has_ret;
6720 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
6723 const struct parsed_proto *pp;
6724 char *p, namebuf[NAMELEN];
6730 for (; count > 0; count--, fp++) {
6731 if (fp->has_ret == -1)
6732 fprintf(fout, "// ret unresolved\n");
6734 fprintf(fout, "// dep:");
6735 for (j = 0; j < fp->dep_func_cnt; j++) {
6736 fprintf(fout, " %s/", fp->dep_func[j].name);
6737 if (fp->dep_func[j].proto != NULL)
6738 fprintf(fout, "%04x/%d", fp->dep_func[j].proto->regmask_dep,
6739 fp->dep_func[j].proto->has_ret);
6741 fprintf(fout, "\n");
6744 p = strchr(fp->name, '@');
6746 memcpy(namebuf, fp->name, p - fp->name);
6747 namebuf[p - fp->name] = 0;
6755 pp = proto_parse(g_fhdr, name, 1);
6756 if (pp != NULL && pp->is_include)
6759 if (fp->pp != NULL) {
6760 // part of seed, output later
6764 regmask_dep = fp->regmask_dep;
6765 argc_stack = fp->argc_stack;
6767 fprintf(fout, "%-5s", fp->pp ? fp->pp->ret_type.name :
6768 (fp->has_ret ? "int" : "void"));
6769 if (regmask_dep && (fp->is_stdcall || argc_stack == 0)
6770 && (regmask_dep & ~((1 << xCX) | (1 << xDX))) == 0)
6772 fprintf(fout, " __fastcall ");
6773 if (!(regmask_dep & (1 << xDX)) && argc_stack == 0)
6779 else if (regmask_dep && !fp->is_stdcall) {
6780 fprintf(fout, "/*__usercall*/ ");
6782 else if (regmask_dep) {
6783 fprintf(fout, "/*__userpurge*/ ");
6785 else if (fp->is_stdcall)
6786 fprintf(fout, " __stdcall ");
6788 fprintf(fout, " __cdecl ");
6790 fprintf(fout, "%s(", name);
6793 for (j = 0; j < xSP; j++) {
6794 if (regmask_dep & (1 << j)) {
6797 fprintf(fout, ", ");
6799 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6801 fprintf(fout, "int");
6802 fprintf(fout, " a%d/*<%s>*/", arg, regs_r32[j]);
6806 for (j = 0; j < argc_stack; j++) {
6809 fprintf(fout, ", ");
6810 if (fp->pp != NULL) {
6811 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6812 if (!fp->pp->arg[arg - 1].type.is_ptr)
6816 fprintf(fout, "int ");
6817 fprintf(fout, "a%d", arg);
6820 fprintf(fout, ");\n");
6824 static void output_hdr(FILE *fout)
6826 static const char *lmod_c_names[] = {
6827 [OPLM_UNSPEC] = "???",
6828 [OPLM_BYTE] = "uint8_t",
6829 [OPLM_WORD] = "uint16_t",
6830 [OPLM_DWORD] = "uint32_t",
6831 [OPLM_QWORD] = "uint64_t",
6833 const struct scanned_var *var;
6834 struct func_prototype *fp;
6835 char line[256] = { 0, };
6839 // add stuff from headers
6840 for (i = 0; i < pp_cache_size; i++) {
6841 if (pp_cache[i].is_cinc && !pp_cache[i].is_stdcall)
6842 snprintf(name, sizeof(name), "_%s", pp_cache[i].name);
6844 snprintf(name, sizeof(name), "%s", pp_cache[i].name);
6845 fp = hg_fp_add(name);
6846 fp->pp = &pp_cache[i];
6847 fp->argc_stack = fp->pp->argc_stack;
6848 fp->is_stdcall = fp->pp->is_stdcall;
6849 fp->regmask_dep = get_pp_arg_regmask_src(fp->pp);
6850 fp->has_ret = !IS(fp->pp->ret_type.name, "void");
6854 qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_name);
6855 for (i = 0; i < hg_fp_cnt; i++)
6856 hg_fp_resolve_deps(&hg_fp[i]);
6858 // note: messes up .proto ptr, don't use
6859 //qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_id);
6862 for (i = 0; i < hg_var_cnt; i++) {
6865 if (var->pp != NULL)
6868 else if (var->is_c_str)
6869 fprintf(fout, "extern %-8s %s[];", "char", var->name);
6871 fprintf(fout, "extern %-8s %s;",
6872 lmod_c_names[var->lmod], var->name);
6875 fprintf(fout, " // seeded");
6876 fprintf(fout, "\n");
6879 fprintf(fout, "\n");
6881 // output function prototypes
6882 output_hdr_fp(fout, hg_fp, hg_fp_cnt);
6885 fprintf(fout, "\n// - seed -\n");
6888 while (fgets(line, sizeof(line), g_fhdr))
6889 fwrite(line, 1, strlen(line), fout);
6892 // '=' needs special treatment
6894 static char *next_word_s(char *w, size_t wsize, char *s)
6903 for (i = 1; i < wsize - 1; i++) {
6905 printf("warning: missing closing quote: \"%s\"\n", s);
6914 for (; i < wsize - 1; i++) {
6915 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
6921 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
6922 printf("warning: '%s' truncated\n", w);
6927 static void scan_variables(FILE *fasm)
6929 struct scanned_var *var;
6930 char line[256] = { 0, };
6938 // skip to next data section
6939 while (my_fgets(line, sizeof(line), fasm))
6944 if (*p == 0 || *p == ';')
6947 p = sskip(next_word_s(words[0], sizeof(words[0]), p));
6948 if (*p == 0 || *p == ';')
6951 if (*p != 's' || !IS_START(p, "segment para public"))
6957 if (p == NULL || !IS_START(p, "segment para public"))
6961 if (!IS_START(p, "'DATA'"))
6965 while (my_fgets(line, sizeof(line), fasm))
6974 if (*p == 0 || *p == ';')
6977 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6978 words[wordc][0] = 0;
6979 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6980 if (*p == 0 || *p == ';') {
6986 if (wordc == 2 && IS(words[1], "ends"))
6991 if (IS_START(words[0], "__IMPORT_DESCRIPTOR_")) {
6992 // when this starts, we don't need anything from this section
6996 if ((hg_var_cnt & 0xff) == 0) {
6997 hg_vars = realloc(hg_vars, sizeof(hg_vars[0])
6998 * (hg_var_cnt + 0x100));
6999 my_assert_not(hg_vars, NULL);
7000 memset(hg_vars + hg_var_cnt, 0, sizeof(hg_vars[0]) * 0x100);
7003 var = &hg_vars[hg_var_cnt++];
7004 snprintf(var->name, sizeof(var->name), "%s", words[0]);
7006 // maybe already in seed header?
7007 var->pp = proto_parse(g_fhdr, var->name, 1);
7008 if (var->pp != NULL) {
7009 if (var->pp->is_fptr) {
7010 var->lmod = OPLM_DWORD;
7013 else if (var->pp->is_func)
7015 else if (!guess_lmod_from_c_type(&var->lmod, &var->pp->type))
7016 aerr("unhandled C type '%s' for '%s'\n",
7017 var->pp->type.name, var->name);
7023 if (IS(words[1], "dd"))
7024 var->lmod = OPLM_DWORD;
7025 else if (IS(words[1], "dw"))
7026 var->lmod = OPLM_WORD;
7027 else if (IS(words[1], "db")) {
7028 var->lmod = OPLM_BYTE;
7029 if (wordc >= 3 && (l = strlen(words[2])) > 4) {
7030 if (words[2][0] == '\'' && IS(words[2] + l - 2, ",0"))
7034 else if (IS(words[1], "dq"))
7035 var->lmod = OPLM_QWORD;
7036 //else if (IS(words[1], "dt"))
7038 aerr("type '%s' not known\n", words[1]);
7046 static void set_label(int i, const char *name)
7052 p = strchr(name, ':');
7056 if (g_labels[i] != NULL && !IS_START(g_labels[i], "algn_"))
7057 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
7058 g_labels[i] = realloc(g_labels[i], len + 1);
7059 my_assert_not(g_labels[i], NULL);
7060 memcpy(g_labels[i], name, len);
7061 g_labels[i][len] = 0;
7070 static struct chunk_item *func_chunks;
7071 static int func_chunk_cnt;
7072 static int func_chunk_alloc;
7074 static void add_func_chunk(FILE *fasm, const char *name, int line)
7076 if (func_chunk_cnt >= func_chunk_alloc) {
7077 func_chunk_alloc *= 2;
7078 func_chunks = realloc(func_chunks,
7079 func_chunk_alloc * sizeof(func_chunks[0]));
7080 my_assert_not(func_chunks, NULL);
7082 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
7083 func_chunks[func_chunk_cnt].name = strdup(name);
7084 func_chunks[func_chunk_cnt].asmln = line;
7088 static int cmp_chunks(const void *p1, const void *p2)
7090 const struct chunk_item *c1 = p1, *c2 = p2;
7091 return strcmp(c1->name, c2->name);
7094 static int cmpstringp(const void *p1, const void *p2)
7096 return strcmp(*(char * const *)p1, *(char * const *)p2);
7099 static void scan_ahead(FILE *fasm)
7109 oldpos = ftell(fasm);
7112 while (my_fgets(line, sizeof(line), fasm))
7123 // get rid of random tabs
7124 for (i = 0; line[i] != 0; i++)
7125 if (line[i] == '\t')
7128 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
7131 next_word(words[0], sizeof(words[0]), p);
7132 if (words[0][0] == 0)
7133 aerr("missing name for func chunk?\n");
7135 add_func_chunk(fasm, words[0], asmln);
7137 else if (IS_START(p, "; sctend"))
7143 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
7144 words[wordc][0] = 0;
7145 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
7146 if (*p == 0 || *p == ';') {
7152 if (wordc == 2 && IS(words[1], "ends"))
7156 fseek(fasm, oldpos, SEEK_SET);
7160 int main(int argc, char *argv[])
7162 FILE *fout, *fasm, *frlist;
7163 struct parsed_data *pd = NULL;
7165 char **rlist = NULL;
7167 int rlist_alloc = 0;
7168 int func_chunks_used = 0;
7169 int func_chunks_sorted = 0;
7170 int func_chunk_i = -1;
7171 long func_chunk_ret = 0;
7172 int func_chunk_ret_ln = 0;
7173 int scanned_ahead = 0;
7175 char words[20][256];
7176 enum opr_lenmod lmod;
7177 char *sctproto = NULL;
7179 int pending_endp = 0;
7181 int skip_warned = 0;
7194 for (arg = 1; arg < argc; arg++) {
7195 if (IS(argv[arg], "-v"))
7197 else if (IS(argv[arg], "-rf"))
7198 g_allow_regfunc = 1;
7199 else if (IS(argv[arg], "-m"))
7201 else if (IS(argv[arg], "-hdr"))
7202 g_header_mode = g_quiet_pp = g_allow_regfunc = 1;
7207 if (argc < arg + 3) {
7208 printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdr.h> [rlist]*\n"
7209 "%s -hdr <out.h> <.asm> <seed.h> [rlist]*\n"
7211 " -hdr - header generation mode\n"
7212 " -rf - allow unannotated indirect calls\n"
7213 " -m - allow multiple .text sections\n"
7214 "[rlist] is a file with function names to skip,"
7222 asmfn = argv[arg++];
7223 fasm = fopen(asmfn, "r");
7224 my_assert_not(fasm, NULL);
7226 hdrfn = argv[arg++];
7227 g_fhdr = fopen(hdrfn, "r");
7228 my_assert_not(g_fhdr, NULL);
7231 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
7232 my_assert_not(rlist, NULL);
7233 // needs special handling..
7234 rlist[rlist_len++] = "__alloca_probe";
7236 func_chunk_alloc = 32;
7237 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
7238 my_assert_not(func_chunks, NULL);
7240 memset(words, 0, sizeof(words));
7242 for (; arg < argc; arg++) {
7243 frlist = fopen(argv[arg], "r");
7244 my_assert_not(frlist, NULL);
7246 while (my_fgets(line, sizeof(line), frlist)) {
7248 if (*p == 0 || *p == ';')
7251 if (IS_START(p, "#if 0")
7252 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
7256 else if (IS_START(p, "#endif"))
7263 p = next_word(words[0], sizeof(words[0]), p);
7264 if (words[0][0] == 0)
7267 if (rlist_len >= rlist_alloc) {
7268 rlist_alloc = rlist_alloc * 2 + 64;
7269 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
7270 my_assert_not(rlist, NULL);
7272 rlist[rlist_len++] = strdup(words[0]);
7281 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
7283 fout = fopen(argv[arg_out], "w");
7284 my_assert_not(fout, NULL);
7287 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
7288 my_assert_not(g_eqs, NULL);
7290 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
7291 g_label_refs[i].i = -1;
7292 g_label_refs[i].next = NULL;
7296 scan_variables(fasm);
7298 while (my_fgets(line, sizeof(line), fasm))
7307 // get rid of random tabs
7308 for (i = 0; line[i] != 0; i++)
7309 if (line[i] == '\t')
7314 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
7315 goto do_pending_endp; // eww..
7317 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
7319 static const char *attrs[] = {
7328 // parse IDA's attribute-list comment
7329 g_ida_func_attr = 0;
7332 for (; *p != 0; p = sskip(p)) {
7333 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
7334 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
7335 g_ida_func_attr |= 1 << i;
7336 p += strlen(attrs[i]);
7340 if (i == ARRAY_SIZE(attrs)) {
7341 anote("unparsed IDA attr: %s\n", p);
7344 if (IS(attrs[i], "fpd=")) {
7345 p = next_word(words[0], sizeof(words[0]), p);
7350 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
7353 next_word(words[0], sizeof(words[0]), p);
7354 if (words[0][0] == 0)
7355 aerr("missing name for func chunk?\n");
7357 if (!scanned_ahead) {
7358 add_func_chunk(fasm, words[0], asmln);
7359 func_chunks_sorted = 0;
7362 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
7364 if (func_chunk_i >= 0) {
7365 if (func_chunk_i < func_chunk_cnt
7366 && IS(func_chunks[func_chunk_i].name, g_func))
7368 // move on to next chunk
7369 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
7371 aerr("seek failed for '%s' chunk #%d\n",
7372 g_func, func_chunk_i);
7373 asmln = func_chunks[func_chunk_i].asmln;
7377 if (func_chunk_ret == 0)
7378 aerr("no return from chunk?\n");
7379 fseek(fasm, func_chunk_ret, SEEK_SET);
7380 asmln = func_chunk_ret_ln;
7386 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
7387 func_chunks_used = 1;
7389 if (IS_START(g_func, "sub_")) {
7390 unsigned long addr = strtoul(p, NULL, 16);
7391 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
7392 if (addr > f_addr && !scanned_ahead) {
7393 //anote("scan_ahead caused by '%s', addr %lx\n",
7397 func_chunks_sorted = 0;
7405 for (i = wordc; i < ARRAY_SIZE(words); i++)
7407 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
7408 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
7409 if (*p == 0 || *p == ';') {
7414 if (*p != 0 && *p != ';')
7415 aerr("too many words\n");
7417 // alow asm patches in comments
7419 if (IS_START(p, "; sctpatch:")) {
7421 if (*p == 0 || *p == ';')
7423 goto parse_words; // lame
7425 if (IS_START(p, "; sctproto:")) {
7426 sctproto = strdup(p + 11);
7428 else if (IS_START(p, "; sctend")) {
7437 awarn("wordc == 0?\n");
7441 // don't care about this:
7442 if (words[0][0] == '.'
7443 || IS(words[0], "include")
7444 || IS(words[0], "assume") || IS(words[1], "segment")
7445 || IS(words[0], "align"))
7451 // do delayed endp processing to collect switch jumptables
7453 if (in_func && !g_skip_func && !end && wordc >= 2
7454 && ((words[0][0] == 'd' && words[0][2] == 0)
7455 || (words[1][0] == 'd' && words[1][2] == 0)))
7458 if (words[1][0] == 'd' && words[1][2] == 0) {
7460 if (g_func_pd_cnt >= pd_alloc) {
7461 pd_alloc = pd_alloc * 2 + 16;
7462 g_func_pd = realloc(g_func_pd,
7463 sizeof(g_func_pd[0]) * pd_alloc);
7464 my_assert_not(g_func_pd, NULL);
7466 pd = &g_func_pd[g_func_pd_cnt];
7468 memset(pd, 0, sizeof(*pd));
7469 strcpy(pd->label, words[0]);
7470 pd->type = OPT_CONST;
7471 pd->lmod = lmod_from_directive(words[1]);
7477 anote("skipping alignment byte?\n");
7480 lmod = lmod_from_directive(words[0]);
7481 if (lmod != pd->lmod)
7482 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
7485 if (pd->count_alloc < pd->count + wordc) {
7486 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
7487 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
7488 my_assert_not(pd->d, NULL);
7490 for (; i < wordc; i++) {
7491 if (IS(words[i], "offset")) {
7492 pd->type = OPT_OFFSET;
7495 p = strchr(words[i], ',');
7498 if (pd->type == OPT_OFFSET)
7499 pd->d[pd->count].u.label = strdup(words[i]);
7501 pd->d[pd->count].u.val = parse_number(words[i]);
7502 pd->d[pd->count].bt_i = -1;
7508 if (in_func && !g_skip_func) {
7510 gen_hdr(g_func, pi);
7512 gen_func(fout, g_fhdr, g_func, pi);
7517 g_ida_func_attr = 0;
7521 func_chunks_used = 0;
7524 memset(&ops, 0, pi * sizeof(ops[0]));
7529 for (i = 0; i < g_func_pd_cnt; i++) {
7531 if (pd->type == OPT_OFFSET) {
7532 for (j = 0; j < pd->count; j++)
7533 free(pd->d[j].u.label);
7547 if (IS(words[1], "proc")) {
7549 aerr("proc '%s' while in_func '%s'?\n",
7552 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
7554 strcpy(g_func, words[0]);
7555 set_label(0, words[0]);
7560 if (IS(words[1], "endp"))
7563 aerr("endp '%s' while not in_func?\n", words[0]);
7564 if (!IS(g_func, words[0]))
7565 aerr("endp '%s' while in_func '%s'?\n",
7568 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
7569 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
7575 if (!g_skip_func && func_chunks_used) {
7576 // start processing chunks
7577 struct chunk_item *ci, key = { g_func, 0 };
7579 func_chunk_ret = ftell(fasm);
7580 func_chunk_ret_ln = asmln;
7581 if (!func_chunks_sorted) {
7582 qsort(func_chunks, func_chunk_cnt,
7583 sizeof(func_chunks[0]), cmp_chunks);
7584 func_chunks_sorted = 1;
7586 ci = bsearch(&key, func_chunks, func_chunk_cnt,
7587 sizeof(func_chunks[0]), cmp_chunks);
7589 aerr("'%s' needs chunks, but none found\n", g_func);
7590 func_chunk_i = ci - func_chunks;
7591 for (; func_chunk_i > 0; func_chunk_i--)
7592 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
7595 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
7597 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
7598 asmln = func_chunks[func_chunk_i].asmln;
7606 if (wordc == 2 && IS(words[1], "ends")) {
7610 goto do_pending_endp;
7614 // scan for next text segment
7615 while (my_fgets(line, sizeof(line), fasm)) {
7618 if (*p == 0 || *p == ';')
7621 if (strstr(p, "segment para public 'CODE' use32"))
7628 p = strchr(words[0], ':');
7630 set_label(pi, words[0]);
7634 if (!in_func || g_skip_func) {
7635 if (!skip_warned && !g_skip_func && g_labels[pi] != NULL) {
7637 anote("skipping from '%s'\n", g_labels[pi]);
7641 g_labels[pi] = NULL;
7645 if (wordc > 1 && IS(words[1], "="))
7648 aerr("unhandled equ, wc=%d\n", wordc);
7649 if (g_eqcnt >= eq_alloc) {
7651 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
7652 my_assert_not(g_eqs, NULL);
7655 len = strlen(words[0]);
7656 if (len > sizeof(g_eqs[0].name) - 1)
7657 aerr("equ name too long: %d\n", len);
7658 strcpy(g_eqs[g_eqcnt].name, words[0]);
7660 if (!IS(words[3], "ptr"))
7661 aerr("unhandled equ\n");
7662 if (IS(words[2], "dword"))
7663 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
7664 else if (IS(words[2], "word"))
7665 g_eqs[g_eqcnt].lmod = OPLM_WORD;
7666 else if (IS(words[2], "byte"))
7667 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
7668 else if (IS(words[2], "qword"))
7669 g_eqs[g_eqcnt].lmod = OPLM_QWORD;
7671 aerr("bad lmod: '%s'\n", words[2]);
7673 g_eqs[g_eqcnt].offset = parse_number(words[4]);
7678 if (pi >= ARRAY_SIZE(ops))
7679 aerr("too many ops\n");
7681 parse_op(&ops[pi], words, wordc);
7683 if (sctproto != NULL) {
7684 if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
7685 ops[pi].datap = sctproto;
7701 // vim:ts=2:shiftwidth=2:expandtab