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 */
134 // must be sorted (larger len must be further in enum)
143 #define MAX_OPERANDS 3
148 enum opr_lenmod lmod;
149 unsigned int is_ptr:1; // pointer in C
150 unsigned int is_array:1; // array in C
151 unsigned int type_from_var:1; // .. in header, sometimes wrong
152 unsigned int size_mismatch:1; // type override differs from C
153 unsigned int size_lt:1; // type override is larger than C
154 unsigned int had_ds:1; // had ds: prefix
155 const struct parsed_proto *pp; // for OPT_LABEL
163 struct parsed_opr operand[MAX_OPERANDS];
166 unsigned char pfo_inv;
167 unsigned char operand_cnt;
168 unsigned char p_argnum; // arg push: altered before call arg #
169 unsigned char p_arggrp; // arg push: arg group # for above
170 unsigned char p_argpass;// arg push: arg of host func
171 short p_argnext;// arg push: same arg pushed elsewhere or -1
172 int regmask_src; // all referensed regs
174 int pfomask; // flagop: parsed_flag_op that can't be delayed
175 int cc_scratch; // scratch storage during analysis
176 int bt_i; // branch target for branches
177 struct parsed_data *btj;// branch targets for jumptables
178 struct parsed_proto *pp;// parsed_proto for OP_CALL
184 // OP_CALL - parser proto hint (str)
185 // (OPF_CC) - points to one of (OPF_FLAGS) that affects cc op
186 // OP_PUSH - points to OP_POP in complex push/pop graph
187 // OP_POP - points to OP_PUSH in simple push/pop pair
191 enum opr_lenmod lmod;
198 enum opr_lenmod lmod;
212 struct label_ref *next;
216 IDAFA_BP_FRAME = (1 << 0),
217 IDAFA_LIB_FUNC = (1 << 1),
218 IDAFA_STATIC = (1 << 2),
219 IDAFA_NORETURN = (1 << 3),
220 IDAFA_THUNK = (1 << 4),
221 IDAFA_FPD = (1 << 5),
224 // note: limited to 32k due to p_argnext
226 #define MAX_ARG_GRP 2
228 static struct parsed_op ops[MAX_OPS];
229 static struct parsed_equ *g_eqs;
231 static char *g_labels[MAX_OPS];
232 static struct label_ref g_label_refs[MAX_OPS];
233 static const struct parsed_proto *g_func_pp;
234 static struct parsed_data *g_func_pd;
235 static int g_func_pd_cnt;
236 static char g_func[256];
237 static char g_comment[256];
238 static int g_bp_frame;
239 static int g_sp_frame;
240 static int g_stack_frame_used;
241 static int g_stack_fsz;
242 static int g_ida_func_attr;
243 static int g_skip_func;
244 static int g_allow_regfunc;
245 static int g_quiet_pp;
246 static int g_header_mode;
248 #define ferr(op_, fmt, ...) do { \
249 printf("%s:%d: error %u: [%s] '%s': " fmt, asmfn, (op_)->asmln, \
250 __LINE__, g_func, dump_op(op_), ##__VA_ARGS__); \
254 #define fnote(op_, fmt, ...) \
255 printf("%s:%d: note: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
256 dump_op(op_), ##__VA_ARGS__)
258 #define ferr_assert(op_, cond) do { \
259 if (!(cond)) ferr(op_, "assertion '%s' failed on ln :%d\n", #cond, \
263 const char *regs_r32[] = {
264 "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp",
265 // not r32, but list here for easy parsing and printing
266 "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
268 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
269 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
270 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
272 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
274 // possible basic comparison types (without inversion)
275 enum parsed_flag_op {
279 PFO_BE, // 6 CF=1||ZF=1
283 PFO_LE, // e ZF=1||SF!=OF
286 #define PFOB_O (1 << PFO_O)
287 #define PFOB_C (1 << PFO_C)
288 #define PFOB_Z (1 << PFO_Z)
289 #define PFOB_S (1 << PFO_S)
291 static const char *parsed_flag_op_names[] = {
292 "o", "c", "z", "be", "s", "p", "l", "le"
295 static int char_array_i(const char *array[], size_t len, const char *s)
299 for (i = 0; i < len; i++)
306 static void printf_number(char *buf, size_t buf_size,
307 unsigned long number)
309 // output in C-friendly form
310 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
313 static int check_segment_prefix(const char *s)
315 if (s[0] == 0 || s[1] != 's' || s[2] != ':')
329 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
333 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
335 *reg_lmod = OPLM_QWORD;
339 *reg_lmod = OPLM_DWORD;
342 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
344 *reg_lmod = OPLM_WORD;
347 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
349 *reg_lmod = OPLM_BYTE;
352 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
354 *reg_lmod = OPLM_BYTE;
361 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
363 enum opr_lenmod lmod;
376 while (my_isblank(*s))
378 for (; my_issep(*s); d++, s++)
380 while (my_isblank(*s))
384 // skip '?s:' prefixes
385 if (check_segment_prefix(s))
388 s = next_idt(w, sizeof(w), s);
393 reg = parse_reg(&lmod, w);
395 *regmask |= 1 << reg;
399 if ('0' <= w[0] && w[0] <= '9') {
400 number = parse_number(w);
401 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
405 // probably some label/identifier - pass
408 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
412 strcpy(name, cvtbuf);
417 static int is_reg_in_str(const char *s)
421 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
424 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
425 if (!strncmp(s, regs_r32[i], 3))
431 static const char *parse_stack_el(const char *name, char *extra_reg,
434 const char *p, *p2, *s;
440 if (g_bp_frame || early_try)
443 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
445 if (extra_reg != NULL) {
446 strncpy(extra_reg, name, 3);
451 if (IS_START(p, "ebp+")) {
455 if (p2 != NULL && is_reg_in_str(p)) {
456 if (extra_reg != NULL) {
457 strncpy(extra_reg, p, p2 - p);
458 extra_reg[p2 - p] = 0;
463 if (!('0' <= *p && *p <= '9'))
470 if (!IS_START(name, "esp+"))
476 if (is_reg_in_str(s)) {
477 if (extra_reg != NULL) {
478 strncpy(extra_reg, s, p - s);
479 extra_reg[p - s] = 0;
484 aerr("%s IDA stackvar not set?\n", __func__);
486 if (!('0' <= *s && *s <= '9')) {
487 aerr("%s IDA stackvar offset not set?\n", __func__);
490 if (s[0] == '0' && s[1] == 'x')
493 if (len < sizeof(buf) - 1) {
494 strncpy(buf, s, len);
496 val = strtol(buf, &endp, 16);
497 if (val == 0 || *endp != 0) {
498 aerr("%s num parse fail for '%s'\n", __func__, buf);
507 if ('0' <= *p && *p <= '9')
513 static int guess_lmod_from_name(struct parsed_opr *opr)
515 if (IS_START(opr->name, "dword_") || IS_START(opr->name, "off_")) {
516 opr->lmod = OPLM_DWORD;
519 if (IS_START(opr->name, "word_")) {
520 opr->lmod = OPLM_WORD;
523 if (IS_START(opr->name, "byte_")) {
524 opr->lmod = OPLM_BYTE;
527 if (IS_START(opr->name, "qword_")) {
528 opr->lmod = OPLM_QWORD;
534 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
535 const struct parsed_type *c_type)
537 static const char *dword_types[] = {
538 "uint32_t", "int", "_DWORD", "UINT_PTR", "DWORD",
539 "WPARAM", "LPARAM", "UINT", "__int32",
540 "LONG", "HIMC", "BOOL", "size_t",
543 static const char *word_types[] = {
544 "uint16_t", "int16_t", "_WORD", "WORD",
545 "unsigned __int16", "__int16",
547 static const char *byte_types[] = {
548 "uint8_t", "int8_t", "char",
549 "unsigned __int8", "__int8", "BYTE", "_BYTE",
551 // structures.. deal the same as with _UNKNOWN for now
557 if (c_type->is_ptr) {
562 n = skip_type_mod(c_type->name);
564 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
565 if (IS(n, dword_types[i])) {
571 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
572 if (IS(n, word_types[i])) {
578 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
579 if (IS(n, byte_types[i])) {
588 static char *default_cast_to(char *buf, size_t buf_size,
589 struct parsed_opr *opr)
595 if (opr->pp == NULL || opr->pp->type.name == NULL
598 snprintf(buf, buf_size, "%s", "(void *)");
602 snprintf(buf, buf_size, "(%s)", opr->pp->type.name);
606 static enum opr_type lmod_from_directive(const char *d)
610 else if (IS(d, "dw"))
612 else if (IS(d, "db"))
615 aerr("unhandled directive: '%s'\n", d);
619 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
625 *regmask |= 1 << reg;
628 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
631 static int parse_operand(struct parsed_opr *opr,
632 int *regmask, int *regmask_indirect,
633 char words[16][256], int wordc, int w, unsigned int op_flags)
635 const struct parsed_proto *pp = NULL;
636 enum opr_lenmod tmplmod;
637 unsigned long number;
645 aerr("parse_operand w %d, wordc %d\n", w, wordc);
649 for (i = w; i < wordc; i++) {
650 len = strlen(words[i]);
651 if (words[i][len - 1] == ',') {
652 words[i][len - 1] = 0;
658 wordc_in = wordc - w;
660 if ((op_flags & OPF_JMP) && wordc_in > 0
661 && !('0' <= words[w][0] && words[w][0] <= '9'))
663 const char *label = NULL;
665 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
666 && IS(words[w + 1], "ptr"))
667 label = words[w + 2];
668 else if (wordc_in == 2 && IS(words[w], "short"))
669 label = words[w + 1];
670 else if (wordc_in == 1
671 && strchr(words[w], '[') == NULL
672 && parse_reg(&tmplmod, words[w]) < 0)
676 opr->type = OPT_LABEL;
677 ret = check_segment_prefix(label);
680 aerr("fs/gs used\n");
684 strcpy(opr->name, label);
690 if (IS(words[w + 1], "ptr")) {
691 if (IS(words[w], "dword"))
692 opr->lmod = OPLM_DWORD;
693 else if (IS(words[w], "word"))
694 opr->lmod = OPLM_WORD;
695 else if (IS(words[w], "byte"))
696 opr->lmod = OPLM_BYTE;
697 else if (IS(words[w], "qword"))
698 opr->lmod = OPLM_QWORD;
700 aerr("type parsing failed\n");
702 wordc_in = wordc - w;
707 if (IS(words[w], "offset")) {
708 opr->type = OPT_OFFSET;
709 opr->lmod = OPLM_DWORD;
710 strcpy(opr->name, words[w + 1]);
711 pp = proto_parse(g_fhdr, opr->name, 1);
714 if (IS(words[w], "(offset")) {
715 p = strchr(words[w + 1], ')');
717 aerr("parse of bracketed offset failed\n");
719 opr->type = OPT_OFFSET;
720 strcpy(opr->name, words[w + 1]);
726 aerr("parse_operand 1 word expected\n");
728 ret = check_segment_prefix(words[w]);
731 aerr("fs/gs used\n");
733 memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
735 strcpy(opr->name, words[w]);
737 if (words[w][0] == '[') {
738 opr->type = OPT_REGMEM;
739 ret = sscanf(words[w], "[%[^]]]", opr->name);
741 aerr("[] parse failure\n");
743 parse_indmode(opr->name, regmask_indirect, 1);
744 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL, 1))
747 struct parsed_equ *eq =
748 equ_find(NULL, parse_stack_el(opr->name, NULL, 1), &i);
750 opr->lmod = eq->lmod;
754 else if (strchr(words[w], '[')) {
756 p = strchr(words[w], '[');
757 opr->type = OPT_REGMEM;
758 parse_indmode(p, regmask_indirect, 0);
759 strncpy(buf, words[w], p - words[w]);
760 buf[p - words[w]] = 0;
761 pp = proto_parse(g_fhdr, buf, 1);
764 else if (('0' <= words[w][0] && words[w][0] <= '9')
765 || words[w][0] == '-')
767 number = parse_number(words[w]);
768 opr->type = OPT_CONST;
770 printf_number(opr->name, sizeof(opr->name), number);
774 ret = parse_reg(&tmplmod, opr->name);
776 setup_reg_opr(opr, ret, tmplmod, regmask);
780 // most likely var in data segment
781 opr->type = OPT_LABEL;
782 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
786 if (pp->is_fptr || pp->is_func) {
787 opr->lmod = OPLM_DWORD;
791 tmplmod = OPLM_UNSPEC;
792 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
793 anote("unhandled C type '%s' for '%s'\n",
794 pp->type.name, opr->name);
796 if (opr->lmod == OPLM_UNSPEC) {
798 opr->type_from_var = 1;
800 else if (opr->lmod != tmplmod) {
801 opr->size_mismatch = 1;
802 if (tmplmod < opr->lmod)
805 opr->is_ptr = pp->type.is_ptr;
807 opr->is_array = pp->type.is_array;
811 if (opr->lmod == OPLM_UNSPEC)
812 guess_lmod_from_name(opr);
816 static const struct {
821 { "repe", OPF_REP|OPF_REPZ },
822 { "repz", OPF_REP|OPF_REPZ },
823 { "repne", OPF_REP|OPF_REPNZ },
824 { "repnz", OPF_REP|OPF_REPNZ },
825 { "lock", OPF_LOCK }, // ignored for now..
828 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
830 static const struct {
833 unsigned short minopr;
834 unsigned short maxopr;
837 unsigned char pfo_inv;
839 { "nop", OP_NOP, 0, 0, 0 },
840 { "push", OP_PUSH, 1, 1, 0 },
841 { "pop", OP_POP, 1, 1, OPF_DATA },
842 { "leave",OP_LEAVE, 0, 0, OPF_DATA },
843 { "mov" , OP_MOV, 2, 2, OPF_DATA },
844 { "lea", OP_LEA, 2, 2, OPF_DATA },
845 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
846 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
847 { "xchg", OP_XCHG, 2, 2, OPF_DATA },
848 { "not", OP_NOT, 1, 1, OPF_DATA },
849 { "xlat", OP_XLAT, 0, 0, OPF_DATA },
850 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
851 { "lodsb",OP_LODS, 0, 0, OPF_DATA },
852 { "lodsw",OP_LODS, 0, 0, OPF_DATA },
853 { "lodsd",OP_LODS, 0, 0, OPF_DATA },
854 { "stosb",OP_STOS, 0, 0, OPF_DATA },
855 { "stosw",OP_STOS, 0, 0, OPF_DATA },
856 { "stosd",OP_STOS, 0, 0, OPF_DATA },
857 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
858 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
859 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
860 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
861 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
862 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
863 { "scasb",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
864 { "scasw",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
865 { "scasd",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
866 { "std", OP_STD, 0, 0, OPF_DATA }, // special flag
867 { "cld", OP_CLD, 0, 0, OPF_DATA },
868 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
869 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
870 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
871 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
872 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
873 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
874 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
875 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
876 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
877 { "shld", OP_SHLD, 3, 3, OPF_DATA|OPF_FLAGS },
878 { "shrd", OP_SHRD, 3, 3, OPF_DATA|OPF_FLAGS },
879 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
880 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
881 { "rcl", OP_RCL, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
882 { "rcr", OP_RCR, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
883 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
884 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
885 { "bsf", OP_BSF, 2, 2, OPF_DATA|OPF_FLAGS },
886 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
887 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
888 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
889 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
890 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
891 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
892 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
893 { "test", OP_TEST, 2, 2, OPF_FLAGS },
894 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
895 { "retn", OP_RET, 0, 1, OPF_TAIL },
896 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
897 { "jmp", OP_JMP, 1, 1, OPF_JMP },
898 { "jecxz",OP_JECXZ, 1, 1, OPF_JMP|OPF_CJMP },
899 { "loop", OP_LOOP, 1, 1, OPF_JMP|OPF_CJMP|OPF_DATA },
900 { "jo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 0 }, // 70 OF=1
901 { "jno", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 1 }, // 71 OF=0
902 { "jc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72 CF=1
903 { "jb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72
904 { "jnc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73 CF=0
905 { "jnb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
906 { "jae", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
907 { "jz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74 ZF=1
908 { "je", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74
909 { "jnz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75 ZF=0
910 { "jne", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75
911 { "jbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76 CF=1||ZF=1
912 { "jna", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76
913 { "ja", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77 CF=0&&ZF=0
914 { "jnbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77
915 { "js", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 0 }, // 78 SF=1
916 { "jns", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 1 }, // 79 SF=0
917 { "jp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a PF=1
918 { "jpe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a
919 { "jnp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b PF=0
920 { "jpo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b
921 { "jl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c SF!=OF
922 { "jnge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c
923 { "jge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d SF=OF
924 { "jnl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d
925 { "jle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e ZF=1||SF!=OF
926 { "jng", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e
927 { "jg", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f ZF=0&&SF=OF
928 { "jnle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f
929 { "seto", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 0 },
930 { "setno", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 1 },
931 { "setc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
932 { "setb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
933 { "setnc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
934 { "setae", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
935 { "setnb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
936 { "setz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
937 { "sete", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
938 { "setnz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
939 { "setne", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
940 { "setbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
941 { "setna", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
942 { "seta", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
943 { "setnbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
944 { "sets", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 0 },
945 { "setns", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 1 },
946 { "setp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
947 { "setpe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
948 { "setnp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
949 { "setpo", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
950 { "setl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
951 { "setnge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
952 { "setge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
953 { "setnl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
954 { "setle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
955 { "setng", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
956 { "setg", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
957 { "setnle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
960 { "emms", OP_EMMS, 0, 0, OPF_DATA },
961 { "movq", OP_MOV, 2, 2, OPF_DATA },
966 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
968 enum opr_lenmod lmod = OPLM_UNSPEC;
969 int prefix_flags = 0;
977 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
978 if (IS(words[w], pref_table[i].name)) {
979 prefix_flags = pref_table[i].flags;
986 aerr("lone prefix: '%s'\n", words[0]);
991 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
992 if (IS(words[w], op_table[i].name))
996 if (i == ARRAY_SIZE(op_table)) {
998 aerr("unhandled op: '%s'\n", words[0]);
1003 op->op = op_table[i].op;
1004 op->flags = op_table[i].flags | prefix_flags;
1005 op->pfo = op_table[i].pfo;
1006 op->pfo_inv = op_table[i].pfo_inv;
1007 op->regmask_src = op->regmask_dst = 0;
1010 if (op->op == OP_UD2)
1013 for (opr = 0; opr < op_table[i].maxopr; opr++) {
1014 if (opr >= op_table[i].minopr && w >= wordc)
1017 regmask = regmask_ind = 0;
1018 w = parse_operand(&op->operand[opr], ®mask, ®mask_ind,
1019 words, wordc, w, op->flags);
1021 if (opr == 0 && (op->flags & OPF_DATA))
1022 op->regmask_dst = regmask;
1024 op->regmask_src |= regmask;
1025 op->regmask_src |= regmask_ind;
1029 aerr("parse_op %s incomplete: %d/%d\n",
1030 words[0], w, wordc);
1033 op->operand_cnt = opr;
1034 if (!strncmp(op_table[i].name, "set", 3))
1035 op->operand[0].lmod = OPLM_BYTE;
1038 // first operand is not dst
1041 op->regmask_src |= op->regmask_dst;
1042 op->regmask_dst = 0;
1045 // first operand is src too
1057 op->regmask_src |= op->regmask_dst;
1062 op->regmask_src |= op->regmask_dst;
1063 op->regmask_dst |= op->regmask_src;
1069 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1070 && op->operand[0].lmod == op->operand[1].lmod
1071 && op->operand[0].reg == op->operand[1].reg
1072 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1074 op->regmask_src = 0;
1077 op->regmask_src |= op->regmask_dst;
1080 // ops with implicit argumets
1082 op->operand_cnt = 2;
1083 setup_reg_opr(&op->operand[0], xAX, OPLM_BYTE, &op->regmask_src);
1084 op->regmask_dst = op->regmask_src;
1085 setup_reg_opr(&op->operand[1], xDX, OPLM_DWORD, &op->regmask_src);
1089 op->operand_cnt = 2;
1090 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
1091 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
1097 if (op->operand_cnt != 0)
1099 if (words[op_w][4] == 'b')
1101 else if (words[op_w][4] == 'w')
1103 else if (words[op_w][4] == 'd')
1105 op->operand_cnt = 3;
1106 setup_reg_opr(&op->operand[0], op->op == OP_LODS ? xSI : xDI,
1107 lmod, &op->regmask_src);
1108 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
1109 op->regmask_dst = op->regmask_src;
1110 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD,
1111 op->op == OP_LODS ? &op->regmask_dst : &op->regmask_src);
1116 if (op->operand_cnt != 0)
1118 if (words[op_w][4] == 'b')
1120 else if (words[op_w][4] == 'w')
1122 else if (words[op_w][4] == 'd')
1124 op->operand_cnt = 3;
1125 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
1126 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
1127 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
1128 op->regmask_dst = op->regmask_src;
1132 op->regmask_dst = 1 << xCX;
1135 op->operand_cnt = 2;
1136 op->regmask_src = 1 << xCX;
1137 op->operand[1].type = OPT_REG;
1138 op->operand[1].reg = xCX;
1139 op->operand[1].lmod = OPLM_DWORD;
1143 if (op->operand_cnt != 1)
1148 op->regmask_src |= op->regmask_dst;
1149 op->regmask_dst = (1 << xDX) | (1 << xAX);
1150 if (op->operand[0].lmod == OPLM_UNSPEC)
1151 op->operand[0].lmod = OPLM_DWORD;
1156 // we could set up operands for edx:eax, but there is no real need to
1157 // (see is_opr_modified())
1158 op->regmask_src |= op->regmask_dst;
1159 op->regmask_dst = (1 << xDX) | (1 << xAX);
1160 if (op->operand[0].lmod == OPLM_UNSPEC)
1161 op->operand[0].lmod = OPLM_DWORD;
1169 op->regmask_src |= op->regmask_dst;
1170 if (op->operand[1].lmod == OPLM_UNSPEC)
1171 op->operand[1].lmod = OPLM_BYTE;
1175 op->regmask_src |= op->regmask_dst;
1176 if (op->operand[2].lmod == OPLM_UNSPEC)
1177 op->operand[2].lmod = OPLM_BYTE;
1181 op->regmask_src |= op->regmask_dst;
1182 op->regmask_dst = 0;
1183 if (op->operand[0].lmod == OPLM_UNSPEC
1184 && (op->operand[0].type == OPT_CONST
1185 || op->operand[0].type == OPT_OFFSET
1186 || op->operand[0].type == OPT_LABEL))
1187 op->operand[0].lmod = OPLM_DWORD;
1193 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1194 && op->operand[0].lmod == op->operand[1].lmod
1195 && op->operand[0].reg == op->operand[1].reg
1196 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1198 op->flags |= OPF_RMD | OPF_DONE;
1199 op->regmask_src = op->regmask_dst = 0;
1204 if (op->operand[0].type == OPT_REG
1205 && op->operand[1].type == OPT_REGMEM)
1208 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1209 if (IS(buf, op->operand[1].name))
1210 op->flags |= OPF_RMD | OPF_DONE;
1215 // trashed regs must be explicitly detected later
1216 op->regmask_dst = 0;
1220 op->regmask_dst = (1 << xBP) | (1 << xSP);
1221 op->regmask_src = 1 << xBP;
1229 static const char *op_name(struct parsed_op *po)
1231 static char buf[16];
1235 if (po->op == OP_JCC || po->op == OP_SCC) {
1237 *p++ = (po->op == OP_JCC) ? 'j' : 's';
1240 strcpy(p, parsed_flag_op_names[po->pfo]);
1244 for (i = 0; i < ARRAY_SIZE(op_table); i++)
1245 if (op_table[i].op == po->op)
1246 return op_table[i].name;
1252 static const char *dump_op(struct parsed_op *po)
1254 static char out[128];
1261 snprintf(out, sizeof(out), "%s", op_name(po));
1262 for (i = 0; i < po->operand_cnt; i++) {
1266 snprintf(p, sizeof(out) - (p - out),
1267 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1268 po->operand[i].name);
1274 static const char *lmod_type_u(struct parsed_op *po,
1275 enum opr_lenmod lmod)
1287 ferr(po, "invalid lmod: %d\n", lmod);
1288 return "(_invalid_)";
1292 static const char *lmod_cast_u(struct parsed_op *po,
1293 enum opr_lenmod lmod)
1305 ferr(po, "invalid lmod: %d\n", lmod);
1306 return "(_invalid_)";
1310 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1311 enum opr_lenmod lmod)
1323 ferr(po, "invalid lmod: %d\n", lmod);
1324 return "(_invalid_)";
1328 static const char *lmod_cast_s(struct parsed_op *po,
1329 enum opr_lenmod lmod)
1341 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1342 return "(_invalid_)";
1346 static const char *lmod_cast(struct parsed_op *po,
1347 enum opr_lenmod lmod, int is_signed)
1350 lmod_cast_s(po, lmod) :
1351 lmod_cast_u(po, lmod);
1354 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1366 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1371 static const char *opr_name(struct parsed_op *po, int opr_num)
1373 if (opr_num >= po->operand_cnt)
1374 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1375 return po->operand[opr_num].name;
1378 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1380 if (opr_num >= po->operand_cnt)
1381 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1382 if (po->operand[opr_num].type != OPT_CONST)
1383 ferr(po, "opr %d: const expected\n", opr_num);
1384 return po->operand[opr_num].val;
1387 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1389 if ((unsigned int)popr->reg >= ARRAY_SIZE(regs_r32))
1390 ferr(po, "invalid reg: %d\n", popr->reg);
1391 return regs_r32[popr->reg];
1394 // cast1 is the "final" cast
1395 static const char *simplify_cast(const char *cast1, const char *cast2)
1397 static char buf[256];
1403 if (IS(cast1, cast2))
1405 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1407 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1409 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1411 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1413 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1416 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1420 static const char *simplify_cast_num(const char *cast, unsigned int val)
1422 if (IS(cast, "(u8)") && val < 0x100)
1424 if (IS(cast, "(s8)") && val < 0x80)
1426 if (IS(cast, "(u16)") && val < 0x10000)
1428 if (IS(cast, "(s16)") && val < 0x8000)
1430 if (IS(cast, "(s32)") && val < 0x80000000)
1436 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1445 namelen = strlen(name);
1447 p = strchr(name, '+');
1451 ferr(po, "equ parse failed for '%s'\n", name);
1453 if (IS_START(p, "0x"))
1455 *extra_offs = strtol(p, &endp, 16);
1457 ferr(po, "equ parse failed for '%s'\n", name);
1460 for (i = 0; i < g_eqcnt; i++)
1461 if (strncmp(g_eqs[i].name, name, namelen) == 0
1462 && g_eqs[i].name[namelen] == 0)
1466 ferr(po, "unresolved equ name: '%s'\n", name);
1473 static int is_stack_access(struct parsed_op *po,
1474 const struct parsed_opr *popr)
1476 return (parse_stack_el(popr->name, NULL, 0)
1477 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1478 && IS_START(popr->name, "ebp")));
1481 static void parse_stack_access(struct parsed_op *po,
1482 const char *name, char *ofs_reg, int *offset_out,
1483 int *stack_ra_out, const char **bp_arg_out, int is_lea)
1485 const char *bp_arg = "";
1486 const char *p = NULL;
1487 struct parsed_equ *eq;
1494 if (IS_START(name, "ebp-")
1495 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1498 if (IS_START(p, "0x"))
1500 offset = strtoul(p, &endp, 16);
1504 ferr(po, "ebp- parse of '%s' failed\n", name);
1507 bp_arg = parse_stack_el(name, ofs_reg, 0);
1508 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1509 eq = equ_find(po, bp_arg, &offset);
1511 ferr(po, "detected but missing eq\n");
1512 offset += eq->offset;
1515 if (!strncmp(name, "ebp", 3))
1518 // yes it sometimes LEAs ra for compares..
1519 if (!is_lea && ofs_reg[0] == 0
1520 && stack_ra <= offset && offset < stack_ra + 4)
1522 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1525 *offset_out = offset;
1526 *stack_ra_out = stack_ra;
1528 *bp_arg_out = bp_arg;
1531 static int stack_frame_access(struct parsed_op *po,
1532 struct parsed_opr *popr, char *buf, size_t buf_size,
1533 const char *name, const char *cast, int is_src, int is_lea)
1535 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1536 const char *prefix = "";
1537 const char *bp_arg = NULL;
1538 char ofs_reg[16] = { 0, };
1539 int i, arg_i, arg_s;
1547 if (po->flags & OPF_EBP_S)
1548 ferr(po, "stack_frame_access while ebp is scratch\n");
1550 parse_stack_access(po, name, ofs_reg, &offset,
1551 &stack_ra, &bp_arg, is_lea);
1553 if (offset > stack_ra)
1555 arg_i = (offset - stack_ra - 4) / 4;
1556 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1558 if (g_func_pp->is_vararg
1559 && arg_i == g_func_pp->argc_stack && is_lea)
1561 // should be va_list
1564 snprintf(buf, buf_size, "%sap", cast);
1567 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1568 offset, bp_arg, arg_i);
1570 if (ofs_reg[0] != 0)
1571 ferr(po, "offset reg on arg access?\n");
1573 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1574 if (g_func_pp->arg[i].reg != NULL)
1580 if (i == g_func_pp->argc)
1581 ferr(po, "arg %d not in prototype?\n", arg_i);
1583 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1590 ferr(po, "lea/byte to arg?\n");
1591 if (is_src && (offset & 3) == 0)
1592 snprintf(buf, buf_size, "%sa%d",
1593 simplify_cast(cast, "(u8)"), i + 1);
1595 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1596 cast, offset & 3, i + 1);
1601 ferr(po, "lea/word to arg?\n");
1606 ferr(po, "problematic arg store\n");
1607 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1608 simplify_cast(cast, "*(u16 *)"), i + 1);
1611 ferr(po, "unaligned arg word load\n");
1613 else if (is_src && (offset & 2) == 0)
1614 snprintf(buf, buf_size, "%sa%d",
1615 simplify_cast(cast, "(u16)"), i + 1);
1617 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1618 cast, (offset & 2) ? "HI" : "LO", i + 1);
1630 snprintf(buf, buf_size, "(u32)&a%d + %d",
1633 ferr(po, "unaligned arg store\n");
1635 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1636 snprintf(buf, buf_size, "%s(a%d >> %d)",
1637 prefix, i + 1, (offset & 3) * 8);
1641 snprintf(buf, buf_size, "%s%sa%d",
1642 prefix, is_lea ? "&" : "", i + 1);
1647 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1651 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1654 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1655 if (tmp_lmod != OPLM_DWORD
1656 && (unaligned || (!is_src && lmod_bytes(po, tmp_lmod)
1657 < lmod_bytes(po, popr->lmod) + (offset & 3))))
1659 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1660 i + 1, offset, g_func_pp->arg[i].type.name);
1662 // can't check this because msvc likes to reuse
1663 // arg space for scratch..
1664 //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1665 // ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1669 if (g_stack_fsz == 0)
1670 ferr(po, "stack var access without stackframe\n");
1671 g_stack_frame_used = 1;
1673 sf_ofs = g_stack_fsz + offset;
1674 lim = (ofs_reg[0] != 0) ? -4 : 0;
1675 if (offset > 0 || sf_ofs < lim)
1676 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1686 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1687 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1691 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1692 // known unaligned or possibly unaligned
1693 strcat(g_comment, " unaligned");
1695 prefix = "*(u16 *)&";
1696 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1697 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1700 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1704 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1705 // known unaligned or possibly unaligned
1706 strcat(g_comment, " unaligned");
1708 prefix = "*(u32 *)&";
1709 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1710 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1713 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1717 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1724 static void check_func_pp(struct parsed_op *po,
1725 const struct parsed_proto *pp, const char *pfx)
1727 enum opr_lenmod tmp_lmod;
1731 if (pp->argc_reg != 0) {
1732 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1733 pp_print(buf, sizeof(buf), pp);
1734 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1736 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1737 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1738 pfx, pp->argc_reg, pp->argc_stack);
1741 // fptrs must use 32bit args, callsite might have no information and
1742 // lack a cast to smaller types, which results in incorrectly masked
1743 // args passed (callee may assume masked args, it does on ARM)
1744 if (!pp->is_osinc) {
1745 for (i = 0; i < pp->argc; i++) {
1746 ret = guess_lmod_from_c_type(&tmp_lmod, &pp->arg[i].type);
1747 if (ret && tmp_lmod != OPLM_DWORD)
1748 ferr(po, "reference to %s with arg%d '%s'\n", pp->name,
1749 i + 1, pp->arg[i].type.name);
1754 static const char *check_label_read_ref(struct parsed_op *po,
1757 const struct parsed_proto *pp;
1759 pp = proto_parse(g_fhdr, name, 0);
1761 ferr(po, "proto_parse failed for ref '%s'\n", name);
1764 check_func_pp(po, pp, "ref");
1769 static char *out_src_opr(char *buf, size_t buf_size,
1770 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1773 char tmp1[256], tmp2[256];
1782 switch (popr->type) {
1785 ferr(po, "lea from reg?\n");
1787 switch (popr->lmod) {
1789 snprintf(buf, buf_size, "%s%s.q", cast, opr_reg_p(po, popr));
1792 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1795 snprintf(buf, buf_size, "%s%s",
1796 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1799 if (popr->name[1] == 'h') // XXX..
1800 snprintf(buf, buf_size, "%s(%s >> 8)",
1801 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1803 snprintf(buf, buf_size, "%s%s",
1804 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1807 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1812 if (is_stack_access(po, popr)) {
1813 stack_frame_access(po, popr, buf, buf_size,
1814 popr->name, cast, 1, is_lea);
1818 strcpy(expr, popr->name);
1819 if (strchr(expr, '[')) {
1820 // special case: '[' can only be left for label[reg] form
1821 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1823 ferr(po, "parse failure for '%s'\n", expr);
1824 if (tmp1[0] == '(') {
1825 // (off_4FFF50+3)[eax]
1826 p = strchr(tmp1 + 1, ')');
1827 if (p == NULL || p[1] != 0)
1828 ferr(po, "parse failure (2) for '%s'\n", expr);
1830 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1832 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1835 // XXX: do we need more parsing?
1837 snprintf(buf, buf_size, "%s", expr);
1841 snprintf(buf, buf_size, "%s(%s)",
1842 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1846 name = check_label_read_ref(po, popr->name);
1847 if (cast[0] == 0 && popr->is_ptr)
1851 snprintf(buf, buf_size, "(u32)&%s", name);
1852 else if (popr->size_lt)
1853 snprintf(buf, buf_size, "%s%s%s%s", cast,
1854 lmod_cast_u_ptr(po, popr->lmod),
1855 popr->is_array ? "" : "&", name);
1857 snprintf(buf, buf_size, "%s%s%s", cast, name,
1858 popr->is_array ? "[0]" : "");
1862 name = check_label_read_ref(po, popr->name);
1866 ferr(po, "lea an offset?\n");
1867 snprintf(buf, buf_size, "%s&%s", cast, name);
1872 ferr(po, "lea from const?\n");
1874 printf_number(tmp1, sizeof(tmp1), popr->val);
1875 if (popr->val == 0 && strchr(cast, '*'))
1876 snprintf(buf, buf_size, "NULL");
1878 snprintf(buf, buf_size, "%s%s",
1879 simplify_cast_num(cast, popr->val), tmp1);
1883 ferr(po, "invalid src type: %d\n", popr->type);
1889 // note: may set is_ptr (we find that out late for ebp frame..)
1890 static char *out_dst_opr(char *buf, size_t buf_size,
1891 struct parsed_op *po, struct parsed_opr *popr)
1893 switch (popr->type) {
1895 switch (popr->lmod) {
1897 snprintf(buf, buf_size, "%s.q", opr_reg_p(po, popr));
1900 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1904 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1908 if (popr->name[1] == 'h') // XXX..
1909 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1911 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1914 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1919 if (is_stack_access(po, popr)) {
1920 stack_frame_access(po, popr, buf, buf_size,
1921 popr->name, "", 0, 0);
1925 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1928 if (popr->size_mismatch)
1929 snprintf(buf, buf_size, "%s%s%s",
1930 lmod_cast_u_ptr(po, popr->lmod),
1931 popr->is_array ? "" : "&", popr->name);
1933 snprintf(buf, buf_size, "%s%s", popr->name,
1934 popr->is_array ? "[0]" : "");
1938 ferr(po, "invalid dst type: %d\n", popr->type);
1944 static char *out_src_opr_u32(char *buf, size_t buf_size,
1945 struct parsed_op *po, struct parsed_opr *popr)
1947 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1950 static void out_test_for_cc(char *buf, size_t buf_size,
1951 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1952 enum opr_lenmod lmod, const char *expr)
1954 const char *cast, *scast;
1956 cast = lmod_cast_u(po, lmod);
1957 scast = lmod_cast_s(po, lmod);
1961 case PFO_BE: // CF=1||ZF=1; CF=0
1962 snprintf(buf, buf_size, "(%s%s %s 0)",
1963 cast, expr, is_inv ? "!=" : "==");
1967 case PFO_L: // SF!=OF; OF=0
1968 snprintf(buf, buf_size, "(%s%s %s 0)",
1969 scast, expr, is_inv ? ">=" : "<");
1972 case PFO_LE: // ZF=1||SF!=OF; OF=0
1973 snprintf(buf, buf_size, "(%s%s %s 0)",
1974 scast, expr, is_inv ? ">" : "<=");
1978 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1982 static void out_cmp_for_cc(char *buf, size_t buf_size,
1983 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1985 const char *cast, *scast, *cast_use;
1986 char buf1[256], buf2[256];
1987 enum opr_lenmod lmod;
1989 if (po->op != OP_DEC && po->operand[0].lmod != po->operand[1].lmod)
1990 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1991 po->operand[0].lmod, po->operand[1].lmod);
1992 lmod = po->operand[0].lmod;
1994 cast = lmod_cast_u(po, lmod);
1995 scast = lmod_cast_s(po, lmod);
2011 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
2014 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
2015 if (po->op == OP_DEC)
2016 snprintf(buf2, sizeof(buf2), "1");
2018 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
2022 // note: must be unsigned compare
2023 snprintf(buf, buf_size, "(%s %s %s)",
2024 buf1, is_inv ? ">=" : "<", buf2);
2028 snprintf(buf, buf_size, "(%s %s %s)",
2029 buf1, is_inv ? "!=" : "==", buf2);
2033 // note: must be unsigned compare
2034 snprintf(buf, buf_size, "(%s %s %s)",
2035 buf1, is_inv ? ">" : "<=", buf2);
2038 if (is_inv && lmod == OPLM_BYTE
2039 && po->operand[1].type == OPT_CONST
2040 && po->operand[1].val == 0xff)
2042 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
2043 snprintf(buf, buf_size, "(0)");
2047 // note: must be signed compare
2049 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
2050 scast, buf1, buf2, is_inv ? ">=" : "<");
2054 snprintf(buf, buf_size, "(%s %s %s)",
2055 buf1, is_inv ? ">=" : "<", buf2);
2059 snprintf(buf, buf_size, "(%s %s %s)",
2060 buf1, is_inv ? ">" : "<=", buf2);
2068 static void out_cmp_test(char *buf, size_t buf_size,
2069 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
2071 char buf1[256], buf2[256], buf3[256];
2073 if (po->op == OP_TEST) {
2074 if (IS(opr_name(po, 0), opr_name(po, 1))) {
2075 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
2078 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
2079 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
2080 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
2082 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
2083 po->operand[0].lmod, buf3);
2085 else if (po->op == OP_CMP) {
2086 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
2089 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
2092 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
2093 struct parsed_opr *popr2)
2095 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
2096 ferr(po, "missing lmod for both operands\n");
2098 if (popr1->lmod == OPLM_UNSPEC)
2099 popr1->lmod = popr2->lmod;
2100 else if (popr2->lmod == OPLM_UNSPEC)
2101 popr2->lmod = popr1->lmod;
2102 else if (popr1->lmod != popr2->lmod) {
2103 if (popr1->type_from_var) {
2104 popr1->size_mismatch = 1;
2105 if (popr1->lmod < popr2->lmod)
2107 popr1->lmod = popr2->lmod;
2109 else if (popr2->type_from_var) {
2110 popr2->size_mismatch = 1;
2111 if (popr2->lmod < popr1->lmod)
2113 popr2->lmod = popr1->lmod;
2116 ferr(po, "conflicting lmods: %d vs %d\n",
2117 popr1->lmod, popr2->lmod);
2121 static const char *op_to_c(struct parsed_op *po)
2145 ferr(po, "op_to_c was supplied with %d\n", po->op);
2149 static void op_set_clear_flag(struct parsed_op *po,
2150 enum op_flags flag_set, enum op_flags flag_clear)
2152 po->flags |= flag_set;
2153 po->flags &= ~flag_clear;
2156 // last op in stream - unconditional branch or ret
2157 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
2158 || ((ops[_i].flags & (OPF_JMP|OPF_CJMP|OPF_RMD)) == OPF_JMP \
2159 && ops[_i].op != OP_CALL))
2161 #define check_i(po, i) \
2163 ferr(po, "bad " #i ": %d\n", i)
2165 static int scan_for_pop(int i, int opcnt, const char *reg,
2166 int magic, int depth, int *maxdepth, int do_flags)
2168 const struct parsed_proto *pp;
2169 struct parsed_op *po;
2173 for (; i < opcnt; i++) {
2175 if (po->cc_scratch == magic)
2176 break; // already checked
2177 po->cc_scratch = magic;
2179 if (po->flags & OPF_TAIL) {
2180 if (po->op == OP_CALL) {
2181 pp = proto_parse(g_fhdr, po->operand[0].name, g_quiet_pp);
2182 if (pp != NULL && pp->is_noreturn)
2183 // no stack cleanup for noreturn
2186 return -1; // deadend
2189 if ((po->flags & (OPF_RMD|OPF_DONE))
2190 || (po->op == OP_PUSH && po->p_argnum != 0)) // arg push
2193 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2194 if (po->btj != NULL) {
2196 for (j = 0; j < po->btj->count; j++) {
2197 check_i(po, po->btj->d[j].bt_i);
2198 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
2199 depth, maxdepth, do_flags);
2201 return ret; // dead end
2206 check_i(po, po->bt_i);
2207 if (po->flags & OPF_CJMP) {
2208 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
2209 depth, maxdepth, do_flags);
2211 return ret; // dead end
2219 if ((po->op == OP_POP || po->op == OP_PUSH)
2220 && po->operand[0].type == OPT_REG
2221 && IS(po->operand[0].name, reg))
2223 if (po->op == OP_PUSH && !(po->flags & OPF_FARGNR)) {
2225 if (depth > *maxdepth)
2228 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2230 else if (po->op == OP_POP) {
2233 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2238 if (depth < 0) // should not happen
2239 ferr(po, "fail with depth\n");
2241 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2250 // scan for pop starting from 'ret' op (all paths)
2251 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2257 for (; i < opcnt; i++) {
2258 if (!(ops[i].flags & OPF_TAIL))
2261 for (j = i - 1; j >= 0; j--) {
2262 if (ops[j].flags & (OPF_RMD|OPF_DONE))
2264 if (ops[j].flags & OPF_JMP)
2267 if (ops[j].op == OP_POP && ops[j].datap == NULL
2268 && ops[j].operand[0].type == OPT_REG
2269 && IS(ops[j].operand[0].name, reg))
2272 ops[j].flags |= flag_set;
2276 if (g_labels[j] != NULL)
2281 return found ? 0 : -1;
2284 static void scan_for_pop_const(int i, int opcnt, int *regmask_pp)
2286 struct parsed_op *po;
2287 int is_multipath = 0;
2290 for (j = i + 1; j < opcnt; j++) {
2293 if (po->op == OP_JMP && po->btj == NULL) {
2294 ferr_assert(po, po->bt_i >= 0);
2299 if ((po->flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
2300 || po->op == OP_PUSH)
2305 if (g_labels[j] != NULL)
2308 if (po->op == OP_POP && !(po->flags & OPF_RMD))
2310 is_multipath |= !!(po->flags & OPF_PPUSH);
2312 ops[i].flags |= OPF_PPUSH | OPF_DONE;
2314 po->flags |= OPF_PPUSH | OPF_DONE;
2315 *regmask_pp |= 1 << po->operand[0].reg;
2318 ops[i].flags |= OPF_RMD | OPF_DONE;
2319 po->flags |= OPF_DONE;
2320 po->datap = &ops[i];
2327 static void scan_propagate_df(int i, int opcnt)
2329 struct parsed_op *po = &ops[i];
2332 for (; i < opcnt; i++) {
2334 if (po->flags & OPF_DF)
2335 return; // already resolved
2336 po->flags |= OPF_DF;
2338 if (po->op == OP_CALL)
2339 ferr(po, "call with DF set?\n");
2341 if (po->flags & OPF_JMP) {
2342 if (po->btj != NULL) {
2344 for (j = 0; j < po->btj->count; j++) {
2345 check_i(po, po->btj->d[j].bt_i);
2346 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2351 check_i(po, po->bt_i);
2352 if (po->flags & OPF_CJMP)
2353 scan_propagate_df(po->bt_i, opcnt);
2359 if (po->flags & OPF_TAIL)
2362 if (po->op == OP_CLD) {
2363 po->flags |= OPF_RMD | OPF_DONE;
2368 ferr(po, "missing DF clear?\n");
2371 // is operand 'opr' referenced by parsed_op 'po'?
2372 static int is_opr_referenced(const struct parsed_opr *opr,
2373 const struct parsed_op *po)
2377 if (opr->type == OPT_REG) {
2378 mask = po->regmask_dst | po->regmask_src;
2379 if (po->op == OP_CALL)
2380 mask |= (1 << xAX) | (1 << xCX) | (1 << xDX);
2381 if ((1 << opr->reg) & mask)
2387 for (i = 0; i < po->operand_cnt; i++)
2388 if (IS(po->operand[0].name, opr->name))
2394 // is operand 'opr' read by parsed_op 'po'?
2395 static int is_opr_read(const struct parsed_opr *opr,
2396 const struct parsed_op *po)
2400 if (opr->type == OPT_REG) {
2401 mask = po->regmask_src;
2402 if (po->op == OP_CALL)
2403 // assume worst case
2404 mask |= (1 << xAX) | (1 << xCX) | (1 << xDX);
2405 if ((1 << opr->reg) & mask)
2415 // is operand 'opr' modified by parsed_op 'po'?
2416 static int is_opr_modified(const struct parsed_opr *opr,
2417 const struct parsed_op *po)
2421 if (!(po->flags & OPF_DATA))
2424 if (opr->type == OPT_REG) {
2425 if (po->op == OP_CALL) {
2426 mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2427 if ((1 << opr->reg) & mask)
2433 if (po->operand[0].type == OPT_REG) {
2434 if (po->regmask_dst & (1 << opr->reg))
2441 return IS(po->operand[0].name, opr->name);
2444 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2445 static int is_any_opr_modified(const struct parsed_op *po_test,
2446 const struct parsed_op *po, int c_mode)
2451 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2454 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2457 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2460 // in reality, it can wreck any register, but in decompiled C
2461 // version it can only overwrite eax or edx:eax
2462 mask = (1 << xAX) | (1 << xDX);
2466 if (po->op == OP_CALL
2467 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2470 for (i = 0; i < po_test->operand_cnt; i++)
2471 if (IS(po_test->operand[i].name, po->operand[0].name))
2477 // scan for any po_test operand modification in range given
2478 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2481 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2484 for (; i < opcnt; i++) {
2485 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2492 // scan for po_test operand[0] modification in range given
2493 static int scan_for_mod_opr0(struct parsed_op *po_test,
2496 for (; i < opcnt; i++) {
2497 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2504 static int scan_for_flag_set(int i, int magic, int *branched,
2505 int *setters, int *setter_cnt)
2507 struct label_ref *lr;
2511 if (ops[i].cc_scratch == magic) {
2512 // is this a problem?
2513 //ferr(&ops[i], "%s looped\n", __func__);
2516 ops[i].cc_scratch = magic;
2518 if (g_labels[i] != NULL) {
2521 lr = &g_label_refs[i];
2522 for (; lr->next; lr = lr->next) {
2523 check_i(&ops[i], lr->i);
2524 ret = scan_for_flag_set(lr->i, magic,
2525 branched, setters, setter_cnt);
2530 check_i(&ops[i], lr->i);
2531 if (i > 0 && LAST_OP(i - 1)) {
2535 ret = scan_for_flag_set(lr->i, magic,
2536 branched, setters, setter_cnt);
2542 if (ops[i].flags & OPF_FLAGS) {
2543 setters[*setter_cnt] = i;
2548 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2555 // scan back for cdq, if anything modifies edx, fail
2556 static int scan_for_cdq_edx(int i)
2559 if (g_labels[i] != NULL) {
2560 if (g_label_refs[i].next != NULL)
2562 if (i > 0 && LAST_OP(i - 1)) {
2563 i = g_label_refs[i].i;
2570 if (ops[i].op == OP_CDQ)
2573 if (ops[i].regmask_dst & (1 << xDX))
2580 static int scan_for_reg_clear(int i, int reg)
2583 if (g_labels[i] != NULL) {
2584 if (g_label_refs[i].next != NULL)
2586 if (i > 0 && LAST_OP(i - 1)) {
2587 i = g_label_refs[i].i;
2594 if (ops[i].op == OP_XOR
2595 && ops[i].operand[0].lmod == OPLM_DWORD
2596 && ops[i].operand[0].reg == ops[i].operand[1].reg
2597 && ops[i].operand[0].reg == reg)
2600 if (ops[i].regmask_dst & (1 << reg))
2607 static void patch_esp_adjust(struct parsed_op *po, int adj)
2609 ferr_assert(po, po->op == OP_ADD);
2610 ferr_assert(po, IS(opr_name(po, 0), "esp"));
2611 ferr_assert(po, po->operand[1].type == OPT_CONST);
2613 // this is a bit of a hack, but deals with use of
2614 // single adj for multiple calls
2615 po->operand[1].val -= adj;
2616 po->flags |= OPF_RMD;
2617 if (po->operand[1].val == 0)
2618 po->flags |= OPF_DONE;
2619 ferr_assert(po, (int)po->operand[1].val >= 0);
2622 // scan for positive, constant esp adjust
2623 // multipath case is preliminary
2624 static int scan_for_esp_adjust(int i, int opcnt,
2625 int adj_expect, int *adj, int *is_multipath, int do_update)
2627 int adj_expect_unknown = 0;
2628 struct parsed_op *po;
2632 *adj = *is_multipath = 0;
2633 if (adj_expect < 0) {
2634 adj_expect_unknown = 1;
2635 adj_expect = 32 * 4; // enough?
2638 for (; i < opcnt && *adj < adj_expect; i++) {
2639 if (g_labels[i] != NULL)
2643 if (po->flags & OPF_DONE)
2646 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2647 if (po->operand[1].type != OPT_CONST)
2648 ferr(&ops[i], "non-const esp adjust?\n");
2649 *adj += po->operand[1].val;
2651 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2654 patch_esp_adjust(po, adj_expect);
2656 po->flags |= OPF_RMD;
2660 else if (po->op == OP_PUSH) {
2661 //if (first_pop == -1)
2662 // first_pop = -2; // none
2663 *adj -= lmod_bytes(po, po->operand[0].lmod);
2665 else if (po->op == OP_POP) {
2666 if (!(po->flags & OPF_DONE)) {
2667 // seems like msvc only uses 'pop ecx' for stack realignment..
2668 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2670 if (first_pop == -1 && *adj >= 0)
2673 if (do_update && *adj >= 0) {
2674 po->flags |= OPF_RMD;
2676 po->flags |= OPF_DONE;
2679 *adj += lmod_bytes(po, po->operand[0].lmod);
2680 if (*adj > adj_best)
2683 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2684 if (po->op == OP_JMP && po->btj == NULL) {
2690 if (po->op != OP_CALL)
2692 if (po->operand[0].type != OPT_LABEL)
2694 if (po->pp != NULL && po->pp->is_stdcall)
2696 if (adj_expect_unknown && first_pop >= 0)
2698 // assume it's another cdecl call
2702 if (first_pop >= 0) {
2703 // probably only 'pop ecx' was used
2711 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2713 struct parsed_op *po;
2717 ferr(ops, "%s: followed bad branch?\n", __func__);
2719 for (; i < opcnt; i++) {
2721 if (po->cc_scratch == magic)
2723 po->cc_scratch = magic;
2726 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2727 if (po->btj != NULL) {
2729 for (j = 0; j < po->btj->count; j++)
2730 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2734 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2735 if (!(po->flags & OPF_CJMP))
2738 if (po->flags & OPF_TAIL)
2743 static const struct parsed_proto *try_recover_pp(
2744 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2746 const struct parsed_proto *pp = NULL;
2750 // maybe an arg of g_func?
2751 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2753 char ofs_reg[16] = { 0, };
2754 int arg, arg_s, arg_i;
2761 parse_stack_access(po, opr->name, ofs_reg,
2762 &offset, &stack_ra, NULL, 0);
2763 if (ofs_reg[0] != 0)
2764 ferr(po, "offset reg on arg access?\n");
2765 if (offset <= stack_ra) {
2766 // search who set the stack var instead
2767 if (search_instead != NULL)
2768 *search_instead = 1;
2772 arg_i = (offset - stack_ra - 4) / 4;
2773 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2774 if (g_func_pp->arg[arg].reg != NULL)
2780 if (arg == g_func_pp->argc)
2781 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2783 pp = g_func_pp->arg[arg].fptr;
2785 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2786 check_func_pp(po, pp, "icall arg");
2788 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2790 p = strchr(opr->name + 1, '[');
2791 memcpy(buf, opr->name, p - opr->name);
2792 buf[p - opr->name] = 0;
2793 pp = proto_parse(g_fhdr, buf, g_quiet_pp);
2795 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2796 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
2799 ferr(po, "proto_parse failed for icall to '%s'\n", opr->name);
2802 check_func_pp(po, pp, "reg-fptr ref");
2808 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2809 int magic, const struct parsed_proto **pp_found, int *pp_i,
2812 const struct parsed_proto *pp = NULL;
2813 struct parsed_op *po;
2814 struct label_ref *lr;
2816 ops[i].cc_scratch = magic;
2819 if (g_labels[i] != NULL) {
2820 lr = &g_label_refs[i];
2821 for (; lr != NULL; lr = lr->next) {
2822 check_i(&ops[i], lr->i);
2823 scan_for_call_type(lr->i, opr, magic, pp_found, pp_i, multi);
2825 if (i > 0 && LAST_OP(i - 1))
2833 if (ops[i].cc_scratch == magic)
2835 ops[i].cc_scratch = magic;
2837 if (!(ops[i].flags & OPF_DATA))
2839 if (!is_opr_modified(opr, &ops[i]))
2841 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2842 // most probably trashed by some processing
2847 opr = &ops[i].operand[1];
2848 if (opr->type != OPT_REG)
2852 po = (i >= 0) ? &ops[i] : ops;
2855 // reached the top - can only be an arg-reg
2856 if (opr->type != OPT_REG || g_func_pp == NULL)
2859 for (i = 0; i < g_func_pp->argc; i++) {
2860 if (g_func_pp->arg[i].reg == NULL)
2862 if (IS(opr->name, g_func_pp->arg[i].reg))
2865 if (i == g_func_pp->argc)
2867 pp = g_func_pp->arg[i].fptr;
2869 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2870 i + 1, g_func_pp->arg[i].reg);
2871 check_func_pp(po, pp, "icall reg-arg");
2874 pp = try_recover_pp(po, opr, NULL);
2876 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2877 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2878 || (*pp_found)->is_stdcall != pp->is_stdcall
2879 || (*pp_found)->is_fptr != pp->is_fptr
2880 || (*pp_found)->argc != pp->argc
2881 || (*pp_found)->argc_reg != pp->argc_reg
2882 || (*pp_found)->argc_stack != pp->argc_stack)
2884 ferr(po, "icall: parsed_proto mismatch\n");
2894 static void add_label_ref(struct label_ref *lr, int op_i)
2896 struct label_ref *lr_new;
2903 lr_new = calloc(1, sizeof(*lr_new));
2905 lr_new->next = lr->next;
2909 static struct parsed_data *try_resolve_jumptab(int i, int opcnt)
2911 struct parsed_op *po = &ops[i];
2912 struct parsed_data *pd;
2913 char label[NAMELEN], *p;
2916 p = strchr(po->operand[0].name, '[');
2920 len = p - po->operand[0].name;
2921 strncpy(label, po->operand[0].name, len);
2924 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2925 if (IS(g_func_pd[j].label, label)) {
2931 //ferr(po, "label '%s' not parsed?\n", label);
2934 if (pd->type != OPT_OFFSET)
2935 ferr(po, "label '%s' with non-offset data?\n", label);
2937 // find all labels, link
2938 for (j = 0; j < pd->count; j++) {
2939 for (l = 0; l < opcnt; l++) {
2940 if (g_labels[l] != NULL && IS(g_labels[l], pd->d[j].u.label)) {
2941 add_label_ref(&g_label_refs[l], i);
2951 static void clear_labels(int count)
2955 for (i = 0; i < count; i++) {
2956 if (g_labels[i] != NULL) {
2963 static void resolve_branches_parse_calls(int opcnt)
2965 const struct parsed_proto *pp_c;
2966 struct parsed_proto *pp;
2967 struct parsed_data *pd;
2968 struct parsed_op *po;
2969 const char *tmpname;
2972 for (i = 0; i < opcnt; i++)
2978 if (po->op == OP_CALL) {
2981 if (po->operand[0].type == OPT_LABEL) {
2982 tmpname = opr_name(po, 0);
2983 if (IS_START(tmpname, "loc_"))
2984 ferr(po, "call to loc_*\n");
2985 pp_c = proto_parse(g_fhdr, tmpname, g_header_mode);
2986 if (!g_header_mode && pp_c == NULL)
2987 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2990 pp = proto_clone(pp_c);
2991 my_assert_not(pp, NULL);
2994 else if (po->datap != NULL) {
2995 pp = calloc(1, sizeof(*pp));
2996 my_assert_not(pp, NULL);
2998 ret = parse_protostr(po->datap, pp);
3000 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3007 check_func_pp(po, pp, "fptr var call");
3008 if (pp->is_noreturn)
3009 po->flags |= OPF_TAIL;
3015 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3018 if (po->operand[0].type == OPT_REGMEM) {
3019 pd = try_resolve_jumptab(i, opcnt);
3027 for (l = 0; l < opcnt; l++) {
3028 if (g_labels[l] != NULL
3029 && IS(po->operand[0].name, g_labels[l]))
3031 if (l == i + 1 && po->op == OP_JMP) {
3032 // yet another alignment type..
3033 po->flags |= OPF_RMD|OPF_DONE;
3036 add_label_ref(&g_label_refs[l], i);
3042 if (po->bt_i != -1 || (po->flags & OPF_RMD))
3045 if (po->operand[0].type == OPT_LABEL)
3049 ferr(po, "unhandled branch\n");
3053 po->flags |= OPF_TAIL;
3054 if (i > 0 && ops[i - 1].op == OP_POP)
3055 po->flags |= OPF_ATAIL;
3060 static void scan_prologue_epilogue(int opcnt)
3062 int ecx_push = 0, esp_sub = 0;
3066 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
3067 && ops[1].op == OP_MOV
3068 && IS(opr_name(&ops[1], 0), "ebp")
3069 && IS(opr_name(&ops[1], 1), "esp"))
3072 ops[0].flags |= OPF_RMD | OPF_DONE;
3073 ops[1].flags |= OPF_RMD | OPF_DONE;
3076 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
3077 g_stack_fsz = opr_const(&ops[2], 1);
3078 ops[2].flags |= OPF_RMD | OPF_DONE;
3082 // another way msvc builds stack frame..
3084 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3086 ops[i].flags |= OPF_RMD | OPF_DONE;
3090 // and another way..
3091 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
3092 && ops[i].operand[1].type == OPT_CONST
3093 && ops[i + 1].op == OP_CALL
3094 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
3096 g_stack_fsz += ops[i].operand[1].val;
3097 ops[i].flags |= OPF_RMD | OPF_DONE;
3099 ops[i].flags |= OPF_RMD | OPF_DONE;
3106 for (; i < opcnt; i++)
3107 if (ops[i].flags & OPF_TAIL)
3110 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3111 if (ops[j].bt_i != -1 || ops[j].btj != NULL)
3117 if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
3118 || ops[j].op == OP_LEAVE)
3120 ops[j].flags |= OPF_RMD | OPF_DONE;
3122 else if (ops[i].op == OP_CALL && ops[i].pp != NULL
3123 && ops[i].pp->is_noreturn)
3125 // on noreturn, msvc sometimes cleans stack, sometimes not
3130 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3131 ferr(&ops[j], "'pop ebp' expected\n");
3133 if (g_stack_fsz != 0) {
3134 if (ops[j].op == OP_LEAVE)
3136 else if (ops[j].op == OP_POP
3137 && ops[j - 1].op == OP_MOV
3138 && IS(opr_name(&ops[j - 1], 0), "esp")
3139 && IS(opr_name(&ops[j - 1], 1), "ebp"))
3141 ops[j - 1].flags |= OPF_RMD | OPF_DONE;
3144 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3146 ferr(&ops[j], "esp restore expected\n");
3149 if (ecx_push && j >= 0 && ops[j].op == OP_POP
3150 && IS(opr_name(&ops[j], 0), "ecx"))
3152 ferr(&ops[j], "unexpected ecx pop\n");
3158 } while (i < opcnt);
3161 ferr(ops, "missing ebp epilogue\n");
3167 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3168 ops[i].flags |= OPF_RMD | OPF_DONE;
3174 for (; i < opcnt; i++) {
3175 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
3177 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
3178 && ops[i].operand[1].type == OPT_CONST)
3180 g_stack_fsz = ops[i].operand[1].val;
3181 ops[i].flags |= OPF_RMD | OPF_DONE;
3187 if (ecx_push && !esp_sub) {
3188 // could actually be args for a call..
3189 for (; i < opcnt; i++)
3190 if (ops[i].op != OP_PUSH)
3193 if (ops[i].op == OP_CALL && ops[i].operand[0].type == OPT_LABEL) {
3194 const struct parsed_proto *pp;
3195 pp = proto_parse(g_fhdr, opr_name(&ops[i], 0), 1);
3196 j = pp ? pp->argc_stack : 0;
3197 while (i > 0 && j > 0) {
3199 if (ops[i].op == OP_PUSH) {
3200 ops[i].flags &= ~(OPF_RMD | OPF_DONE);
3205 ferr(&ops[i], "unhandled prologue\n");
3208 i = g_stack_fsz = ecx_push = 0;
3209 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3210 if (!(ops[i].flags & OPF_RMD))
3220 if (ecx_push || esp_sub)
3226 for (; i < opcnt; i++)
3227 if (ops[i].flags & OPF_TAIL)
3230 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3231 if (ops[j].bt_i != -1 || ops[j].btj != NULL)
3238 for (l = 0; l < ecx_push; l++) {
3239 if (ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ecx"))
3241 else if (ops[j].op == OP_ADD
3242 && IS(opr_name(&ops[j], 0), "esp")
3243 && ops[j].operand[1].type == OPT_CONST)
3246 l += ops[j].operand[1].val / 4 - 1;
3249 ferr(&ops[j], "'pop ecx' expected\n");
3251 ops[j].flags |= OPF_RMD | OPF_DONE;
3255 ferr(&ops[j], "epilogue scan failed\n");
3261 if (ops[j].op != OP_ADD
3262 || !IS(opr_name(&ops[j], 0), "esp")
3263 || ops[j].operand[1].type != OPT_CONST
3264 || ops[j].operand[1].val != g_stack_fsz)
3265 ferr(&ops[j], "'add esp' expected\n");
3267 ops[j].flags |= OPF_RMD | OPF_DONE;
3268 ops[j].operand[1].val = 0; // hack for stack arg scanner
3273 } while (i < opcnt);
3276 ferr(ops, "missing esp epilogue\n");
3280 static const struct parsed_proto *resolve_icall(int i, int opcnt,
3281 int *pp_i, int *multi_src)
3283 const struct parsed_proto *pp = NULL;
3284 int search_advice = 0;
3289 switch (ops[i].operand[0].type) {
3293 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
3298 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
3306 // find an instruction that changed opr before i op
3307 // *op_i must be set to -1 by the caller
3308 // *entry is set to 1 if one source is determined to be the caller
3309 // returns 1 if found, *op_i is then set to origin
3310 static int resolve_origin(int i, const struct parsed_opr *opr,
3311 int magic, int *op_i, int *is_caller)
3313 struct label_ref *lr;
3316 if (ops[i].cc_scratch == magic)
3318 ops[i].cc_scratch = magic;
3321 if (g_labels[i] != NULL) {
3322 lr = &g_label_refs[i];
3323 for (; lr != NULL; lr = lr->next) {
3324 check_i(&ops[i], lr->i);
3325 ret |= resolve_origin(lr->i, opr, magic, op_i, is_caller);
3327 if (i > 0 && LAST_OP(i - 1))
3333 if (is_caller != NULL)
3338 if (ops[i].cc_scratch == magic)
3340 ops[i].cc_scratch = magic;
3342 if (!(ops[i].flags & OPF_DATA))
3344 if (!is_opr_modified(opr, &ops[i]))
3351 // XXX: could check if the other op does the same
3360 // find an instruction that previously referenced opr
3361 // if multiple results are found - fail
3362 // *op_i must be set to -1 by the caller
3363 // returns 1 if found, *op_i is then set to referencer insn
3364 static int resolve_last_ref(int i, const struct parsed_opr *opr,
3365 int magic, int *op_i)
3367 struct label_ref *lr;
3370 if (ops[i].cc_scratch == magic)
3372 ops[i].cc_scratch = magic;
3375 if (g_labels[i] != NULL) {
3376 lr = &g_label_refs[i];
3377 for (; lr != NULL; lr = lr->next) {
3378 check_i(&ops[i], lr->i);
3379 ret |= resolve_last_ref(lr->i, opr, magic, op_i);
3381 if (i > 0 && LAST_OP(i - 1))
3389 if (ops[i].cc_scratch == magic)
3391 ops[i].cc_scratch = magic;
3393 if (!is_opr_referenced(opr, &ops[i]))
3404 // find next instruction that reads opr
3405 // if multiple results are found - fail
3406 // *op_i must be set to -1 by the caller
3407 // returns 1 if found, *op_i is then set to referencer insn
3408 static int find_next_read(int i, int opcnt,
3409 const struct parsed_opr *opr, int magic, int *op_i)
3411 struct parsed_op *po;
3414 for (; i < opcnt; i++)
3416 if (ops[i].cc_scratch == magic)
3418 ops[i].cc_scratch = magic;
3421 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
3422 if (po->btj != NULL) {
3424 for (j = 0; j < po->btj->count; j++) {
3425 check_i(po, po->btj->d[j].bt_i);
3426 ret |= find_next_read(po->btj->d[j].bt_i, opcnt, opr,
3432 if (po->flags & OPF_RMD)
3434 check_i(po, po->bt_i);
3435 if (po->flags & OPF_CJMP) {
3436 ret = find_next_read(po->bt_i, opcnt, opr, magic, op_i);
3445 if (!is_opr_read(opr, po)) {
3446 if (is_opr_modified(opr, po))
3449 if (po->flags & OPF_TAIL)
3464 static int try_resolve_const(int i, const struct parsed_opr *opr,
3465 int magic, unsigned int *val)
3470 ret = resolve_origin(i, opr, magic, &s_i, NULL);
3473 if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
3476 *val = ops[i].operand[1].val;
3483 static struct parsed_proto *process_call_early(int i, int opcnt,
3486 struct parsed_op *po = &ops[i];
3487 struct parsed_proto *pp;
3493 if (pp == NULL || pp->is_vararg || pp->argc_reg != 0)
3497 // look for and make use of esp adjust
3499 if (!pp->is_stdcall && pp->argc_stack > 0)
3500 ret = scan_for_esp_adjust(i + 1, opcnt,
3501 pp->argc_stack * 4, &adj, &multipath, 0);
3503 if (pp->argc_stack > adj / 4)
3507 if (ops[ret].op == OP_POP) {
3508 for (j = 1; j < adj / 4; j++) {
3509 if (ops[ret + j].op != OP_POP
3510 || ops[ret + j].operand[0].reg != xCX)
3522 static struct parsed_proto *process_call(int i, int opcnt)
3524 struct parsed_op *po = &ops[i];
3525 const struct parsed_proto *pp_c;
3526 struct parsed_proto *pp;
3527 const char *tmpname;
3528 int call_i = -1, ref_i = -1;
3529 int adj = 0, multipath = 0;
3532 tmpname = opr_name(po, 0);
3537 pp_c = resolve_icall(i, opcnt, &call_i, &multipath);
3539 if (!pp_c->is_func && !pp_c->is_fptr)
3540 ferr(po, "call to non-func: %s\n", pp_c->name);
3541 pp = proto_clone(pp_c);
3542 my_assert_not(pp, NULL);
3544 // not resolved just to single func
3547 switch (po->operand[0].type) {
3549 // we resolved this call and no longer need the register
3550 po->regmask_src &= ~(1 << po->operand[0].reg);
3552 if (!multipath && i != call_i && ops[call_i].op == OP_MOV
3553 && ops[call_i].operand[1].type == OPT_LABEL)
3555 // no other source users?
3556 ret = resolve_last_ref(i, &po->operand[0], opcnt * 10,
3558 if (ret == 1 && call_i == ref_i) {
3559 // and nothing uses it after us?
3561 ret = find_next_read(i + 1, opcnt, &po->operand[0],
3562 opcnt * 11, &ref_i);
3564 // then also don't need the source mov
3565 ops[call_i].flags |= OPF_RMD;
3577 pp = calloc(1, sizeof(*pp));
3578 my_assert_not(pp, NULL);
3581 ret = scan_for_esp_adjust(i + 1, opcnt,
3582 -1, &adj, &multipath, 0);
3583 if (ret < 0 || adj < 0) {
3584 if (!g_allow_regfunc)
3585 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3586 pp->is_unresolved = 1;
3590 if (adj > ARRAY_SIZE(pp->arg))
3591 ferr(po, "esp adjust too large: %d\n", adj);
3592 pp->ret_type.name = strdup("int");
3593 pp->argc = pp->argc_stack = adj;
3594 for (arg = 0; arg < pp->argc; arg++)
3595 pp->arg[arg].type.name = strdup("int");
3600 // look for and make use of esp adjust
3603 if (!pp->is_stdcall && pp->argc_stack > 0) {
3604 int adj_expect = pp->is_vararg ? -1 : pp->argc_stack * 4;
3605 ret = scan_for_esp_adjust(i + 1, opcnt,
3606 adj_expect, &adj, &multipath, 0);
3609 if (pp->is_vararg) {
3610 if (adj / 4 < pp->argc_stack) {
3611 fnote(po, "(this call)\n");
3612 ferr(&ops[ret], "esp adjust is too small: %x < %x\n",
3613 adj, pp->argc_stack * 4);
3615 // modify pp to make it have varargs as normal args
3617 pp->argc += adj / 4 - pp->argc_stack;
3618 for (; arg < pp->argc; arg++) {
3619 pp->arg[arg].type.name = strdup("int");
3622 if (pp->argc > ARRAY_SIZE(pp->arg))
3623 ferr(po, "too many args for '%s'\n", tmpname);
3625 if (pp->argc_stack > adj / 4) {
3626 fnote(po, "(this call)\n");
3627 ferr(&ops[ret], "stack tracking failed for '%s': %x %x\n",
3628 tmpname, pp->argc_stack * 4, adj);
3631 scan_for_esp_adjust(i + 1, opcnt,
3632 pp->argc_stack * 4, &adj, &multipath, 1);
3634 else if (pp->is_vararg)
3635 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3641 static int collect_call_args_early(struct parsed_op *po, int i,
3642 struct parsed_proto *pp, int *regmask)
3647 for (arg = 0; arg < pp->argc; arg++)
3648 if (pp->arg[arg].reg == NULL)
3651 // first see if it can be easily done
3652 for (j = i; j > 0 && arg < pp->argc; )
3654 if (g_labels[j] != NULL)
3658 if (ops[j].op == OP_CALL)
3660 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP)
3662 else if (ops[j].op == OP_POP)
3664 else if (ops[j].flags & OPF_CJMP)
3666 else if (ops[j].op == OP_PUSH) {
3667 if (ops[j].flags & (OPF_FARG|OPF_FARGNR))
3669 ret = scan_for_mod(&ops[j], j + 1, i, 1);
3673 if (pp->arg[arg].type.is_va_list)
3677 for (arg++; arg < pp->argc; arg++)
3678 if (pp->arg[arg].reg == NULL)
3687 for (arg = 0; arg < pp->argc; arg++)
3688 if (pp->arg[arg].reg == NULL)
3691 for (j = i; j > 0 && arg < pp->argc; )
3695 if (ops[j].op == OP_PUSH)
3697 ops[j].p_argnext = -1;
3698 ferr_assert(&ops[j], pp->arg[arg].datap == NULL);
3699 pp->arg[arg].datap = &ops[j];
3701 if (ops[j].operand[0].type == OPT_REG)
3702 *regmask |= 1 << ops[j].operand[0].reg;
3704 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_FARGNR | OPF_FARG;
3705 ops[j].flags &= ~OPF_RSAVE;
3708 for (arg++; arg < pp->argc; arg++)
3709 if (pp->arg[arg].reg == NULL)
3717 static int collect_call_args_r(struct parsed_op *po, int i,
3718 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3719 int *arg_grp, int arg, int magic, int need_op_saving, int may_reuse)
3721 struct parsed_proto *pp_tmp;
3722 struct parsed_op *po_tmp;
3723 struct label_ref *lr;
3724 int need_to_save_current;
3725 int arg_grp_current = 0;
3726 int save_args_seen = 0;
3734 ferr(po, "dead label encountered\n");
3738 for (; arg < pp->argc; arg++)
3739 if (pp->arg[arg].reg == NULL)
3741 magic = (magic & 0xffffff) | (arg << 24);
3743 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
3745 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
3746 if (ops[j].cc_scratch != magic) {
3747 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
3751 // ok: have already been here
3754 ops[j].cc_scratch = magic;
3756 if (g_labels[j] != NULL && g_label_refs[j].i != -1) {
3757 lr = &g_label_refs[j];
3758 if (lr->next != NULL)
3760 for (; lr->next; lr = lr->next) {
3761 check_i(&ops[j], lr->i);
3762 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
3764 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3765 arg_grp, arg, magic, need_op_saving, may_reuse);
3770 check_i(&ops[j], lr->i);
3771 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
3773 if (j > 0 && LAST_OP(j - 1)) {
3774 // follow last branch in reverse
3779 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3780 arg_grp, arg, magic, need_op_saving, may_reuse);
3786 if (ops[j].op == OP_CALL)
3788 if (pp->is_unresolved)
3793 ferr(po, "arg collect hit unparsed call '%s'\n",
3794 ops[j].operand[0].name);
3795 if (may_reuse && pp_tmp->argc_stack > 0)
3796 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
3797 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
3799 // esp adjust of 0 means we collected it before
3800 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP
3801 && (ops[j].operand[1].type != OPT_CONST
3802 || ops[j].operand[1].val != 0))
3804 if (pp->is_unresolved)
3807 ferr(po, "arg collect %d/%d hit esp adjust of %d\n",
3808 arg, pp->argc, ops[j].operand[1].val);
3810 else if (ops[j].op == OP_POP && !(ops[j].flags & OPF_DONE))
3812 if (pp->is_unresolved)
3815 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
3817 else if (ops[j].flags & OPF_CJMP)
3819 if (pp->is_unresolved)
3824 else if (ops[j].op == OP_PUSH
3825 && !(ops[j].flags & (OPF_FARGNR|OPF_DONE)))
3827 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
3830 ops[j].p_argnext = -1;
3831 po_tmp = pp->arg[arg].datap;
3833 ops[j].p_argnext = po_tmp - ops;
3834 pp->arg[arg].datap = &ops[j];
3836 need_to_save_current = 0;
3839 if (ops[j].operand[0].type == OPT_REG)
3840 reg = ops[j].operand[0].reg;
3842 if (!need_op_saving) {
3843 ret = scan_for_mod(&ops[j], j + 1, i, 1);
3844 need_to_save_current = (ret >= 0);
3846 if (need_op_saving || need_to_save_current) {
3847 // mark this push as one that needs operand saving
3848 ops[j].flags &= ~OPF_RMD;
3849 if (ops[j].p_argnum == 0) {
3850 ops[j].p_argnum = arg + 1;
3851 save_args |= 1 << arg;
3853 else if (ops[j].p_argnum < arg + 1) {
3854 // XXX: might kill valid var..
3855 //*save_arg_vars &= ~(1 << (ops[j].p_argnum - 1));
3856 ops[j].p_argnum = arg + 1;
3857 save_args |= 1 << arg;
3860 if (save_args_seen & (1 << (ops[j].p_argnum - 1))) {
3863 if (arg_grp_current >= MAX_ARG_GRP)
3864 ferr(&ops[j], "out of arg groups (arg%d), f %s\n",
3865 ops[j].p_argnum, pp->name);
3868 else if (ops[j].p_argnum == 0)
3869 ops[j].flags |= OPF_RMD;
3871 // some PUSHes are reused by different calls on other branches,
3872 // but that can't happen if we didn't branch, so they
3873 // can be removed from future searches (handles nested calls)
3875 ops[j].flags |= OPF_FARGNR;
3877 ops[j].flags |= OPF_FARG;
3878 ops[j].flags &= ~OPF_RSAVE;
3880 // check for __VALIST
3881 if (!pp->is_unresolved && g_func_pp != NULL
3882 && pp->arg[arg].type.is_va_list)
3885 ret = resolve_origin(j, &ops[j].operand[0],
3886 magic + 1, &k, NULL);
3887 if (ret == 1 && k >= 0)
3889 if (ops[k].op == OP_LEA) {
3890 snprintf(buf, sizeof(buf), "arg_%X",
3891 g_func_pp->argc_stack * 4);
3892 if (!g_func_pp->is_vararg
3893 || strstr(ops[k].operand[1].name, buf))
3895 ops[k].flags |= OPF_RMD | OPF_DONE;
3896 ops[j].flags |= OPF_RMD | OPF_VAPUSH;
3897 save_args &= ~(1 << arg);
3901 ferr(&ops[j], "lea va_list used, but no vararg?\n");
3903 // check for va_list from g_func_pp arg too
3904 else if (ops[k].op == OP_MOV
3905 && is_stack_access(&ops[k], &ops[k].operand[1]))
3907 ret = stack_frame_access(&ops[k], &ops[k].operand[1],
3908 buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
3910 ops[k].flags |= OPF_RMD | OPF_DONE;
3911 ops[j].flags |= OPF_RMD;
3912 ops[j].p_argpass = ret + 1;
3913 save_args &= ~(1 << arg);
3920 *save_arg_vars |= save_args;
3922 // tracking reg usage
3924 *regmask |= 1 << reg;
3927 if (!pp->is_unresolved) {
3929 for (; arg < pp->argc; arg++)
3930 if (pp->arg[arg].reg == NULL)
3933 magic = (magic & 0xffffff) | (arg << 24);
3936 if (ops[j].p_arggrp > arg_grp_current) {
3938 arg_grp_current = ops[j].p_arggrp;
3940 if (ops[j].p_argnum > 0)
3941 save_args_seen |= 1 << (ops[j].p_argnum - 1);
3944 if (arg < pp->argc) {
3945 ferr(po, "arg collect failed for '%s': %d/%d\n",
3946 pp->name, arg, pp->argc);
3950 if (arg_grp_current > *arg_grp)
3951 *arg_grp = arg_grp_current;
3956 static int collect_call_args(struct parsed_op *po, int i,
3957 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3960 // arg group is for cases when pushes for
3961 // multiple funcs are going on
3962 struct parsed_op *po_tmp;
3963 int save_arg_vars_current = 0;
3968 ret = collect_call_args_r(po, i, pp, regmask,
3969 &save_arg_vars_current, &arg_grp, 0, magic, 0, 0);
3974 // propagate arg_grp
3975 for (a = 0; a < pp->argc; a++) {
3976 if (pp->arg[a].reg != NULL)
3979 po_tmp = pp->arg[a].datap;
3980 while (po_tmp != NULL) {
3981 po_tmp->p_arggrp = arg_grp;
3982 if (po_tmp->p_argnext > 0)
3983 po_tmp = &ops[po_tmp->p_argnext];
3989 save_arg_vars[arg_grp] |= save_arg_vars_current;
3991 if (pp->is_unresolved) {
3993 pp->argc_stack += ret;
3994 for (a = 0; a < pp->argc; a++)
3995 if (pp->arg[a].type.name == NULL)
3996 pp->arg[a].type.name = strdup("int");
4002 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
4006 for (i = 0; i < pp->argc; i++)
4007 if (pp->arg[i].reg == NULL)
4011 memmove(&pp->arg[i + 1], &pp->arg[i],
4012 sizeof(pp->arg[0]) * pp->argc_stack);
4013 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
4014 pp->arg[i].reg = strdup(reg);
4015 pp->arg[i].type.name = strdup("int");
4020 static void output_std_flags(FILE *fout, struct parsed_op *po,
4021 int *pfomask, const char *dst_opr_text)
4023 if (*pfomask & (1 << PFO_Z)) {
4024 fprintf(fout, "\n cond_z = (%s%s == 0);",
4025 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
4026 *pfomask &= ~(1 << PFO_Z);
4028 if (*pfomask & (1 << PFO_S)) {
4029 fprintf(fout, "\n cond_s = (%s%s < 0);",
4030 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
4031 *pfomask &= ~(1 << PFO_S);
4036 OPP_FORCE_NORETURN = (1 << 0),
4037 OPP_SIMPLE_ARGS = (1 << 1),
4038 OPP_ALIGN = (1 << 2),
4041 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
4044 const char *cconv = "";
4046 if (pp->is_fastcall)
4047 cconv = "__fastcall ";
4048 else if (pp->is_stdcall && pp->argc_reg == 0)
4049 cconv = "__stdcall ";
4051 fprintf(fout, (flags & OPP_ALIGN) ? "%-16s" : "%s", cconv);
4053 if (pp->is_noreturn || (flags & OPP_FORCE_NORETURN))
4054 fprintf(fout, "noreturn ");
4057 static void output_pp(FILE *fout, const struct parsed_proto *pp,
4062 fprintf(fout, (flags & OPP_ALIGN) ? "%-5s" : "%s ",
4066 output_pp_attrs(fout, pp, flags);
4069 fprintf(fout, "%s", pp->name);
4074 for (i = 0; i < pp->argc; i++) {
4076 fprintf(fout, ", ");
4077 if (pp->arg[i].fptr != NULL && !(flags & OPP_SIMPLE_ARGS)) {
4079 output_pp(fout, pp->arg[i].fptr, 0);
4081 else if (pp->arg[i].type.is_retreg) {
4082 fprintf(fout, "u32 *r_%s", pp->arg[i].reg);
4085 fprintf(fout, "%s", pp->arg[i].type.name);
4087 fprintf(fout, " a%d", i + 1);
4090 if (pp->is_vararg) {
4092 fprintf(fout, ", ");
4093 fprintf(fout, "...");
4098 static int get_pp_arg_regmask(const struct parsed_proto *pp)
4103 for (i = 0; i < pp->argc; i++) {
4104 if (pp->arg[i].reg != NULL) {
4105 reg = char_array_i(regs_r32,
4106 ARRAY_SIZE(regs_r32), pp->arg[i].reg);
4108 ferr(ops, "arg '%s' of func '%s' is not a reg?\n",
4109 pp->arg[i].reg, pp->name);
4110 regmask |= 1 << reg;
4117 static char *saved_arg_name(char *buf, size_t buf_size, int grp, int num)
4123 snprintf(buf1, sizeof(buf1), "%d", grp);
4124 snprintf(buf, buf_size, "s%s_a%d", buf1, num);
4129 static void gen_x_cleanup(int opcnt);
4131 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
4133 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
4134 struct parsed_opr *last_arith_dst = NULL;
4135 char buf1[256], buf2[256], buf3[256], cast[64];
4136 struct parsed_proto *pp, *pp_tmp;
4137 struct parsed_data *pd;
4139 int save_arg_vars[MAX_ARG_GRP] = { 0, };
4141 int need_tmp_var = 0;
4144 int label_pending = 0;
4145 int regmask_save = 0; // regs saved/restored in this func
4146 int regmask_arg = 0; // regs carrying function args (fastcall, etc)
4147 int regmask_now; // temp
4148 int regmask_init = 0; // regs that need zero initialization
4149 int regmask_pp = 0; // regs used in complex push-pop graph
4150 int regmask = 0; // used regs
4160 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
4161 g_stack_frame_used = 0;
4163 g_func_pp = proto_parse(fhdr, funcn, 0);
4164 if (g_func_pp == NULL)
4165 ferr(ops, "proto_parse failed for '%s'\n", funcn);
4167 regmask_arg = get_pp_arg_regmask(g_func_pp);
4170 // - resolve all branches
4171 // - parse calls with labels
4172 resolve_branches_parse_calls(opcnt);
4175 // - handle ebp/esp frame, remove ops related to it
4176 scan_prologue_epilogue(opcnt);
4179 // - remove dead labels
4180 for (i = 0; i < opcnt; i++)
4182 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
4189 // - process trivial calls
4190 for (i = 0; i < opcnt; i++)
4193 if (po->flags & (OPF_RMD|OPF_DONE))
4196 if (po->op == OP_CALL)
4198 pp = process_call_early(i, opcnt, &j);
4200 if (!(po->flags & OPF_ATAIL))
4201 // since we know the args, try to collect them
4202 if (collect_call_args_early(po, i, pp, ®mask) != 0)
4208 // commit esp adjust
4209 if (ops[j].op != OP_POP)
4210 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
4212 for (l = 0; l < pp->argc_stack; l++)
4213 ops[j + l].flags |= OPF_DONE | OPF_RMD;
4217 if (strstr(pp->ret_type.name, "int64"))
4220 po->flags |= OPF_DONE;
4227 // - handle push <const>/pop pairs
4228 for (i = 0; i < opcnt; i++)
4231 if (po->flags & (OPF_RMD|OPF_DONE))
4234 if (po->op == OP_CALL && !(po->flags & OPF_DONE))
4236 pp = process_call(i, opcnt);
4238 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
4239 // since we know the args, collect them
4240 collect_call_args(po, i, pp, ®mask, save_arg_vars,
4244 if (strstr(pp->ret_type.name, "int64"))
4247 else if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4248 && !(po->flags & OPF_RSAVE) && po->operand[0].type == OPT_CONST)
4249 scan_for_pop_const(i, opcnt, ®mask_pp);
4253 // - find POPs for PUSHes, rm both
4254 // - scan for STD/CLD, propagate DF
4255 // - scan for all used registers
4256 // - find flag set ops for their users
4257 // - do unreselved calls
4258 // - declare indirect functions
4259 for (i = 0; i < opcnt; i++)
4262 if (po->flags & (OPF_RMD|OPF_DONE))
4265 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
4266 reg = po->operand[0].reg;
4267 if (!(regmask & (1 << reg)))
4268 // not a reg save after all, rerun scan_for_pop
4269 po->flags &= ~OPF_RSAVE;
4271 regmask_save |= 1 << reg;
4274 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4275 && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
4277 if (po->operand[0].type == OPT_REG)
4279 reg = po->operand[0].reg;
4281 ferr(po, "reg not set for push?\n");
4284 ret = scan_for_pop(i + 1, opcnt,
4285 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
4288 ferr(po, "too much depth: %d\n", depth);
4290 po->flags |= OPF_RMD;
4291 scan_for_pop(i + 1, opcnt, po->operand[0].name,
4292 i + opcnt * 4, 0, &depth, 1);
4295 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
4298 if (regmask & (1 << reg)) {
4299 if (regmask_save & (1 << reg))
4300 ferr(po, "%s already saved?\n", po->operand[0].name);
4304 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
4310 if (po->op == OP_STD) {
4311 po->flags |= OPF_DF | OPF_RMD | OPF_DONE;
4312 scan_propagate_df(i + 1, opcnt);
4315 regmask_now = po->regmask_src | po->regmask_dst;
4316 if (regmask_now & (1 << xBP)) {
4317 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
4318 if (po->regmask_dst & (1 << xBP))
4319 // compiler decided to drop bp frame and use ebp as scratch
4320 scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
4322 regmask_now &= ~(1 << xBP);
4326 regmask |= regmask_now;
4328 if (po->flags & OPF_CC)
4330 int setters[16], cnt = 0, branched = 0;
4332 ret = scan_for_flag_set(i, i + opcnt * 6,
4333 &branched, setters, &cnt);
4334 if (ret < 0 || cnt <= 0)
4335 ferr(po, "unable to trace flag setter(s)\n");
4336 if (cnt > ARRAY_SIZE(setters))
4337 ferr(po, "too many flag setters\n");
4339 for (j = 0; j < cnt; j++)
4341 tmp_op = &ops[setters[j]]; // flag setter
4344 // to get nicer code, we try to delay test and cmp;
4345 // if we can't because of operand modification, or if we
4346 // have arith op, or branch, make it calculate flags explicitly
4347 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
4349 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
4350 pfomask = 1 << po->pfo;
4352 else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
4353 pfomask = 1 << po->pfo;
4356 // see if we'll be able to handle based on op result
4357 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
4358 && po->pfo != PFO_Z && po->pfo != PFO_S
4359 && po->pfo != PFO_P)
4361 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
4363 pfomask = 1 << po->pfo;
4366 if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
4367 propagate_lmod(tmp_op, &tmp_op->operand[0],
4368 &tmp_op->operand[1]);
4369 if (tmp_op->operand[0].lmod == OPLM_DWORD)
4374 tmp_op->pfomask |= pfomask;
4375 cond_vars |= pfomask;
4377 // note: may overwrite, currently not a problem
4381 if (po->op == OP_RCL || po->op == OP_RCR
4382 || po->op == OP_ADC || po->op == OP_SBB)
4383 cond_vars |= 1 << PFO_C;
4386 if (po->op == OP_CMPS || po->op == OP_SCAS) {
4387 cond_vars |= 1 << PFO_Z;
4389 else if (po->op == OP_MUL
4390 || (po->op == OP_IMUL && po->operand_cnt == 1))
4392 if (po->operand[0].lmod == OPLM_DWORD)
4395 else if (po->op == OP_CALL) {
4396 // note: resolved non-reg calls are OPF_DONE already
4399 ferr(po, "NULL pp\n");
4401 if (pp->is_unresolved) {
4402 int regmask_stack = 0;
4403 collect_call_args(po, i, pp, ®mask, save_arg_vars,
4406 // this is pretty rough guess:
4407 // see ecx and edx were pushed (and not their saved versions)
4408 for (arg = 0; arg < pp->argc; arg++) {
4409 if (pp->arg[arg].reg != NULL)
4412 tmp_op = pp->arg[arg].datap;
4414 ferr(po, "parsed_op missing for arg%d\n", arg);
4415 if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
4416 regmask_stack |= 1 << tmp_op->operand[0].reg;
4419 if (!((regmask_stack & (1 << xCX))
4420 && (regmask_stack & (1 << xDX))))
4422 if (pp->argc_stack != 0
4423 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
4425 pp_insert_reg_arg(pp, "ecx");
4426 pp->is_fastcall = 1;
4427 regmask_init |= 1 << xCX;
4428 regmask |= 1 << xCX;
4430 if (pp->argc_stack != 0
4431 || ((regmask | regmask_arg) & (1 << xDX)))
4433 pp_insert_reg_arg(pp, "edx");
4434 regmask_init |= 1 << xDX;
4435 regmask |= 1 << xDX;
4439 // note: __cdecl doesn't fall into is_unresolved category
4440 if (pp->argc_stack > 0)
4444 for (arg = 0; arg < pp->argc; arg++) {
4445 if (pp->arg[arg].reg != NULL) {
4446 reg = char_array_i(regs_r32,
4447 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
4449 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
4450 if (!(regmask & (1 << reg))) {
4451 regmask_init |= 1 << reg;
4452 regmask |= 1 << reg;
4457 else if (po->op == OP_MOV && po->operand[0].pp != NULL
4458 && po->operand[1].pp != NULL)
4460 // <var> = offset <something>
4461 if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
4462 && !IS_START(po->operand[1].name, "off_"))
4464 if (!po->operand[0].pp->is_fptr)
4465 ferr(po, "%s not declared as fptr when it should be\n",
4466 po->operand[0].name);
4467 if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
4468 pp_print(buf1, sizeof(buf1), po->operand[0].pp);
4469 pp_print(buf2, sizeof(buf2), po->operand[1].pp);
4470 fnote(po, "var: %s\n", buf1);
4471 fnote(po, "func: %s\n", buf2);
4472 ferr(po, "^ mismatch\n");
4476 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
4477 regmask |= 1 << xAX;
4478 else if (po->op == OP_DIV || po->op == OP_IDIV) {
4479 // 32bit division is common, look for it
4480 if (po->op == OP_DIV)
4481 ret = scan_for_reg_clear(i, xDX);
4483 ret = scan_for_cdq_edx(i);
4485 po->flags |= OPF_32BIT;
4489 else if (po->op == OP_CLD)
4490 po->flags |= OPF_RMD | OPF_DONE;
4492 if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
4498 // - confirm regmask_save, it might have been reduced
4499 if (regmask_save != 0)
4502 for (i = 0; i < opcnt; i++) {
4504 if (po->flags & OPF_RMD)
4507 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
4508 regmask_save |= 1 << po->operand[0].reg;
4512 // output starts here
4514 // define userstack size
4515 if (g_func_pp->is_userstack) {
4516 fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
4517 fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
4518 fprintf(fout, "#endif\n");
4521 // the function itself
4522 ferr_assert(ops, !g_func_pp->is_fptr);
4523 output_pp(fout, g_func_pp,
4524 (g_ida_func_attr & IDAFA_NORETURN) ? OPP_FORCE_NORETURN : 0);
4525 fprintf(fout, "\n{\n");
4527 // declare indirect functions
4528 for (i = 0; i < opcnt; i++) {
4530 if (po->flags & OPF_RMD)
4533 if (po->op == OP_CALL) {
4536 ferr(po, "NULL pp\n");
4538 if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
4539 if (pp->name[0] != 0) {
4540 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
4541 memcpy(pp->name, "i_", 2);
4543 // might be declared already
4545 for (j = 0; j < i; j++) {
4546 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
4547 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
4557 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
4560 output_pp(fout, pp, OPP_SIMPLE_ARGS);
4561 fprintf(fout, ";\n");
4566 // output LUTs/jumptables
4567 for (i = 0; i < g_func_pd_cnt; i++) {
4569 fprintf(fout, " static const ");
4570 if (pd->type == OPT_OFFSET) {
4571 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
4573 for (j = 0; j < pd->count; j++) {
4575 fprintf(fout, ", ");
4576 fprintf(fout, "&&%s", pd->d[j].u.label);
4580 fprintf(fout, "%s %s[] =\n { ",
4581 lmod_type_u(ops, pd->lmod), pd->label);
4583 for (j = 0; j < pd->count; j++) {
4585 fprintf(fout, ", ");
4586 fprintf(fout, "%u", pd->d[j].u.val);
4589 fprintf(fout, " };\n");
4593 // declare stack frame, va_arg
4595 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
4596 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
4600 if (g_func_pp->is_userstack) {
4601 fprintf(fout, " u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
4602 fprintf(fout, " u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
4606 if (g_func_pp->is_vararg) {
4607 fprintf(fout, " va_list ap;\n");
4611 // declare arg-registers
4612 for (i = 0; i < g_func_pp->argc; i++) {
4613 if (g_func_pp->arg[i].reg != NULL) {
4614 reg = char_array_i(regs_r32,
4615 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
4616 if (regmask & (1 << reg)) {
4617 if (g_func_pp->arg[i].type.is_retreg)
4618 fprintf(fout, " u32 %s = *r_%s;\n",
4619 g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
4621 fprintf(fout, " u32 %s = (u32)a%d;\n",
4622 g_func_pp->arg[i].reg, i + 1);
4625 if (g_func_pp->arg[i].type.is_retreg)
4626 ferr(ops, "retreg '%s' is unused?\n",
4627 g_func_pp->arg[i].reg);
4628 fprintf(fout, " // %s = a%d; // unused\n",
4629 g_func_pp->arg[i].reg, i + 1);
4635 // declare normal registers
4636 regmask_now = regmask & ~regmask_arg;
4637 regmask_now &= ~(1 << xSP);
4638 if (regmask_now & 0x00ff) {
4639 for (reg = 0; reg < 8; reg++) {
4640 if (regmask_now & (1 << reg)) {
4641 fprintf(fout, " u32 %s", regs_r32[reg]);
4642 if (regmask_init & (1 << reg))
4643 fprintf(fout, " = 0");
4644 fprintf(fout, ";\n");
4649 if (regmask_now & 0xff00) {
4650 for (reg = 8; reg < 16; reg++) {
4651 if (regmask_now & (1 << reg)) {
4652 fprintf(fout, " mmxr %s", regs_r32[reg]);
4653 if (regmask_init & (1 << reg))
4654 fprintf(fout, " = { 0, }");
4655 fprintf(fout, ";\n");
4662 for (reg = 0; reg < 8; reg++) {
4663 if (regmask_save & (1 << reg)) {
4664 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
4670 for (i = 0; i < ARRAY_SIZE(save_arg_vars); i++) {
4671 if (save_arg_vars[i] == 0)
4673 for (reg = 0; reg < 32; reg++) {
4674 if (save_arg_vars[i] & (1 << reg)) {
4675 fprintf(fout, " u32 %s;\n",
4676 saved_arg_name(buf1, sizeof(buf1), i, reg + 1));
4682 // declare push-pop temporaries
4684 for (reg = 0; reg < 8; reg++) {
4685 if (regmask_pp & (1 << reg)) {
4686 fprintf(fout, " u32 pp_%s;\n", regs_r32[reg]);
4693 for (i = 0; i < 8; i++) {
4694 if (cond_vars & (1 << i)) {
4695 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
4702 fprintf(fout, " u32 tmp;\n");
4707 fprintf(fout, " u64 tmp64;\n");
4712 fprintf(fout, "\n");
4714 if (g_func_pp->is_vararg) {
4715 if (g_func_pp->argc_stack == 0)
4716 ferr(ops, "vararg func without stack args?\n");
4717 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
4721 for (i = 0; i < opcnt; i++)
4723 if (g_labels[i] != NULL) {
4724 fprintf(fout, "\n%s:\n", g_labels[i]);
4727 delayed_flag_op = NULL;
4728 last_arith_dst = NULL;
4732 if (po->flags & OPF_RMD)
4737 #define assert_operand_cnt(n_) \
4738 if (po->operand_cnt != n_) \
4739 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
4741 // conditional/flag using op?
4742 if (po->flags & OPF_CC)
4748 // we go through all this trouble to avoid using parsed_flag_op,
4749 // which makes generated code much nicer
4750 if (delayed_flag_op != NULL)
4752 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
4753 po->pfo, po->pfo_inv);
4756 else if (last_arith_dst != NULL
4757 && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
4758 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
4761 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4762 out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
4763 last_arith_dst->lmod, buf3);
4766 else if (tmp_op != NULL) {
4767 // use preprocessed flag calc results
4768 if (!(tmp_op->pfomask & (1 << po->pfo)))
4769 ferr(po, "not prepared for pfo %d\n", po->pfo);
4771 // note: pfo_inv was not yet applied
4772 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
4773 po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
4776 ferr(po, "all methods of finding comparison failed\n");
4779 if (po->flags & OPF_JMP) {
4780 fprintf(fout, " if %s", buf1);
4782 else if (po->op == OP_RCL || po->op == OP_RCR
4783 || po->op == OP_ADC || po->op == OP_SBB)
4786 fprintf(fout, " cond_%s = %s;\n",
4787 parsed_flag_op_names[po->pfo], buf1);
4789 else if (po->flags & OPF_DATA) { // SETcc
4790 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
4791 fprintf(fout, " %s = %s;", buf2, buf1);
4794 ferr(po, "unhandled conditional op\n");
4798 pfomask = po->pfomask;
4800 if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
4801 struct parsed_opr opr = {0,};
4804 opr.lmod = OPLM_DWORD;
4805 ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
4807 if (ret != 1 || uval == 0) {
4808 // we need initial flags for ecx=0 case..
4809 if (i > 0 && ops[i - 1].op == OP_XOR
4810 && IS(ops[i - 1].operand[0].name,
4811 ops[i - 1].operand[1].name))
4813 fprintf(fout, " cond_z = ");
4814 if (pfomask & (1 << PFO_C))
4815 fprintf(fout, "cond_c = ");
4816 fprintf(fout, "0;\n");
4818 else if (last_arith_dst != NULL) {
4819 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4820 out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
4821 last_arith_dst->lmod, buf3);
4822 fprintf(fout, " cond_z = %s;\n", buf1);
4825 ferr(po, "missing initial ZF\n");
4832 assert_operand_cnt(2);
4833 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4834 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4835 default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
4836 fprintf(fout, " %s = %s;", buf1,
4837 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4842 assert_operand_cnt(2);
4843 po->operand[1].lmod = OPLM_DWORD; // always
4844 fprintf(fout, " %s = %s;",
4845 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4846 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4851 assert_operand_cnt(2);
4852 fprintf(fout, " %s = %s;",
4853 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4854 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4858 assert_operand_cnt(2);
4859 switch (po->operand[1].lmod) {
4861 strcpy(buf3, "(s8)");
4864 strcpy(buf3, "(s16)");
4867 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
4869 fprintf(fout, " %s = %s;",
4870 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4871 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4876 assert_operand_cnt(2);
4877 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4878 fprintf(fout, " tmp = %s;",
4879 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
4880 fprintf(fout, " %s = %s;",
4881 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4882 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4883 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4884 fprintf(fout, " %s = %stmp;",
4885 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
4886 default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
4887 snprintf(g_comment, sizeof(g_comment), "xchg");
4891 assert_operand_cnt(1);
4892 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4893 fprintf(fout, " %s = ~%s;", buf1, buf1);
4897 assert_operand_cnt(2);
4898 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4899 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4900 fprintf(fout, " %s = *(u8 *)(%s + %s);", buf1, buf2, buf1);
4901 strcpy(g_comment, "xlat");
4905 assert_operand_cnt(2);
4906 fprintf(fout, " %s = (s32)%s >> 31;",
4907 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4908 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4909 strcpy(g_comment, "cdq");
4913 assert_operand_cnt(3);
4914 if (po->flags & OPF_REP) {
4919 fprintf(fout, " eax = %sesi; esi %c= %d;",
4920 lmod_cast_u_ptr(po, po->operand[0].lmod),
4921 (po->flags & OPF_DF) ? '-' : '+',
4922 lmod_bytes(po, po->operand[0].lmod));
4923 strcpy(g_comment, "lods");
4928 assert_operand_cnt(3);
4929 if (po->flags & OPF_REP) {
4930 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
4931 (po->flags & OPF_DF) ? '-' : '+',
4932 lmod_bytes(po, po->operand[0].lmod));
4933 fprintf(fout, " %sedi = eax;",
4934 lmod_cast_u_ptr(po, po->operand[0].lmod));
4935 strcpy(g_comment, "rep stos");
4938 fprintf(fout, " %sedi = eax; edi %c= %d;",
4939 lmod_cast_u_ptr(po, po->operand[0].lmod),
4940 (po->flags & OPF_DF) ? '-' : '+',
4941 lmod_bytes(po, po->operand[0].lmod));
4942 strcpy(g_comment, "stos");
4947 assert_operand_cnt(3);
4948 j = lmod_bytes(po, po->operand[0].lmod);
4949 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4950 l = (po->flags & OPF_DF) ? '-' : '+';
4951 if (po->flags & OPF_REP) {
4953 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
4956 " %sedi = %sesi;", buf1, buf1);
4957 strcpy(g_comment, "rep movs");
4960 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
4961 buf1, buf1, l, j, l, j);
4962 strcpy(g_comment, "movs");
4967 // repe ~ repeat while ZF=1
4968 assert_operand_cnt(3);
4969 j = lmod_bytes(po, po->operand[0].lmod);
4970 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4971 l = (po->flags & OPF_DF) ? '-' : '+';
4972 if (po->flags & OPF_REP) {
4974 " for (; ecx != 0; ecx--) {\n");
4975 if (pfomask & (1 << PFO_C)) {
4978 " cond_c = %sesi < %sedi;\n", buf1, buf1);
4979 pfomask &= ~(1 << PFO_C);
4982 " cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
4983 buf1, buf1, l, j, l, j);
4985 " if (cond_z %s 0) break;\n",
4986 (po->flags & OPF_REPZ) ? "==" : "!=");
4989 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
4990 (po->flags & OPF_REPZ) ? "e" : "ne");
4994 " cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
4995 buf1, buf1, l, j, l, j);
4996 strcpy(g_comment, "cmps");
4998 pfomask &= ~(1 << PFO_Z);
4999 last_arith_dst = NULL;
5000 delayed_flag_op = NULL;
5004 // only does ZF (for now)
5005 // repe ~ repeat while ZF=1
5006 assert_operand_cnt(3);
5007 j = lmod_bytes(po, po->operand[0].lmod);
5008 l = (po->flags & OPF_DF) ? '-' : '+';
5009 if (po->flags & OPF_REP) {
5011 " for (; ecx != 0; ecx--) {\n");
5013 " cond_z = (%seax == %sedi); edi %c= %d;\n",
5014 lmod_cast_u(po, po->operand[0].lmod),
5015 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
5017 " if (cond_z %s 0) break;\n",
5018 (po->flags & OPF_REPZ) ? "==" : "!=");
5021 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
5022 (po->flags & OPF_REPZ) ? "e" : "ne");
5025 fprintf(fout, " cond_z = (%seax == %sedi); edi %c= %d;",
5026 lmod_cast_u(po, po->operand[0].lmod),
5027 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
5028 strcpy(g_comment, "scas");
5030 pfomask &= ~(1 << PFO_Z);
5031 last_arith_dst = NULL;
5032 delayed_flag_op = NULL;
5035 // arithmetic w/flags
5037 if (po->operand[1].type == OPT_CONST && !po->operand[1].val) {
5038 // deal with complex dst clear
5039 assert_operand_cnt(2);
5040 fprintf(fout, " %s = %s;",
5041 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5042 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5043 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5044 output_std_flags(fout, po, &pfomask, buf1);
5045 last_arith_dst = &po->operand[0];
5046 delayed_flag_op = NULL;
5051 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5054 assert_operand_cnt(2);
5055 fprintf(fout, " %s %s= %s;",
5056 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5058 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5059 output_std_flags(fout, po, &pfomask, buf1);
5060 last_arith_dst = &po->operand[0];
5061 delayed_flag_op = NULL;
5066 assert_operand_cnt(2);
5067 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5068 if (pfomask & (1 << PFO_C)) {
5069 if (po->operand[1].type == OPT_CONST) {
5070 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5071 j = po->operand[1].val;
5074 if (po->op == OP_SHL)
5078 fprintf(fout, " cond_c = (%s >> %d) & 1;\n",
5082 ferr(po, "zero shift?\n");
5086 pfomask &= ~(1 << PFO_C);
5088 fprintf(fout, " %s %s= %s", buf1, op_to_c(po),
5089 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5090 if (po->operand[1].type != OPT_CONST)
5091 fprintf(fout, " & 0x1f");
5093 output_std_flags(fout, po, &pfomask, buf1);
5094 last_arith_dst = &po->operand[0];
5095 delayed_flag_op = NULL;
5099 assert_operand_cnt(2);
5100 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5101 fprintf(fout, " %s = %s%s >> %s;", buf1,
5102 lmod_cast_s(po, po->operand[0].lmod), buf1,
5103 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5104 output_std_flags(fout, po, &pfomask, buf1);
5105 last_arith_dst = &po->operand[0];
5106 delayed_flag_op = NULL;
5111 assert_operand_cnt(3);
5112 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5113 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5114 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5115 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5116 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[2]);
5117 if (po->operand[2].type != OPT_CONST)
5118 ferr(po, "TODO: masking\n");
5119 if (po->op == OP_SHLD) {
5120 fprintf(fout, " %s <<= %s; %s |= %s >> (%d - %s);",
5121 buf1, buf3, buf1, buf2, l, buf3);
5122 strcpy(g_comment, "shld");
5125 fprintf(fout, " %s >>= %s; %s |= %s << (%d - %s);",
5126 buf1, buf3, buf1, buf2, l, buf3);
5127 strcpy(g_comment, "shrd");
5129 output_std_flags(fout, po, &pfomask, buf1);
5130 last_arith_dst = &po->operand[0];
5131 delayed_flag_op = NULL;
5136 assert_operand_cnt(2);
5137 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5138 if (po->operand[1].type == OPT_CONST) {
5139 j = po->operand[1].val;
5140 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
5141 fprintf(fout, po->op == OP_ROL ?
5142 " %s = (%s << %d) | (%s >> %d);" :
5143 " %s = (%s >> %d) | (%s << %d);",
5144 buf1, buf1, j, buf1,
5145 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
5149 output_std_flags(fout, po, &pfomask, buf1);
5150 last_arith_dst = &po->operand[0];
5151 delayed_flag_op = NULL;
5156 assert_operand_cnt(2);
5157 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5158 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5159 if (po->operand[1].type == OPT_CONST) {
5160 j = po->operand[1].val % l;
5162 ferr(po, "zero rotate\n");
5163 fprintf(fout, " tmp = (%s >> %d) & 1;\n",
5164 buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
5165 if (po->op == OP_RCL) {
5167 " %s = (%s << %d) | (cond_c << %d)",
5168 buf1, buf1, j, j - 1);
5170 fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
5174 " %s = (%s >> %d) | (cond_c << %d)",
5175 buf1, buf1, j, l - j);
5177 fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
5179 fprintf(fout, ";\n");
5180 fprintf(fout, " cond_c = tmp;");
5184 strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
5185 output_std_flags(fout, po, &pfomask, buf1);
5186 last_arith_dst = &po->operand[0];
5187 delayed_flag_op = NULL;
5191 assert_operand_cnt(2);
5192 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5193 if (IS(opr_name(po, 0), opr_name(po, 1))) {
5194 // special case for XOR
5195 if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
5196 fprintf(fout, " cond_be = 1;\n");
5197 pfomask &= ~(1 << PFO_BE);
5199 fprintf(fout, " %s = 0;",
5200 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5201 last_arith_dst = &po->operand[0];
5202 delayed_flag_op = NULL;
5208 assert_operand_cnt(2);
5209 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5210 if (pfomask & (1 << PFO_C)) {
5211 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5212 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5213 if (po->operand[0].lmod == OPLM_DWORD) {
5214 fprintf(fout, " tmp64 = (u64)%s + %s;\n", buf1, buf2);
5215 fprintf(fout, " cond_c = tmp64 >> 32;\n");
5216 fprintf(fout, " %s = (u32)tmp64;",
5217 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5218 strcat(g_comment, "add64");
5221 fprintf(fout, " cond_c = ((u32)%s + %s) >> %d;\n",
5222 buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
5223 fprintf(fout, " %s += %s;",
5224 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5227 pfomask &= ~(1 << PFO_C);
5228 output_std_flags(fout, po, &pfomask, buf1);
5229 last_arith_dst = &po->operand[0];
5230 delayed_flag_op = NULL;
5236 assert_operand_cnt(2);
5237 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5238 if (pfomask & ~((1 << PFO_Z) | (1 << PFO_S))) {
5239 for (j = 0; j <= PFO_LE; j++) {
5240 if (!(pfomask & (1 << j)))
5242 if (j == PFO_Z || j == PFO_S)
5245 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5246 fprintf(fout, " cond_%s = %s;\n",
5247 parsed_flag_op_names[j], buf1);
5248 pfomask &= ~(1 << j);
5255 assert_operand_cnt(2);
5256 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5257 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5258 if (po->op == OP_SBB
5259 && IS(po->operand[0].name, po->operand[1].name))
5261 // avoid use of unitialized var
5262 fprintf(fout, " %s = -cond_c;", buf1);
5263 // carry remains what it was
5264 pfomask &= ~(1 << PFO_C);
5267 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
5268 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5270 output_std_flags(fout, po, &pfomask, buf1);
5271 last_arith_dst = &po->operand[0];
5272 delayed_flag_op = NULL;
5276 assert_operand_cnt(2);
5277 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5278 fprintf(fout, " %s = %s ? __builtin_ffs(%s) - 1 : 0;",
5279 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5281 output_std_flags(fout, po, &pfomask, buf1);
5282 last_arith_dst = &po->operand[0];
5283 delayed_flag_op = NULL;
5284 strcat(g_comment, "bsf");
5288 if (pfomask & ~(PFOB_S | PFOB_S | PFOB_C)) {
5289 for (j = 0; j <= PFO_LE; j++) {
5290 if (!(pfomask & (1 << j)))
5292 if (j == PFO_Z || j == PFO_S || j == PFO_C)
5295 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5296 fprintf(fout, " cond_%s = %s;\n",
5297 parsed_flag_op_names[j], buf1);
5298 pfomask &= ~(1 << j);
5304 if (pfomask & (1 << PFO_C))
5305 // carry is unaffected by inc/dec.. wtf?
5306 ferr(po, "carry propagation needed\n");
5308 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5309 if (po->operand[0].type == OPT_REG) {
5310 strcpy(buf2, po->op == OP_INC ? "++" : "--");
5311 fprintf(fout, " %s%s;", buf1, buf2);
5314 strcpy(buf2, po->op == OP_INC ? "+" : "-");
5315 fprintf(fout, " %s %s= 1;", buf1, buf2);
5317 output_std_flags(fout, po, &pfomask, buf1);
5318 last_arith_dst = &po->operand[0];
5319 delayed_flag_op = NULL;
5323 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5324 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
5325 fprintf(fout, " %s = -%s%s;", buf1,
5326 lmod_cast_s(po, po->operand[0].lmod), buf2);
5327 last_arith_dst = &po->operand[0];
5328 delayed_flag_op = NULL;
5329 if (pfomask & (1 << PFO_C)) {
5330 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
5331 pfomask &= ~(1 << PFO_C);
5336 if (po->operand_cnt == 2) {
5337 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5340 if (po->operand_cnt == 3)
5341 ferr(po, "TODO imul3\n");
5344 assert_operand_cnt(1);
5345 switch (po->operand[0].lmod) {
5347 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
5348 fprintf(fout, " tmp64 = %seax * %s%s;\n", buf1, buf1,
5349 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
5350 fprintf(fout, " edx = tmp64 >> 32;\n");
5351 fprintf(fout, " eax = tmp64;");
5354 strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
5355 fprintf(fout, " LOWORD(eax) = %seax * %s;", buf1,
5356 out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
5360 ferr(po, "TODO: unhandled mul type\n");
5363 last_arith_dst = NULL;
5364 delayed_flag_op = NULL;
5369 assert_operand_cnt(1);
5370 if (po->operand[0].lmod != OPLM_DWORD)
5371 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
5373 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5374 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
5375 po->op == OP_IDIV));
5376 switch (po->operand[0].lmod) {
5378 if (po->flags & OPF_32BIT)
5379 snprintf(buf3, sizeof(buf3), "%seax", buf2);
5381 fprintf(fout, " tmp64 = ((u64)edx << 32) | eax;\n");
5382 snprintf(buf3, sizeof(buf3), "%stmp64",
5383 (po->op == OP_IDIV) ? "(s64)" : "");
5385 if (po->operand[0].type == OPT_REG
5386 && po->operand[0].reg == xDX)
5388 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5389 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5392 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5393 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5397 ferr(po, "unhandled division type\n");
5399 last_arith_dst = NULL;
5400 delayed_flag_op = NULL;
5405 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5407 for (j = 0; j < 8; j++) {
5408 if (pfomask & (1 << j)) {
5409 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
5410 fprintf(fout, " cond_%s = %s;",
5411 parsed_flag_op_names[j], buf1);
5418 last_arith_dst = NULL;
5419 delayed_flag_op = po;
5423 // SETcc - should already be handled
5426 // note: we reuse OP_Jcc for SETcc, only flags differ
5428 fprintf(fout, "\n goto %s;", po->operand[0].name);
5432 fprintf(fout, " if (ecx == 0)\n");
5433 fprintf(fout, " goto %s;", po->operand[0].name);
5434 strcat(g_comment, "jecxz");
5438 fprintf(fout, " if (--ecx == 0)\n");
5439 fprintf(fout, " goto %s;", po->operand[0].name);
5440 strcat(g_comment, "loop");
5444 assert_operand_cnt(1);
5445 last_arith_dst = NULL;
5446 delayed_flag_op = NULL;
5448 if (po->operand[0].type == OPT_REGMEM) {
5449 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
5452 ferr(po, "parse failure for jmp '%s'\n",
5453 po->operand[0].name);
5454 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
5457 else if (po->operand[0].type != OPT_LABEL)
5458 ferr(po, "unhandled jmp type\n");
5460 fprintf(fout, " goto %s;", po->operand[0].name);
5464 assert_operand_cnt(1);
5466 my_assert_not(pp, NULL);
5469 if (po->flags & OPF_CC) {
5470 // we treat conditional branch to another func
5471 // (yes such code exists..) as conditional tailcall
5473 fprintf(fout, " {\n");
5476 if (pp->is_fptr && !pp->is_arg) {
5477 fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
5478 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
5480 if (pp->is_unresolved)
5481 fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
5482 buf3, asmfn, po->asmln, pp->name);
5485 fprintf(fout, "%s", buf3);
5486 if (strstr(pp->ret_type.name, "int64")) {
5487 if (po->flags & OPF_TAIL)
5488 ferr(po, "int64 and tail?\n");
5489 fprintf(fout, "tmp64 = ");
5491 else if (!IS(pp->ret_type.name, "void")) {
5492 if (po->flags & OPF_TAIL) {
5493 if (!IS(g_func_pp->ret_type.name, "void")) {
5494 fprintf(fout, "return ");
5495 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
5496 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
5499 else if (regmask & (1 << xAX)) {
5500 fprintf(fout, "eax = ");
5501 if (pp->ret_type.is_ptr)
5502 fprintf(fout, "(u32)");
5506 if (pp->name[0] == 0)
5507 ferr(po, "missing pp->name\n");
5508 fprintf(fout, "%s%s(", pp->name,
5509 pp->has_structarg ? "_sa" : "");
5511 if (po->flags & OPF_ATAIL) {
5512 if (pp->argc_stack != g_func_pp->argc_stack
5513 || (pp->argc_stack > 0
5514 && pp->is_stdcall != g_func_pp->is_stdcall))
5515 ferr(po, "incompatible tailcall\n");
5516 if (g_func_pp->has_retreg)
5517 ferr(po, "TODO: retreg+tailcall\n");
5519 for (arg = j = 0; arg < pp->argc; arg++) {
5521 fprintf(fout, ", ");
5524 if (pp->arg[arg].type.is_ptr)
5525 snprintf(cast, sizeof(cast), "(%s)",
5526 pp->arg[arg].type.name);
5528 if (pp->arg[arg].reg != NULL) {
5529 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5533 for (; j < g_func_pp->argc; j++)
5534 if (g_func_pp->arg[j].reg == NULL)
5536 fprintf(fout, "%sa%d", cast, j + 1);
5541 for (arg = 0; arg < pp->argc; arg++) {
5543 fprintf(fout, ", ");
5546 if (pp->arg[arg].type.is_ptr)
5547 snprintf(cast, sizeof(cast), "(%s)",
5548 pp->arg[arg].type.name);
5550 if (pp->arg[arg].reg != NULL) {
5551 if (pp->arg[arg].type.is_retreg)
5552 fprintf(fout, "&%s", pp->arg[arg].reg);
5554 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5559 tmp_op = pp->arg[arg].datap;
5561 ferr(po, "parsed_op missing for arg%d\n", arg);
5563 if (tmp_op->flags & OPF_VAPUSH) {
5564 fprintf(fout, "ap");
5566 else if (tmp_op->p_argpass != 0) {
5567 fprintf(fout, "a%d", tmp_op->p_argpass);
5569 else if (tmp_op->p_argnum != 0) {
5570 fprintf(fout, "%s%s", cast,
5571 saved_arg_name(buf1, sizeof(buf1),
5572 tmp_op->p_arggrp, tmp_op->p_argnum));
5576 out_src_opr(buf1, sizeof(buf1),
5577 tmp_op, &tmp_op->operand[0], cast, 0));
5581 fprintf(fout, ");");
5583 if (strstr(pp->ret_type.name, "int64")) {
5584 fprintf(fout, "\n");
5585 fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
5586 fprintf(fout, "%seax = tmp64;", buf3);
5589 if (pp->is_unresolved) {
5590 snprintf(buf2, sizeof(buf2), " unresolved %dreg",
5592 strcat(g_comment, buf2);
5595 if (po->flags & OPF_TAIL) {
5597 if (i == opcnt - 1 || pp->is_noreturn)
5599 else if (IS(pp->ret_type.name, "void"))
5601 else if (IS(g_func_pp->ret_type.name, "void"))
5603 // else already handled as 'return f()'
5606 if (!IS(g_func_pp->ret_type.name, "void")) {
5607 ferr(po, "int func -> void func tailcall?\n");
5610 fprintf(fout, "\n%sreturn;", buf3);
5611 strcat(g_comment, " ^ tailcall");
5615 strcat(g_comment, " tailcall");
5617 if (pp->is_noreturn)
5618 strcat(g_comment, " noreturn");
5619 if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
5620 strcat(g_comment, " argframe");
5621 if (po->flags & OPF_CC)
5622 strcat(g_comment, " cond");
5624 if (po->flags & OPF_CC)
5625 fprintf(fout, "\n }");
5627 delayed_flag_op = NULL;
5628 last_arith_dst = NULL;
5632 if (g_func_pp->is_vararg)
5633 fprintf(fout, " va_end(ap);\n");
5634 if (g_func_pp->has_retreg) {
5635 for (arg = 0; arg < g_func_pp->argc; arg++)
5636 if (g_func_pp->arg[arg].type.is_retreg)
5637 fprintf(fout, " *r_%s = %s;\n",
5638 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
5641 if (IS(g_func_pp->ret_type.name, "void")) {
5642 if (i != opcnt - 1 || label_pending)
5643 fprintf(fout, " return;");
5645 else if (g_func_pp->ret_type.is_ptr) {
5646 fprintf(fout, " return (%s)eax;",
5647 g_func_pp->ret_type.name);
5649 else if (IS(g_func_pp->ret_type.name, "__int64"))
5650 fprintf(fout, " return ((u64)edx << 32) | eax;");
5652 fprintf(fout, " return eax;");
5654 last_arith_dst = NULL;
5655 delayed_flag_op = NULL;
5659 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5660 if (po->p_argnum != 0) {
5661 // special case - saved func arg
5662 fprintf(fout, " %s = %s;",
5663 saved_arg_name(buf2, sizeof(buf2),
5664 po->p_arggrp, po->p_argnum), buf1);
5667 else if (po->flags & OPF_RSAVE) {
5668 fprintf(fout, " s_%s = %s;", buf1, buf1);
5671 else if (po->flags & OPF_PPUSH) {
5673 ferr_assert(po, tmp_op != NULL);
5674 out_dst_opr(buf2, sizeof(buf2), po, &tmp_op->operand[0]);
5675 fprintf(fout, " pp_%s = %s;", buf2, buf1);
5678 else if (g_func_pp->is_userstack) {
5679 fprintf(fout, " *(--esp) = %s;", buf1);
5682 if (!(g_ida_func_attr & IDAFA_NORETURN))
5683 ferr(po, "stray push encountered\n");
5688 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5689 if (po->flags & OPF_RSAVE) {
5690 fprintf(fout, " %s = s_%s;", buf1, buf1);
5693 else if (po->flags & OPF_PPUSH) {
5695 ferr_assert(po, po->datap == NULL);
5696 fprintf(fout, " %s = pp_%s;", buf1, buf1);
5699 else if (po->datap != NULL) {
5702 fprintf(fout, " %s = %s;", buf1,
5703 out_src_opr(buf2, sizeof(buf2),
5704 tmp_op, &tmp_op->operand[0],
5705 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5708 else if (g_func_pp->is_userstack) {
5709 fprintf(fout, " %s = *esp++;", buf1);
5713 ferr(po, "stray pop encountered\n");
5722 strcpy(g_comment, "(emms)");
5727 ferr(po, "unhandled op type %d, flags %x\n",
5732 if (g_comment[0] != 0) {
5733 char *p = g_comment;
5734 while (my_isblank(*p))
5736 fprintf(fout, " // %s", p);
5741 fprintf(fout, "\n");
5743 // some sanity checking
5744 if (po->flags & OPF_REP) {
5745 if (po->op != OP_STOS && po->op != OP_MOVS
5746 && po->op != OP_CMPS && po->op != OP_SCAS)
5747 ferr(po, "unexpected rep\n");
5748 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
5749 && (po->op == OP_CMPS || po->op == OP_SCAS))
5750 ferr(po, "cmps/scas with plain rep\n");
5752 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
5753 && po->op != OP_CMPS && po->op != OP_SCAS)
5754 ferr(po, "unexpected repz/repnz\n");
5757 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
5759 // see is delayed flag stuff is still valid
5760 if (delayed_flag_op != NULL && delayed_flag_op != po) {
5761 if (is_any_opr_modified(delayed_flag_op, po, 0))
5762 delayed_flag_op = NULL;
5765 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
5766 if (is_opr_modified(last_arith_dst, po))
5767 last_arith_dst = NULL;
5773 if (g_stack_fsz && !g_stack_frame_used)
5774 fprintf(fout, " (void)sf;\n");
5776 fprintf(fout, "}\n\n");
5778 gen_x_cleanup(opcnt);
5781 static void gen_x_cleanup(int opcnt)
5785 for (i = 0; i < opcnt; i++) {
5786 struct label_ref *lr, *lr_del;
5788 lr = g_label_refs[i].next;
5789 while (lr != NULL) {
5794 g_label_refs[i].i = -1;
5795 g_label_refs[i].next = NULL;
5797 if (ops[i].op == OP_CALL) {
5799 proto_release(ops[i].pp);
5805 struct func_proto_dep;
5807 struct func_prototype {
5812 int has_ret:3; // -1, 0, 1: unresolved, no, yes
5813 unsigned int dep_resolved:1;
5814 unsigned int is_stdcall:1;
5815 struct func_proto_dep *dep_func;
5817 const struct parsed_proto *pp; // seed pp, if any
5820 struct func_proto_dep {
5822 struct func_prototype *proto;
5823 int regmask_live; // .. at the time of call
5824 unsigned int ret_dep:1; // return from this is caller's return
5827 static struct func_prototype *hg_fp;
5828 static int hg_fp_cnt;
5830 static struct scanned_var {
5832 enum opr_lenmod lmod;
5833 unsigned int is_seeded:1;
5834 unsigned int is_c_str:1;
5835 const struct parsed_proto *pp; // seed pp, if any
5837 static int hg_var_cnt;
5839 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
5842 struct func_prototype *hg_fp_add(const char *funcn)
5844 struct func_prototype *fp;
5846 if ((hg_fp_cnt & 0xff) == 0) {
5847 hg_fp = realloc(hg_fp, sizeof(hg_fp[0]) * (hg_fp_cnt + 0x100));
5848 my_assert_not(hg_fp, NULL);
5849 memset(hg_fp + hg_fp_cnt, 0, sizeof(hg_fp[0]) * 0x100);
5852 fp = &hg_fp[hg_fp_cnt];
5853 snprintf(fp->name, sizeof(fp->name), "%s", funcn);
5855 fp->argc_stack = -1;
5861 static struct func_proto_dep *hg_fp_find_dep(struct func_prototype *fp,
5866 for (i = 0; i < fp->dep_func_cnt; i++)
5867 if (IS(fp->dep_func[i].name, name))
5868 return &fp->dep_func[i];
5873 static void hg_fp_add_dep(struct func_prototype *fp, const char *name)
5876 if (hg_fp_find_dep(fp, name))
5879 if ((fp->dep_func_cnt & 0xff) == 0) {
5880 fp->dep_func = realloc(fp->dep_func,
5881 sizeof(fp->dep_func[0]) * (fp->dep_func_cnt + 0x100));
5882 my_assert_not(fp->dep_func, NULL);
5883 memset(&fp->dep_func[fp->dep_func_cnt], 0,
5884 sizeof(fp->dep_func[0]) * 0x100);
5886 fp->dep_func[fp->dep_func_cnt].name = strdup(name);
5890 static int hg_fp_cmp_name(const void *p1_, const void *p2_)
5892 const struct func_prototype *p1 = p1_, *p2 = p2_;
5893 return strcmp(p1->name, p2->name);
5897 static int hg_fp_cmp_id(const void *p1_, const void *p2_)
5899 const struct func_prototype *p1 = p1_, *p2 = p2_;
5900 return p1->id - p2->id;
5904 // recursive register dep pass
5905 // - track saved regs (part 2)
5906 // - try to figure out arg-regs
5907 // - calculate reg deps
5908 static void gen_hdr_dep_pass(int i, int opcnt, unsigned char *cbits,
5909 struct func_prototype *fp, int regmask_save, int regmask_dst,
5910 int *regmask_dep, int *has_ret)
5912 struct func_proto_dep *dep;
5913 struct parsed_op *po;
5914 int from_caller = 0;
5920 for (; i < opcnt; i++)
5922 if (cbits[i >> 3] & (1 << (i & 7)))
5924 cbits[i >> 3] |= (1 << (i & 7));
5928 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
5929 if (po->flags & OPF_RMD)
5932 if (po->btj != NULL) {
5934 for (j = 0; j < po->btj->count; j++) {
5935 check_i(po, po->btj->d[j].bt_i);
5936 gen_hdr_dep_pass(po->btj->d[j].bt_i, opcnt, cbits, fp,
5937 regmask_save, regmask_dst, regmask_dep, has_ret);
5942 check_i(po, po->bt_i);
5943 if (po->flags & OPF_CJMP) {
5944 gen_hdr_dep_pass(po->bt_i, opcnt, cbits, fp,
5945 regmask_save, regmask_dst, regmask_dep, has_ret);
5953 if (po->flags & OPF_FARG)
5954 /* (just calculate register deps) */;
5955 else if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
5957 reg = po->operand[0].reg;
5959 ferr(po, "reg not set for push?\n");
5961 if (po->flags & OPF_RSAVE) {
5962 regmask_save |= 1 << reg;
5965 if (po->flags & OPF_DONE)
5969 ret = scan_for_pop(i + 1, opcnt,
5970 po->operand[0].name, i + opcnt * 2, 0, &depth, 0);
5972 regmask_save |= 1 << reg;
5973 po->flags |= OPF_RMD;
5974 scan_for_pop(i + 1, opcnt,
5975 po->operand[0].name, i + opcnt * 3, 0, &depth, 1);
5979 else if (po->flags & OPF_RMD)
5981 else if (po->op == OP_CALL) {
5982 po->regmask_dst |= 1 << xAX;
5984 dep = hg_fp_find_dep(fp, po->operand[0].name);
5986 dep->regmask_live = regmask_save | regmask_dst;
5988 else if (po->op == OP_RET) {
5989 if (po->operand_cnt > 0) {
5991 if (fp->argc_stack >= 0
5992 && fp->argc_stack != po->operand[0].val / 4)
5993 ferr(po, "ret mismatch? (%d)\n", fp->argc_stack * 4);
5994 fp->argc_stack = po->operand[0].val / 4;
5998 // if has_ret is 0, there is uninitialized eax path,
5999 // which means it's most likely void func
6000 if (*has_ret != 0 && (po->flags & OPF_TAIL)) {
6001 if (po->op == OP_CALL) {
6006 struct parsed_opr opr = { 0, };
6011 ret = resolve_origin(i, &opr, i + opcnt * 4, &j, &from_caller);
6014 if (ret != 1 && from_caller) {
6015 // unresolved eax - probably void func
6019 if (j >= 0 && ops[j].op == OP_CALL) {
6020 dep = hg_fp_find_dep(fp, ops[j].operand[0].name);
6031 l = regmask_save | regmask_dst;
6032 if (g_bp_frame && !(po->flags & OPF_EBP_S))
6035 l = po->regmask_src & ~l;
6038 fnote(po, "dep |= %04x, dst %04x, save %04x (f %x)\n",
6039 l, regmask_dst, regmask_save, po->flags);
6042 regmask_dst |= po->regmask_dst;
6044 if (po->flags & OPF_TAIL)
6049 static void gen_hdr(const char *funcn, int opcnt)
6051 int save_arg_vars[MAX_ARG_GRP] = { 0, };
6052 unsigned char cbits[MAX_OPS / 8];
6053 const struct parsed_proto *pp_c;
6054 struct parsed_proto *pp;
6055 struct func_prototype *fp;
6056 struct parsed_op *po;
6057 int regmask_dummy = 0;
6059 int max_bp_offset = 0;
6064 pp_c = proto_parse(g_fhdr, funcn, 1);
6066 // already in seed, will add to hg_fp later
6069 fp = hg_fp_add(funcn);
6071 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
6072 g_stack_frame_used = 0;
6075 // - resolve all branches
6076 // - parse calls with labels
6077 resolve_branches_parse_calls(opcnt);
6080 // - handle ebp/esp frame, remove ops related to it
6081 scan_prologue_epilogue(opcnt);
6084 // - remove dead labels
6086 for (i = 0; i < opcnt; i++)
6088 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
6094 if (po->flags & (OPF_RMD|OPF_DONE))
6097 if (po->op == OP_CALL) {
6098 if (po->operand[0].type == OPT_LABEL)
6099 hg_fp_add_dep(fp, opr_name(po, 0));
6100 else if (po->pp != NULL)
6101 hg_fp_add_dep(fp, po->pp->name);
6106 // - remove dead labels
6107 // - handle push <const>/pop pairs
6108 for (i = 0; i < opcnt; i++)
6110 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
6116 if (po->flags & (OPF_RMD|OPF_DONE))
6119 if (po->op == OP_PUSH && po->operand[0].type == OPT_CONST)
6120 scan_for_pop_const(i, opcnt, ®mask_dummy);
6124 // - process trivial calls
6125 for (i = 0; i < opcnt; i++)
6128 if (po->flags & (OPF_RMD|OPF_DONE))
6131 if (po->op == OP_CALL)
6133 pp = process_call_early(i, opcnt, &j);
6135 if (!(po->flags & OPF_ATAIL))
6136 // since we know the args, try to collect them
6137 if (collect_call_args_early(po, i, pp, ®mask_dummy) != 0)
6143 // commit esp adjust
6144 if (ops[j].op != OP_POP)
6145 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
6147 for (l = 0; l < pp->argc_stack; l++)
6148 ops[j + l].flags |= OPF_DONE | OPF_RMD;
6152 po->flags |= OPF_DONE;
6158 // - track saved regs (simple)
6160 for (i = 0; i < opcnt; i++)
6163 if (po->flags & (OPF_RMD|OPF_DONE))
6166 if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
6168 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
6170 // regmask_save |= 1 << po->operand[0].reg; // do it later
6171 po->flags |= OPF_RSAVE | OPF_RMD | OPF_DONE;
6172 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, OPF_RMD);
6175 else if (po->op == OP_CALL && !(po->flags & OPF_DONE))
6177 pp = process_call(i, opcnt);
6179 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
6180 // since we know the args, collect them
6181 ret = collect_call_args(po, i, pp, ®mask_dummy, save_arg_vars,
6188 memset(cbits, 0, sizeof(cbits));
6192 gen_hdr_dep_pass(0, opcnt, cbits, fp, 0, 0, ®mask_dep, &has_ret);
6194 // find unreachable code - must be fixed in IDA
6195 for (i = 0; i < opcnt; i++)
6197 if (cbits[i >> 3] & (1 << (i & 7)))
6200 if (g_labels[i] == NULL && i > 0 && ops[i - 1].op == OP_CALL
6201 && ops[i - 1].pp != NULL && ops[i - 1].pp->is_osinc)
6203 // the compiler sometimes still generates code after
6204 // noreturn OS functions
6207 if (ops[i].op != OP_NOP)
6208 ferr(&ops[i], "unreachable code\n");
6211 for (i = 0; i < g_eqcnt; i++) {
6212 if (g_eqs[i].offset > max_bp_offset && g_eqs[i].offset < 4*32)
6213 max_bp_offset = g_eqs[i].offset;
6216 if (fp->argc_stack < 0) {
6217 max_bp_offset = (max_bp_offset + 3) & ~3;
6218 fp->argc_stack = max_bp_offset / 4;
6219 if ((g_ida_func_attr & IDAFA_BP_FRAME) && fp->argc_stack > 0)
6223 fp->regmask_dep = regmask_dep & ~(1 << xSP);
6224 fp->has_ret = has_ret;
6226 printf("// has_ret %d, regmask_dep %x\n",
6227 fp->has_ret, fp->regmask_dep);
6228 output_hdr_fp(stdout, fp, 1);
6229 if (IS(funcn, "sub_10007F72")) exit(1);
6232 gen_x_cleanup(opcnt);
6235 static void hg_fp_resolve_deps(struct func_prototype *fp)
6237 struct func_prototype fp_s;
6241 // this thing is recursive, so mark first..
6242 fp->dep_resolved = 1;
6244 for (i = 0; i < fp->dep_func_cnt; i++) {
6245 strcpy(fp_s.name, fp->dep_func[i].name);
6246 fp->dep_func[i].proto = bsearch(&fp_s, hg_fp, hg_fp_cnt,
6247 sizeof(hg_fp[0]), hg_fp_cmp_name);
6248 if (fp->dep_func[i].proto != NULL) {
6249 if (!fp->dep_func[i].proto->dep_resolved)
6250 hg_fp_resolve_deps(fp->dep_func[i].proto);
6252 dep = ~fp->dep_func[i].regmask_live
6253 & fp->dep_func[i].proto->regmask_dep;
6254 fp->regmask_dep |= dep;
6255 // printf("dep %s %s |= %x\n", fp->name,
6256 // fp->dep_func[i].name, dep);
6258 if (fp->has_ret == -1 && fp->dep_func[i].ret_dep)
6259 fp->has_ret = fp->dep_func[i].proto->has_ret;
6264 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
6267 const struct parsed_proto *pp;
6268 char *p, namebuf[NAMELEN];
6274 for (; count > 0; count--, fp++) {
6275 if (fp->has_ret == -1)
6276 fprintf(fout, "// ret unresolved\n");
6278 fprintf(fout, "// dep:");
6279 for (j = 0; j < fp->dep_func_cnt; j++) {
6280 fprintf(fout, " %s/", fp->dep_func[j].name);
6281 if (fp->dep_func[j].proto != NULL)
6282 fprintf(fout, "%04x/%d", fp->dep_func[j].proto->regmask_dep,
6283 fp->dep_func[j].proto->has_ret);
6285 fprintf(fout, "\n");
6288 p = strchr(fp->name, '@');
6290 memcpy(namebuf, fp->name, p - fp->name);
6291 namebuf[p - fp->name] = 0;
6299 pp = proto_parse(g_fhdr, name, 1);
6300 if (pp != NULL && pp->is_include)
6303 if (fp->pp != NULL) {
6304 // part of seed, output later
6308 regmask_dep = fp->regmask_dep;
6309 argc_stack = fp->argc_stack;
6311 fprintf(fout, "%-5s", fp->pp ? fp->pp->ret_type.name :
6312 (fp->has_ret ? "int" : "void"));
6313 if (regmask_dep && (fp->is_stdcall || argc_stack == 0)
6314 && (regmask_dep & ~((1 << xCX) | (1 << xDX))) == 0)
6316 fprintf(fout, " __fastcall ");
6317 if (!(regmask_dep & (1 << xDX)) && argc_stack == 0)
6323 else if (regmask_dep && !fp->is_stdcall) {
6324 fprintf(fout, "/*__usercall*/ ");
6326 else if (regmask_dep) {
6327 fprintf(fout, "/*__userpurge*/ ");
6329 else if (fp->is_stdcall)
6330 fprintf(fout, " __stdcall ");
6332 fprintf(fout, " __cdecl ");
6334 fprintf(fout, "%s(", name);
6337 for (j = 0; j < xSP; j++) {
6338 if (regmask_dep & (1 << j)) {
6341 fprintf(fout, ", ");
6343 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6345 fprintf(fout, "int");
6346 fprintf(fout, " a%d/*<%s>*/", arg, regs_r32[j]);
6350 for (j = 0; j < argc_stack; j++) {
6353 fprintf(fout, ", ");
6354 if (fp->pp != NULL) {
6355 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6356 if (!fp->pp->arg[arg - 1].type.is_ptr)
6360 fprintf(fout, "int ");
6361 fprintf(fout, "a%d", arg);
6364 fprintf(fout, ");\n");
6368 static void output_hdr(FILE *fout)
6370 static const char *lmod_c_names[] = {
6371 [OPLM_UNSPEC] = "???",
6372 [OPLM_BYTE] = "uint8_t",
6373 [OPLM_WORD] = "uint16_t",
6374 [OPLM_DWORD] = "uint32_t",
6375 [OPLM_QWORD] = "uint64_t",
6377 const struct scanned_var *var;
6378 struct func_prototype *fp;
6379 char line[256] = { 0, };
6383 // add stuff from headers
6384 for (i = 0; i < pp_cache_size; i++) {
6385 if (pp_cache[i].is_cinc && !pp_cache[i].is_stdcall)
6386 snprintf(name, sizeof(name), "_%s", pp_cache[i].name);
6388 snprintf(name, sizeof(name), "%s", pp_cache[i].name);
6389 fp = hg_fp_add(name);
6390 fp->pp = &pp_cache[i];
6391 fp->argc_stack = fp->pp->argc_stack;
6392 fp->is_stdcall = fp->pp->is_stdcall;
6393 fp->regmask_dep = get_pp_arg_regmask(fp->pp);
6394 fp->has_ret = !IS(fp->pp->ret_type.name, "void");
6398 qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_name);
6399 for (i = 0; i < hg_fp_cnt; i++)
6400 hg_fp_resolve_deps(&hg_fp[i]);
6402 // note: messes up .proto ptr, don't use
6403 //qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_id);
6406 for (i = 0; i < hg_var_cnt; i++) {
6409 if (var->pp != NULL)
6412 else if (var->is_c_str)
6413 fprintf(fout, "extern %-8s %s[];", "char", var->name);
6415 fprintf(fout, "extern %-8s %s;",
6416 lmod_c_names[var->lmod], var->name);
6419 fprintf(fout, " // seeded");
6420 fprintf(fout, "\n");
6423 fprintf(fout, "\n");
6425 // output function prototypes
6426 output_hdr_fp(fout, hg_fp, hg_fp_cnt);
6429 fprintf(fout, "\n// - seed -\n");
6432 while (fgets(line, sizeof(line), g_fhdr))
6433 fwrite(line, 1, strlen(line), fout);
6436 // '=' needs special treatment
6438 static char *next_word_s(char *w, size_t wsize, char *s)
6447 for (i = 1; i < wsize - 1; i++) {
6449 printf("warning: missing closing quote: \"%s\"\n", s);
6458 for (; i < wsize - 1; i++) {
6459 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
6465 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
6466 printf("warning: '%s' truncated\n", w);
6471 static void scan_variables(FILE *fasm)
6473 struct scanned_var *var;
6474 char line[256] = { 0, };
6482 // skip to next data section
6483 while (my_fgets(line, sizeof(line), fasm))
6488 if (*p == 0 || *p == ';')
6491 p = sskip(next_word_s(words[0], sizeof(words[0]), p));
6492 if (*p == 0 || *p == ';')
6495 if (*p != 's' || !IS_START(p, "segment para public"))
6501 if (p == NULL || !IS_START(p, "segment para public"))
6505 if (!IS_START(p, "'DATA'"))
6509 while (my_fgets(line, sizeof(line), fasm))
6518 if (*p == 0 || *p == ';')
6521 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6522 words[wordc][0] = 0;
6523 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6524 if (*p == 0 || *p == ';') {
6530 if (wordc == 2 && IS(words[1], "ends"))
6535 if (IS_START(words[0], "__IMPORT_DESCRIPTOR_")) {
6536 // when this starts, we don't need anything from this section
6540 if ((hg_var_cnt & 0xff) == 0) {
6541 hg_vars = realloc(hg_vars, sizeof(hg_vars[0])
6542 * (hg_var_cnt + 0x100));
6543 my_assert_not(hg_vars, NULL);
6544 memset(hg_vars + hg_var_cnt, 0, sizeof(hg_vars[0]) * 0x100);
6547 var = &hg_vars[hg_var_cnt++];
6548 snprintf(var->name, sizeof(var->name), "%s", words[0]);
6550 // maybe already in seed header?
6551 var->pp = proto_parse(g_fhdr, var->name, 1);
6552 if (var->pp != NULL) {
6553 if (var->pp->is_fptr) {
6554 var->lmod = OPLM_DWORD;
6557 else if (var->pp->is_func)
6559 else if (!guess_lmod_from_c_type(&var->lmod, &var->pp->type))
6560 aerr("unhandled C type '%s' for '%s'\n",
6561 var->pp->type.name, var->name);
6567 if (IS(words[1], "dd"))
6568 var->lmod = OPLM_DWORD;
6569 else if (IS(words[1], "dw"))
6570 var->lmod = OPLM_WORD;
6571 else if (IS(words[1], "db")) {
6572 var->lmod = OPLM_BYTE;
6573 if (wordc >= 3 && (l = strlen(words[2])) > 4) {
6574 if (words[2][0] == '\'' && IS(words[2] + l - 2, ",0"))
6578 else if (IS(words[1], "dq"))
6579 var->lmod = OPLM_QWORD;
6580 //else if (IS(words[1], "dt"))
6582 aerr("type '%s' not known\n", words[1]);
6590 static void set_label(int i, const char *name)
6596 p = strchr(name, ':');
6600 if (g_labels[i] != NULL && !IS_START(g_labels[i], "algn_"))
6601 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
6602 g_labels[i] = realloc(g_labels[i], len + 1);
6603 my_assert_not(g_labels[i], NULL);
6604 memcpy(g_labels[i], name, len);
6605 g_labels[i][len] = 0;
6614 static struct chunk_item *func_chunks;
6615 static int func_chunk_cnt;
6616 static int func_chunk_alloc;
6618 static void add_func_chunk(FILE *fasm, const char *name, int line)
6620 if (func_chunk_cnt >= func_chunk_alloc) {
6621 func_chunk_alloc *= 2;
6622 func_chunks = realloc(func_chunks,
6623 func_chunk_alloc * sizeof(func_chunks[0]));
6624 my_assert_not(func_chunks, NULL);
6626 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
6627 func_chunks[func_chunk_cnt].name = strdup(name);
6628 func_chunks[func_chunk_cnt].asmln = line;
6632 static int cmp_chunks(const void *p1, const void *p2)
6634 const struct chunk_item *c1 = p1, *c2 = p2;
6635 return strcmp(c1->name, c2->name);
6638 static int cmpstringp(const void *p1, const void *p2)
6640 return strcmp(*(char * const *)p1, *(char * const *)p2);
6643 static void scan_ahead(FILE *fasm)
6653 oldpos = ftell(fasm);
6656 while (my_fgets(line, sizeof(line), fasm))
6667 // get rid of random tabs
6668 for (i = 0; line[i] != 0; i++)
6669 if (line[i] == '\t')
6672 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6675 next_word(words[0], sizeof(words[0]), p);
6676 if (words[0][0] == 0)
6677 aerr("missing name for func chunk?\n");
6679 add_func_chunk(fasm, words[0], asmln);
6681 else if (IS_START(p, "; sctend"))
6687 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6688 words[wordc][0] = 0;
6689 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6690 if (*p == 0 || *p == ';') {
6696 if (wordc == 2 && IS(words[1], "ends"))
6700 fseek(fasm, oldpos, SEEK_SET);
6704 int main(int argc, char *argv[])
6706 FILE *fout, *fasm, *frlist;
6707 struct parsed_data *pd = NULL;
6709 char **rlist = NULL;
6711 int rlist_alloc = 0;
6712 int func_chunks_used = 0;
6713 int func_chunks_sorted = 0;
6714 int func_chunk_i = -1;
6715 long func_chunk_ret = 0;
6716 int func_chunk_ret_ln = 0;
6717 int scanned_ahead = 0;
6719 char words[20][256];
6720 enum opr_lenmod lmod;
6721 char *sctproto = NULL;
6723 int pending_endp = 0;
6725 int skip_warned = 0;
6738 for (arg = 1; arg < argc; arg++) {
6739 if (IS(argv[arg], "-v"))
6741 else if (IS(argv[arg], "-rf"))
6742 g_allow_regfunc = 1;
6743 else if (IS(argv[arg], "-m"))
6745 else if (IS(argv[arg], "-hdr"))
6746 g_header_mode = g_quiet_pp = g_allow_regfunc = 1;
6751 if (argc < arg + 3) {
6752 printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdr.h> [rlist]*\n"
6753 "%s -hdr <out.h> <.asm> <seed.h> [rlist]*\n"
6755 " -hdr - header generation mode\n"
6756 " -rf - allow unannotated indirect calls\n"
6757 " -m - allow multiple .text sections\n"
6758 "[rlist] is a file with function names to skip,"
6766 asmfn = argv[arg++];
6767 fasm = fopen(asmfn, "r");
6768 my_assert_not(fasm, NULL);
6770 hdrfn = argv[arg++];
6771 g_fhdr = fopen(hdrfn, "r");
6772 my_assert_not(g_fhdr, NULL);
6775 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
6776 my_assert_not(rlist, NULL);
6777 // needs special handling..
6778 rlist[rlist_len++] = "__alloca_probe";
6780 func_chunk_alloc = 32;
6781 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
6782 my_assert_not(func_chunks, NULL);
6784 memset(words, 0, sizeof(words));
6786 for (; arg < argc; arg++) {
6787 frlist = fopen(argv[arg], "r");
6788 my_assert_not(frlist, NULL);
6790 while (my_fgets(line, sizeof(line), frlist)) {
6792 if (*p == 0 || *p == ';')
6795 if (IS_START(p, "#if 0")
6796 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
6800 else if (IS_START(p, "#endif"))
6807 p = next_word(words[0], sizeof(words[0]), p);
6808 if (words[0][0] == 0)
6811 if (rlist_len >= rlist_alloc) {
6812 rlist_alloc = rlist_alloc * 2 + 64;
6813 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
6814 my_assert_not(rlist, NULL);
6816 rlist[rlist_len++] = strdup(words[0]);
6825 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
6827 fout = fopen(argv[arg_out], "w");
6828 my_assert_not(fout, NULL);
6831 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
6832 my_assert_not(g_eqs, NULL);
6834 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
6835 g_label_refs[i].i = -1;
6836 g_label_refs[i].next = NULL;
6840 scan_variables(fasm);
6842 while (my_fgets(line, sizeof(line), fasm))
6851 // get rid of random tabs
6852 for (i = 0; line[i] != 0; i++)
6853 if (line[i] == '\t')
6858 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
6859 goto do_pending_endp; // eww..
6861 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
6863 static const char *attrs[] = {
6872 // parse IDA's attribute-list comment
6873 g_ida_func_attr = 0;
6876 for (; *p != 0; p = sskip(p)) {
6877 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
6878 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
6879 g_ida_func_attr |= 1 << i;
6880 p += strlen(attrs[i]);
6884 if (i == ARRAY_SIZE(attrs)) {
6885 anote("unparsed IDA attr: %s\n", p);
6888 if (IS(attrs[i], "fpd=")) {
6889 p = next_word(words[0], sizeof(words[0]), p);
6894 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6897 next_word(words[0], sizeof(words[0]), p);
6898 if (words[0][0] == 0)
6899 aerr("missing name for func chunk?\n");
6901 if (!scanned_ahead) {
6902 add_func_chunk(fasm, words[0], asmln);
6903 func_chunks_sorted = 0;
6906 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
6908 if (func_chunk_i >= 0) {
6909 if (func_chunk_i < func_chunk_cnt
6910 && IS(func_chunks[func_chunk_i].name, g_func))
6912 // move on to next chunk
6913 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
6915 aerr("seek failed for '%s' chunk #%d\n",
6916 g_func, func_chunk_i);
6917 asmln = func_chunks[func_chunk_i].asmln;
6921 if (func_chunk_ret == 0)
6922 aerr("no return from chunk?\n");
6923 fseek(fasm, func_chunk_ret, SEEK_SET);
6924 asmln = func_chunk_ret_ln;
6930 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
6931 func_chunks_used = 1;
6933 if (IS_START(g_func, "sub_")) {
6934 unsigned long addr = strtoul(p, NULL, 16);
6935 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
6936 if (addr > f_addr && !scanned_ahead) {
6937 anote("scan_ahead caused by '%s', addr %lx\n",
6941 func_chunks_sorted = 0;
6949 for (i = wordc; i < ARRAY_SIZE(words); i++)
6951 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6952 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6953 if (*p == 0 || *p == ';') {
6958 if (*p != 0 && *p != ';')
6959 aerr("too many words\n");
6961 // alow asm patches in comments
6963 if (IS_START(p, "; sctpatch:")) {
6965 if (*p == 0 || *p == ';')
6967 goto parse_words; // lame
6969 if (IS_START(p, "; sctproto:")) {
6970 sctproto = strdup(p + 11);
6972 else if (IS_START(p, "; sctend")) {
6981 awarn("wordc == 0?\n");
6985 // don't care about this:
6986 if (words[0][0] == '.'
6987 || IS(words[0], "include")
6988 || IS(words[0], "assume") || IS(words[1], "segment")
6989 || IS(words[0], "align"))
6995 // do delayed endp processing to collect switch jumptables
6997 if (in_func && !g_skip_func && !end && wordc >= 2
6998 && ((words[0][0] == 'd' && words[0][2] == 0)
6999 || (words[1][0] == 'd' && words[1][2] == 0)))
7002 if (words[1][0] == 'd' && words[1][2] == 0) {
7004 if (g_func_pd_cnt >= pd_alloc) {
7005 pd_alloc = pd_alloc * 2 + 16;
7006 g_func_pd = realloc(g_func_pd,
7007 sizeof(g_func_pd[0]) * pd_alloc);
7008 my_assert_not(g_func_pd, NULL);
7010 pd = &g_func_pd[g_func_pd_cnt];
7012 memset(pd, 0, sizeof(*pd));
7013 strcpy(pd->label, words[0]);
7014 pd->type = OPT_CONST;
7015 pd->lmod = lmod_from_directive(words[1]);
7021 anote("skipping alignment byte?\n");
7024 lmod = lmod_from_directive(words[0]);
7025 if (lmod != pd->lmod)
7026 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
7029 if (pd->count_alloc < pd->count + wordc) {
7030 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
7031 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
7032 my_assert_not(pd->d, NULL);
7034 for (; i < wordc; i++) {
7035 if (IS(words[i], "offset")) {
7036 pd->type = OPT_OFFSET;
7039 p = strchr(words[i], ',');
7042 if (pd->type == OPT_OFFSET)
7043 pd->d[pd->count].u.label = strdup(words[i]);
7045 pd->d[pd->count].u.val = parse_number(words[i]);
7046 pd->d[pd->count].bt_i = -1;
7052 if (in_func && !g_skip_func) {
7054 gen_hdr(g_func, pi);
7056 gen_func(fout, g_fhdr, g_func, pi);
7061 g_ida_func_attr = 0;
7065 func_chunks_used = 0;
7068 memset(&ops, 0, pi * sizeof(ops[0]));
7073 for (i = 0; i < g_func_pd_cnt; i++) {
7075 if (pd->type == OPT_OFFSET) {
7076 for (j = 0; j < pd->count; j++)
7077 free(pd->d[j].u.label);
7091 if (IS(words[1], "proc")) {
7093 aerr("proc '%s' while in_func '%s'?\n",
7096 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
7098 strcpy(g_func, words[0]);
7099 set_label(0, words[0]);
7104 if (IS(words[1], "endp"))
7107 aerr("endp '%s' while not in_func?\n", words[0]);
7108 if (!IS(g_func, words[0]))
7109 aerr("endp '%s' while in_func '%s'?\n",
7112 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
7113 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
7119 if (!g_skip_func && func_chunks_used) {
7120 // start processing chunks
7121 struct chunk_item *ci, key = { g_func, 0 };
7123 func_chunk_ret = ftell(fasm);
7124 func_chunk_ret_ln = asmln;
7125 if (!func_chunks_sorted) {
7126 qsort(func_chunks, func_chunk_cnt,
7127 sizeof(func_chunks[0]), cmp_chunks);
7128 func_chunks_sorted = 1;
7130 ci = bsearch(&key, func_chunks, func_chunk_cnt,
7131 sizeof(func_chunks[0]), cmp_chunks);
7133 aerr("'%s' needs chunks, but none found\n", g_func);
7134 func_chunk_i = ci - func_chunks;
7135 for (; func_chunk_i > 0; func_chunk_i--)
7136 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
7139 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
7141 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
7142 asmln = func_chunks[func_chunk_i].asmln;
7150 if (wordc == 2 && IS(words[1], "ends")) {
7154 goto do_pending_endp;
7158 // scan for next text segment
7159 while (my_fgets(line, sizeof(line), fasm)) {
7162 if (*p == 0 || *p == ';')
7165 if (strstr(p, "segment para public 'CODE' use32"))
7172 p = strchr(words[0], ':');
7174 set_label(pi, words[0]);
7178 if (!in_func || g_skip_func) {
7179 if (!skip_warned && !g_skip_func && g_labels[pi] != NULL) {
7181 anote("skipping from '%s'\n", g_labels[pi]);
7185 g_labels[pi] = NULL;
7189 if (wordc > 1 && IS(words[1], "="))
7192 aerr("unhandled equ, wc=%d\n", wordc);
7193 if (g_eqcnt >= eq_alloc) {
7195 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
7196 my_assert_not(g_eqs, NULL);
7199 len = strlen(words[0]);
7200 if (len > sizeof(g_eqs[0].name) - 1)
7201 aerr("equ name too long: %d\n", len);
7202 strcpy(g_eqs[g_eqcnt].name, words[0]);
7204 if (!IS(words[3], "ptr"))
7205 aerr("unhandled equ\n");
7206 if (IS(words[2], "dword"))
7207 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
7208 else if (IS(words[2], "word"))
7209 g_eqs[g_eqcnt].lmod = OPLM_WORD;
7210 else if (IS(words[2], "byte"))
7211 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
7212 else if (IS(words[2], "qword"))
7213 g_eqs[g_eqcnt].lmod = OPLM_QWORD;
7215 aerr("bad lmod: '%s'\n", words[2]);
7217 g_eqs[g_eqcnt].offset = parse_number(words[4]);
7222 if (pi >= ARRAY_SIZE(ops))
7223 aerr("too many ops\n");
7225 parse_op(&ops[pi], words, wordc);
7227 if (sctproto != NULL) {
7228 if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
7229 ops[pi].datap = sctproto;
7245 // vim:ts=2:shiftwidth=2:expandtab