reg return, __userstack, repe fix, more..
[ia32rtools.git] / tools / translate.c
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6 #include "my_assert.h"
7 #include "my_str.h"
8
9 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
10 #define IS(w, y) !strcmp(w, y)
11 #define IS_START(w, y) !strncmp(w, y, strlen(y))
12
13 #include "protoparse.h"
14
15 static const char *asmfn;
16 static int asmln;
17 static FILE *g_fhdr;
18
19 #define anote(fmt, ...) \
20         printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
21 #define awarn(fmt, ...) \
22         printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
23 #define aerr(fmt, ...) do { \
24         printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
25   fcloseall(); \
26         exit(1); \
27 } while (0)
28
29 #include "masm_tools.h"
30
31 enum op_flags {
32   OPF_RMD    = (1 << 0), /* removed or optimized out */
33   OPF_DATA   = (1 << 1), /* data processing - writes to dst opr */
34   OPF_FLAGS  = (1 << 2), /* sets flags */
35   OPF_JMP    = (1 << 3), /* branch, call */
36   OPF_CJMP   = (1 << 4), /* cond. branch (cc or jecxz) */
37   OPF_CC     = (1 << 5), /* uses flags */
38   OPF_TAIL   = (1 << 6), /* ret or tail call */
39   OPF_RSAVE  = (1 << 7), /* push/pop is local reg save/load */
40   OPF_REP    = (1 << 8), /* prefixed by rep */
41   OPF_REPZ   = (1 << 9), /* rep is repe/repz */
42   OPF_REPNZ  = (1 << 10), /* rep is repne/repnz */
43   OPF_FARG   = (1 << 11), /* push collected as func arg (no reuse) */
44   OPF_EBP_S  = (1 << 12), /* ebp used as scratch here, not BP */
45   OPF_DF     = (1 << 13), /* DF flag set */
46   OPF_ATAIL  = (1 << 14), /* tail call with reused arg frame */
47   OPF_32BIT  = (1 << 15), /* 32bit division */
48   OPF_LOCK   = (1 << 16), /* op has lock prefix */
49 };
50
51 enum op_op {
52         OP_INVAL,
53         OP_NOP,
54         OP_PUSH,
55         OP_POP,
56         OP_LEAVE,
57         OP_MOV,
58         OP_LEA,
59         OP_MOVZX,
60         OP_MOVSX,
61         OP_XCHG,
62         OP_NOT,
63         OP_CDQ,
64         OP_STOS,
65         OP_MOVS,
66         OP_CMPS,
67         OP_SCAS,
68         OP_STD,
69         OP_CLD,
70         OP_RET,
71         OP_ADD,
72         OP_SUB,
73         OP_AND,
74         OP_OR,
75         OP_XOR,
76         OP_SHL,
77         OP_SHR,
78         OP_SAR,
79         OP_ROL,
80         OP_ROR,
81         OP_RCL,
82         OP_RCR,
83         OP_ADC,
84         OP_SBB,
85         OP_BSF,
86         OP_INC,
87         OP_DEC,
88         OP_NEG,
89         OP_MUL,
90         OP_IMUL,
91         OP_DIV,
92         OP_IDIV,
93         OP_TEST,
94         OP_CMP,
95         OP_CALL,
96         OP_JMP,
97         OP_JECXZ,
98         OP_JO,
99         OP_JNO,
100         OP_JC,
101         OP_JNC,
102         OP_JZ,
103         OP_JNZ,
104         OP_JBE,
105         OP_JA,
106         OP_JS,
107         OP_JNS,
108         OP_JP,
109         OP_JNP,
110         OP_JL,
111         OP_JGE,
112         OP_JLE,
113         OP_JG,
114 };
115
116 enum opr_type {
117   OPT_UNSPEC,
118   OPT_REG,
119   OPT_REGMEM,
120   OPT_LABEL,
121   OPT_OFFSET,
122   OPT_CONST,
123 };
124
125 // must be sorted (larger len must be further in enum)
126 enum opr_lenmod {
127         OPLM_UNSPEC,
128         OPLM_BYTE,
129         OPLM_WORD,
130         OPLM_DWORD,
131 };
132
133 #define MAX_OPERANDS 3
134
135 struct parsed_opr {
136   enum opr_type type;
137   enum opr_lenmod lmod;
138   unsigned int is_ptr:1;   // pointer in C
139   unsigned int is_array:1; // array in C
140   unsigned int type_from_var:1; // .. in header, sometimes wrong
141   unsigned int size_mismatch:1; // type override differs from C
142   unsigned int size_lt:1;  // type override is larger than C
143   unsigned int had_ds:1;   // had ds: prefix
144   int reg;
145   unsigned int val;
146   char name[256];
147 };
148
149 struct parsed_op {
150   enum op_op op;
151   struct parsed_opr operand[MAX_OPERANDS];
152   unsigned int flags;
153   int operand_cnt;
154   int regmask_src;        // all referensed regs
155   int regmask_dst;
156   int pfomask;            // flagop: parsed_flag_op that can't be delayed
157   int argnum;             // push: altered before call arg #
158   int cc_scratch;         // scratch storage during analysis
159   int bt_i;               // branch target for branches
160   struct parsed_data *btj;// branch targets for jumptables
161   void *datap;
162 };
163
164 // datap:
165 // OP_CALL - parser proto hint (str), ptr to struct parsed_proto
166 // (OPF_CC) - point to one of (OPF_FLAGS) that affects cc op
167 // OP_POP - point to OP_PUSH in push/pop pair
168
169 struct parsed_equ {
170   char name[64];
171   enum opr_lenmod lmod;
172   int offset;
173 };
174
175 struct parsed_data {
176   char label[256];
177   enum opr_type type;
178   enum opr_lenmod lmod;
179   int count;
180   int count_alloc;
181   struct {
182     union {
183       char *label;
184       unsigned int val;
185     } u;
186     int bt_i;
187   } *d;
188 };
189
190 struct label_ref {
191   int i;
192   struct label_ref *next;
193 };
194
195 enum ida_func_attr {
196   IDAFA_BP_FRAME = (1 << 0),
197   IDAFA_LIB_FUNC = (1 << 1),
198   IDAFA_STATIC   = (1 << 2),
199   IDAFA_NORETURN = (1 << 3),
200   IDAFA_THUNK    = (1 << 4),
201   IDAFA_FPD      = (1 << 5),
202 };
203
204 #define MAX_OPS 4096
205
206 static struct parsed_op ops[MAX_OPS];
207 static struct parsed_equ *g_eqs;
208 static int g_eqcnt;
209 static char g_labels[MAX_OPS][48];
210 static struct label_ref g_label_refs[MAX_OPS];
211 static const struct parsed_proto *g_func_pp;
212 static struct parsed_data *g_func_pd;
213 static int g_func_pd_cnt;
214 static char g_func[256];
215 static char g_comment[256];
216 static int g_bp_frame;
217 static int g_sp_frame;
218 static int g_stack_frame_used;
219 static int g_stack_fsz;
220 static int g_ida_func_attr;
221 static int g_allow_regfunc;
222 #define ferr(op_, fmt, ...) do { \
223   printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
224     dump_op(op_), ##__VA_ARGS__); \
225   fcloseall(); \
226   exit(1); \
227 } while (0)
228 #define fnote(op_, fmt, ...) \
229   printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
230     dump_op(op_), ##__VA_ARGS__)
231
232 #define MAX_REGS 8
233
234 const char *regs_r32[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp" };
235 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
236 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
237 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
238
239 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
240
241 // possible basic comparison types (without inversion)
242 enum parsed_flag_op {
243   PFO_O,  // 0 OF=1
244   PFO_C,  // 2 CF=1
245   PFO_Z,  // 4 ZF=1
246   PFO_BE, // 6 CF=1||ZF=1
247   PFO_S,  // 8 SF=1
248   PFO_P,  // a PF=1
249   PFO_L,  // c SF!=OF
250   PFO_LE, // e ZF=1||SF!=OF
251 };
252
253 static const char *parsed_flag_op_names[] = {
254   "o", "c", "z", "be", "s", "p", "l", "le"
255 };
256
257 static int char_array_i(const char *array[], size_t len, const char *s)
258 {
259   int i;
260
261   for (i = 0; i < len; i++)
262     if (IS(s, array[i]))
263       return i;
264
265   return -1;
266 }
267
268 static void printf_number(char *buf, size_t buf_size,
269   unsigned long number)
270 {
271   // output in C-friendly form
272   snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
273 }
274
275 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
276 {
277   int reg;
278
279   reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
280   if (reg >= 0) {
281     *reg_lmod = OPLM_DWORD;
282     return reg;
283   }
284   reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
285   if (reg >= 0) {
286     *reg_lmod = OPLM_WORD;
287     return reg;
288   }
289   reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
290   if (reg >= 0) {
291     *reg_lmod = OPLM_BYTE;
292     return reg;
293   }
294   reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
295   if (reg >= 0) {
296     *reg_lmod = OPLM_BYTE;
297     return reg;
298   }
299
300   return -1;
301 }
302
303 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
304 {
305   enum opr_lenmod lmod;
306   char cvtbuf[256];
307   char *d = cvtbuf;
308   char *s = name;
309   char w[64];
310   long number;
311   int reg;
312   int c = 0;
313
314   *d = 0;
315
316   while (*s != 0) {
317     d += strlen(d);
318     while (my_isblank(*s))
319       s++;
320     for (; my_issep(*s); d++, s++)
321       *d = *s;
322     while (my_isblank(*s))
323       s++;
324     *d = 0;
325
326     // skip 'ds:' prefix
327     if (IS_START(s, "ds:"))
328       s += 3;
329
330     s = next_idt(w, sizeof(w), s);
331     if (w[0] == 0)
332       break;
333     c++;
334
335     reg = parse_reg(&lmod, w);
336     if (reg >= 0) {
337       *regmask |= 1 << reg;
338       goto pass;
339     }
340
341     if ('0' <= w[0] && w[0] <= '9') {
342       number = parse_number(w);
343       printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
344       continue;
345     }
346
347     // probably some label/identifier - pass
348
349 pass:
350     snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
351   }
352
353   if (need_c_cvt)
354     strcpy(name, cvtbuf);
355
356   return c;
357 }
358
359 static int is_reg_in_str(const char *s)
360 {
361   int i;
362
363   if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
364     return 0;
365
366   for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
367     if (!strncmp(s, regs_r32[i], 3))
368       return 1;
369
370   return 0;
371 }
372
373 static const char *parse_stack_el(const char *name, char *extra_reg)
374 {
375   const char *p, *p2, *s;
376   char *endp = NULL;
377   char buf[32];
378   long val;
379   int len;
380
381   p = name;
382   if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
383     p += 4;
384     if (extra_reg != NULL) {
385       strncpy(extra_reg, name, 3);
386       extra_reg[4] = 0;
387     }
388   }
389
390   if (IS_START(p, "ebp+")) {
391     p += 4;
392
393     p2 = strchr(p, '+');
394     if (p2 != NULL && is_reg_in_str(p)) {
395       if (extra_reg != NULL) {
396         strncpy(extra_reg, p, p2 - p);
397         extra_reg[p2 - p] = 0;
398       }
399       p = p2 + 1;
400     }
401
402     if (!('0' <= *p && *p <= '9'))
403       return p;
404
405     return NULL;
406   }
407
408   if (!IS_START(name, "esp+"))
409     return NULL;
410
411   s = name + 4;
412   p = strchr(s, '+');
413   if (p) {
414     if (is_reg_in_str(s)) {
415       if (extra_reg != NULL) {
416         strncpy(extra_reg, s, p - s);
417         extra_reg[p - s] = 0;
418       }
419       s = p + 1;
420       p = strchr(s, '+');
421       if (p == NULL)
422         aerr("%s IDA stackvar not set?\n", __func__);
423     }
424     if (!('0' <= *s && *s <= '9')) {
425       aerr("%s IDA stackvar offset not set?\n", __func__);
426       return NULL;
427     }
428     if (s[0] == '0' && s[1] == 'x')
429       s += 2;
430     len = p - s;
431     if (len < sizeof(buf) - 1) {
432       strncpy(buf, s, len);
433       buf[len] = 0;
434       val = strtol(buf, &endp, 16);
435       if (val == 0 || *endp != 0) {
436         aerr("%s num parse fail for '%s'\n", __func__, buf);
437         return NULL;
438       }
439     }
440     p++;
441   }
442   else
443     p = name + 4;
444
445   if ('0' <= *p && *p <= '9')
446     return NULL;
447
448   return p;
449 }
450
451 static int guess_lmod_from_name(struct parsed_opr *opr)
452 {
453   if (!strncmp(opr->name, "dword_", 6)) {
454     opr->lmod = OPLM_DWORD;
455     return 1;
456   }
457   if (!strncmp(opr->name, "word_", 5)) {
458     opr->lmod = OPLM_WORD;
459     return 1;
460   }
461   if (!strncmp(opr->name, "byte_", 5)) {
462     opr->lmod = OPLM_BYTE;
463     return 1;
464   }
465   return 0;
466 }
467
468 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
469   const struct parsed_type *c_type)
470 {
471   static const char *dword_types[] = {
472     "int", "_DWORD", "UINT_PTR", "DWORD",
473     "WPARAM", "LPARAM", "UINT", "__int32",
474     "LONG", "HIMC",
475   };
476   static const char *word_types[] = {
477     "uint16_t", "int16_t", "_WORD",
478     "unsigned __int16", "__int16",
479   };
480   static const char *byte_types[] = {
481     "uint8_t", "int8_t", "char",
482     "unsigned __int8", "__int8", "BYTE", "_BYTE",
483     "CHAR", "_UNKNOWN",
484   };
485   const char *n;
486   int i;
487
488   if (c_type->is_ptr) {
489     *lmod = OPLM_DWORD;
490     return 1;
491   }
492
493   n = skip_type_mod(c_type->name);
494
495   for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
496     if (IS(n, dword_types[i])) {
497       *lmod = OPLM_DWORD;
498       return 1;
499     }
500   }
501
502   for (i = 0; i < ARRAY_SIZE(word_types); i++) {
503     if (IS(n, word_types[i])) {
504       *lmod = OPLM_WORD;
505       return 1;
506     }
507   }
508
509   for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
510     if (IS(n, byte_types[i])) {
511       *lmod = OPLM_BYTE;
512       return 1;
513     }
514   }
515
516   return 0;
517 }
518
519 static enum opr_type lmod_from_directive(const char *d)
520 {
521   if (IS(d, "dd"))
522     return OPLM_DWORD;
523   else if (IS(d, "dw"))
524     return OPLM_WORD;
525   else if (IS(d, "db"))
526     return OPLM_BYTE;
527
528   aerr("unhandled directive: '%s'\n", d);
529   return OPLM_UNSPEC;
530 }
531
532 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
533   int *regmask)
534 {
535   opr->type = OPT_REG;
536   opr->reg = reg;
537   opr->lmod = lmod;
538   *regmask |= 1 << reg;
539 }
540
541 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
542   int *extra_offs);
543
544 static int parse_operand(struct parsed_opr *opr,
545   int *regmask, int *regmask_indirect,
546   char words[16][256], int wordc, int w, unsigned int op_flags)
547 {
548   const struct parsed_proto *pp;
549   enum opr_lenmod tmplmod;
550   unsigned long number;
551   char buf[256];
552   int ret, len;
553   int wordc_in;
554   char *p;
555   int i;
556
557   if (w >= wordc)
558     aerr("parse_operand w %d, wordc %d\n", w, wordc);
559
560   opr->reg = xUNSPEC;
561
562   for (i = w; i < wordc; i++) {
563     len = strlen(words[i]);
564     if (words[i][len - 1] == ',') {
565       words[i][len - 1] = 0;
566       wordc = i + 1;
567       break;
568     }
569   }
570
571   wordc_in = wordc - w;
572
573   if ((op_flags & OPF_JMP) && wordc_in > 0
574       && !('0' <= words[w][0] && words[w][0] <= '9'))
575   {
576     const char *label = NULL;
577
578     if (wordc_in == 3 && !strncmp(words[w], "near", 4)
579      && IS(words[w + 1], "ptr"))
580       label = words[w + 2];
581     else if (wordc_in == 2 && IS(words[w], "short"))
582       label = words[w + 1];
583     else if (wordc_in == 1
584           && strchr(words[w], '[') == NULL
585           && parse_reg(&tmplmod, words[w]) < 0)
586       label = words[w];
587
588     if (label != NULL) {
589       opr->type = OPT_LABEL;
590       if (IS_START(label, "ds:")) {
591         opr->had_ds = 1;
592         label += 3;
593       }
594       strcpy(opr->name, label);
595       return wordc;
596     }
597   }
598
599   if (wordc_in >= 3) {
600     if (IS(words[w + 1], "ptr")) {
601       if (IS(words[w], "dword"))
602         opr->lmod = OPLM_DWORD;
603       else if (IS(words[w], "word"))
604         opr->lmod = OPLM_WORD;
605       else if (IS(words[w], "byte"))
606         opr->lmod = OPLM_BYTE;
607       else
608         aerr("type parsing failed\n");
609       w += 2;
610       wordc_in = wordc - w;
611     }
612   }
613
614   if (wordc_in == 2) {
615     if (IS(words[w], "offset")) {
616       opr->type = OPT_OFFSET;
617       strcpy(opr->name, words[w + 1]);
618       return wordc;
619     }
620     if (IS(words[w], "(offset")) {
621       p = strchr(words[w + 1], ')');
622       if (p == NULL)
623         aerr("parse of bracketed offset failed\n");
624       *p = 0;
625       opr->type = OPT_OFFSET;
626       strcpy(opr->name, words[w + 1]);
627       return wordc;
628     }
629   }
630
631   if (wordc_in != 1)
632     aerr("parse_operand 1 word expected\n");
633
634   if (IS_START(words[w], "ds:")) {
635     opr->had_ds = 1;
636     memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
637   }
638   strcpy(opr->name, words[w]);
639
640   if (words[w][0] == '[') {
641     opr->type = OPT_REGMEM;
642     ret = sscanf(words[w], "[%[^]]]", opr->name);
643     if (ret != 1)
644       aerr("[] parse failure\n");
645
646     parse_indmode(opr->name, regmask_indirect, 1);
647     if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL)) {
648       // might be an equ
649       struct parsed_equ *eq =
650         equ_find(NULL, parse_stack_el(opr->name, NULL), &i);
651       if (eq)
652         opr->lmod = eq->lmod;
653     }
654     return wordc;
655   }
656   else if (strchr(words[w], '[')) {
657     // label[reg] form
658     p = strchr(words[w], '[');
659     opr->type = OPT_REGMEM;
660     parse_indmode(p, regmask_indirect, 0);
661     strncpy(buf, words[w], p - words[w]);
662     buf[p - words[w]] = 0;
663     pp = proto_parse(g_fhdr, buf, 1);
664     goto do_label;
665   }
666   else if (('0' <= words[w][0] && words[w][0] <= '9')
667     || words[w][0] == '-')
668   {
669     number = parse_number(words[w]);
670     opr->type = OPT_CONST;
671     opr->val = number;
672     printf_number(opr->name, sizeof(opr->name), number);
673     return wordc;
674   }
675
676   ret = parse_reg(&tmplmod, opr->name);
677   if (ret >= 0) {
678     setup_reg_opr(opr, ret, tmplmod, regmask);
679     return wordc;
680   }
681
682   // most likely var in data segment
683   opr->type = OPT_LABEL;
684   pp = proto_parse(g_fhdr, opr->name, 0);
685
686 do_label:
687   if (pp != NULL) {
688     if (pp->is_fptr || pp->is_func) {
689       opr->lmod = OPLM_DWORD;
690       opr->is_ptr = 1;
691     }
692     else {
693       tmplmod = OPLM_UNSPEC;
694       if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
695         anote("unhandled C type '%s' for '%s'\n",
696           pp->type.name, opr->name);
697       
698       if (opr->lmod == OPLM_UNSPEC) {
699         opr->lmod = tmplmod;
700         opr->type_from_var = 1;
701       }
702       else if (opr->lmod != tmplmod) {
703         opr->size_mismatch = 1;
704         if (tmplmod < opr->lmod)
705           opr->size_lt = 1;
706       }
707       opr->is_ptr = pp->type.is_ptr;
708     }
709     opr->is_array = pp->type.is_array;
710   }
711
712   if (opr->lmod == OPLM_UNSPEC)
713     guess_lmod_from_name(opr);
714   return wordc;
715 }
716
717 static const struct {
718   const char *name;
719   unsigned int flags;
720 } pref_table[] = {
721   { "rep",    OPF_REP },
722   { "repe",   OPF_REP|OPF_REPZ },
723   { "repz",   OPF_REP|OPF_REPZ },
724   { "repne",  OPF_REP|OPF_REPNZ },
725   { "repnz",  OPF_REP|OPF_REPNZ },
726   { "lock",   OPF_LOCK }, // ignored for now..
727 };
728
729 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
730
731 static const struct {
732   const char *name;
733   enum op_op op;
734   unsigned int minopr;
735   unsigned int maxopr;
736   unsigned int flags;
737 } op_table[] = {
738   { "nop",  OP_NOP,    0, 0, 0 },
739   { "push", OP_PUSH,   1, 1, 0 },
740   { "pop",  OP_POP,    1, 1, OPF_DATA },
741   { "leave",OP_LEAVE,  0, 0, OPF_DATA },
742   { "mov" , OP_MOV,    2, 2, OPF_DATA },
743   { "lea",  OP_LEA,    2, 2, OPF_DATA },
744   { "movzx",OP_MOVZX,  2, 2, OPF_DATA },
745   { "movsx",OP_MOVSX,  2, 2, OPF_DATA },
746   { "xchg", OP_XCHG,   2, 2, OPF_DATA },
747   { "not",  OP_NOT,    1, 1, OPF_DATA },
748   { "cdq",  OP_CDQ,    0, 0, OPF_DATA },
749   { "stosb",OP_STOS,   0, 0, OPF_DATA },
750   { "stosw",OP_STOS,   0, 0, OPF_DATA },
751   { "stosd",OP_STOS,   0, 0, OPF_DATA },
752   { "movsb",OP_MOVS,   0, 0, OPF_DATA },
753   { "movsw",OP_MOVS,   0, 0, OPF_DATA },
754   { "movsd",OP_MOVS,   0, 0, OPF_DATA },
755   { "cmpsb",OP_CMPS,   0, 0, OPF_DATA|OPF_FLAGS },
756   { "cmpsw",OP_CMPS,   0, 0, OPF_DATA|OPF_FLAGS },
757   { "cmpsd",OP_CMPS,   0, 0, OPF_DATA|OPF_FLAGS },
758   { "scasb",OP_SCAS,   0, 0, OPF_DATA|OPF_FLAGS },
759   { "scasw",OP_SCAS,   0, 0, OPF_DATA|OPF_FLAGS },
760   { "scasd",OP_SCAS,   0, 0, OPF_DATA|OPF_FLAGS },
761   { "std",  OP_STD,    0, 0, OPF_DATA }, // special flag
762   { "cld",  OP_CLD,    0, 0, OPF_DATA },
763   { "add",  OP_ADD,    2, 2, OPF_DATA|OPF_FLAGS },
764   { "sub",  OP_SUB,    2, 2, OPF_DATA|OPF_FLAGS },
765   { "and",  OP_AND,    2, 2, OPF_DATA|OPF_FLAGS },
766   { "or",   OP_OR,     2, 2, OPF_DATA|OPF_FLAGS },
767   { "xor",  OP_XOR,    2, 2, OPF_DATA|OPF_FLAGS },
768   { "shl",  OP_SHL,    2, 2, OPF_DATA|OPF_FLAGS },
769   { "shr",  OP_SHR,    2, 2, OPF_DATA|OPF_FLAGS },
770   { "sal",  OP_SHL,    2, 2, OPF_DATA|OPF_FLAGS },
771   { "sar",  OP_SAR,    2, 2, OPF_DATA|OPF_FLAGS },
772   { "rol",  OP_ROL,    2, 2, OPF_DATA|OPF_FLAGS },
773   { "ror",  OP_ROR,    2, 2, OPF_DATA|OPF_FLAGS },
774   { "rcl",  OP_RCL,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
775   { "rcr",  OP_RCR,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
776   { "adc",  OP_ADC,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
777   { "sbb",  OP_SBB,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
778   { "bsf",  OP_BSF,    2, 2, OPF_DATA|OPF_FLAGS },
779   { "inc",  OP_INC,    1, 1, OPF_DATA|OPF_FLAGS },
780   { "dec",  OP_DEC,    1, 1, OPF_DATA|OPF_FLAGS },
781   { "neg",  OP_NEG,    1, 1, OPF_DATA|OPF_FLAGS },
782   { "mul",  OP_MUL,    1, 1, OPF_DATA|OPF_FLAGS },
783   { "imul", OP_IMUL,   1, 3, OPF_DATA|OPF_FLAGS },
784   { "div",  OP_DIV,    1, 1, OPF_DATA|OPF_FLAGS },
785   { "idiv", OP_IDIV,   1, 1, OPF_DATA|OPF_FLAGS },
786   { "test", OP_TEST,   2, 2, OPF_FLAGS },
787   { "cmp",  OP_CMP,    2, 2, OPF_FLAGS },
788   { "retn", OP_RET,    0, 1, OPF_TAIL },
789   { "call", OP_CALL,   1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
790   { "jmp",  OP_JMP,    1, 1, OPF_JMP },
791   { "jecxz",OP_JECXZ,  1, 1, OPF_JMP|OPF_CJMP },
792   { "jo",   OP_JO,     1, 1, OPF_CJMP_CC }, // 70 OF=1
793   { "jno",  OP_JNO,    1, 1, OPF_CJMP_CC }, // 71 OF=0
794   { "jc",   OP_JC,     1, 1, OPF_CJMP_CC }, // 72 CF=1
795   { "jb",   OP_JC,     1, 1, OPF_CJMP_CC }, // 72
796   { "jnc",  OP_JNC,    1, 1, OPF_CJMP_CC }, // 73 CF=0
797   { "jnb",  OP_JNC,    1, 1, OPF_CJMP_CC }, // 73
798   { "jae",  OP_JNC,    1, 1, OPF_CJMP_CC }, // 73
799   { "jz",   OP_JZ,     1, 1, OPF_CJMP_CC }, // 74 ZF=1
800   { "je",   OP_JZ,     1, 1, OPF_CJMP_CC }, // 74
801   { "jnz",  OP_JNZ,    1, 1, OPF_CJMP_CC }, // 75 ZF=0
802   { "jne",  OP_JNZ,    1, 1, OPF_CJMP_CC }, // 75
803   { "jbe",  OP_JBE,    1, 1, OPF_CJMP_CC }, // 76 CF=1 || ZF=1
804   { "jna",  OP_JBE,    1, 1, OPF_CJMP_CC }, // 76
805   { "ja",   OP_JA,     1, 1, OPF_CJMP_CC }, // 77 CF=0 && ZF=0
806   { "jnbe", OP_JA,     1, 1, OPF_CJMP_CC }, // 77
807   { "js",   OP_JS,     1, 1, OPF_CJMP_CC }, // 78 SF=1
808   { "jns",  OP_JNS,    1, 1, OPF_CJMP_CC }, // 79 SF=0
809   { "jp",   OP_JP,     1, 1, OPF_CJMP_CC }, // 7a PF=1
810   { "jpe",  OP_JP,     1, 1, OPF_CJMP_CC }, // 7a
811   { "jnp",  OP_JNP,    1, 1, OPF_CJMP_CC }, // 7b PF=0
812   { "jpo",  OP_JNP,    1, 1, OPF_CJMP_CC }, // 7b
813   { "jl",   OP_JL,     1, 1, OPF_CJMP_CC }, // 7c SF!=OF
814   { "jnge", OP_JL,     1, 1, OPF_CJMP_CC }, // 7c
815   { "jge",  OP_JGE,    1, 1, OPF_CJMP_CC }, // 7d SF=OF
816   { "jnl",  OP_JGE,    1, 1, OPF_CJMP_CC }, // 7d
817   { "jle",  OP_JLE,    1, 1, OPF_CJMP_CC }, // 7e ZF=1 || SF!=OF
818   { "jng",  OP_JLE,    1, 1, OPF_CJMP_CC }, // 7e
819   { "jg",   OP_JG,     1, 1, OPF_CJMP_CC }, // 7f ZF=0 && SF=OF
820   { "jnle", OP_JG,     1, 1, OPF_CJMP_CC }, // 7f
821   { "seto",   OP_JO,   1, 1, OPF_DATA|OPF_CC },
822   { "setno",  OP_JNO,  1, 1, OPF_DATA|OPF_CC },
823   { "setc",   OP_JC,   1, 1, OPF_DATA|OPF_CC },
824   { "setb",   OP_JC,   1, 1, OPF_DATA|OPF_CC },
825   { "setnc",  OP_JNC,  1, 1, OPF_DATA|OPF_CC },
826   { "setae",  OP_JNC,  1, 1, OPF_DATA|OPF_CC },
827   { "setz",   OP_JZ,   1, 1, OPF_DATA|OPF_CC },
828   { "sete",   OP_JZ,   1, 1, OPF_DATA|OPF_CC },
829   { "setnz",  OP_JNZ,  1, 1, OPF_DATA|OPF_CC },
830   { "setne",  OP_JNZ,  1, 1, OPF_DATA|OPF_CC },
831   { "setbe",  OP_JBE,  1, 1, OPF_DATA|OPF_CC },
832   { "setna",  OP_JBE,  1, 1, OPF_DATA|OPF_CC },
833   { "seta",   OP_JA,   1, 1, OPF_DATA|OPF_CC },
834   { "setnbe", OP_JA,   1, 1, OPF_DATA|OPF_CC },
835   { "sets",   OP_JS,   1, 1, OPF_DATA|OPF_CC },
836   { "setns",  OP_JNS,  1, 1, OPF_DATA|OPF_CC },
837   { "setp",   OP_JP,   1, 1, OPF_DATA|OPF_CC },
838   { "setpe",  OP_JP,   1, 1, OPF_DATA|OPF_CC },
839   { "setnp",  OP_JNP,  1, 1, OPF_DATA|OPF_CC },
840   { "setpo",  OP_JNP,  1, 1, OPF_DATA|OPF_CC },
841   { "setl",   OP_JL,   1, 1, OPF_DATA|OPF_CC },
842   { "setnge", OP_JL,   1, 1, OPF_DATA|OPF_CC },
843   { "setge",  OP_JGE,  1, 1, OPF_DATA|OPF_CC },
844   { "setnl",  OP_JGE,  1, 1, OPF_DATA|OPF_CC },
845   { "setle",  OP_JLE,  1, 1, OPF_DATA|OPF_CC },
846   { "setng",  OP_JLE,  1, 1, OPF_DATA|OPF_CC },
847   { "setg",   OP_JG,   1, 1, OPF_DATA|OPF_CC },
848   { "setnle", OP_JG,   1, 1, OPF_DATA|OPF_CC },
849 };
850
851 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
852 {
853   enum opr_lenmod lmod = OPLM_UNSPEC;
854   int prefix_flags = 0;
855   int regmask_ind;
856   int regmask;
857   int op_w = 0;
858   int opr = 0;
859   int w = 0;
860   int i;
861
862   for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
863     if (IS(words[w], pref_table[i].name)) {
864       prefix_flags = pref_table[i].flags;
865       break;
866     }
867   }
868
869   if (prefix_flags) {
870     if (wordc <= 1)
871       aerr("lone prefix: '%s'\n", words[0]);
872     w++;
873   }
874
875   op_w = w;
876   for (i = 0; i < ARRAY_SIZE(op_table); i++) {
877     if (IS(words[w], op_table[i].name))
878       break;
879   }
880
881   if (i == ARRAY_SIZE(op_table))
882     aerr("unhandled op: '%s'\n", words[0]);
883   w++;
884
885   op->op = op_table[i].op;
886   op->flags = op_table[i].flags | prefix_flags;
887   op->regmask_src = op->regmask_dst = 0;
888
889   for (opr = 0; opr < op_table[i].minopr; opr++) {
890     regmask = regmask_ind = 0;
891     w = parse_operand(&op->operand[opr], &regmask, &regmask_ind,
892       words, wordc, w, op->flags);
893
894     if (opr == 0 && (op->flags & OPF_DATA))
895       op->regmask_dst = regmask;
896     // for now, mark dst as src too
897     op->regmask_src |= regmask | regmask_ind;
898   }
899
900   for (; w < wordc && opr < op_table[i].maxopr; opr++) {
901     w = parse_operand(&op->operand[opr],
902       &op->regmask_src, &op->regmask_src,
903       words, wordc, w, op->flags);
904   }
905
906   if (w < wordc)
907     aerr("parse_op %s incomplete: %d/%d\n",
908       words[0], w, wordc);
909
910   // special cases
911   op->operand_cnt = opr;
912   if (!strncmp(op_table[i].name, "set", 3))
913     op->operand[0].lmod = OPLM_BYTE;
914
915   // ops with implicit argumets
916   switch (op->op) {
917   case OP_CDQ:
918     op->operand_cnt = 2;
919     setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
920     setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
921     break;
922
923   case OP_STOS:
924   case OP_SCAS:
925     if (op->operand_cnt != 0)
926       break;
927     if      (words[op_w][4] == 'b')
928       lmod = OPLM_BYTE;
929     else if (words[op_w][4] == 'w')
930       lmod = OPLM_WORD;
931     else if (words[op_w][4] == 'd')
932       lmod = OPLM_DWORD;
933     op->operand_cnt = 3;
934     setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
935     setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
936     op->regmask_dst = op->regmask_src;
937     setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD, &op->regmask_src);
938     break;
939
940   case OP_MOVS:
941   case OP_CMPS:
942     if (op->operand_cnt != 0)
943       break;
944     if      (words[op_w][4] == 'b')
945       lmod = OPLM_BYTE;
946     else if (words[op_w][4] == 'w')
947       lmod = OPLM_WORD;
948     else if (words[op_w][4] == 'd')
949       lmod = OPLM_DWORD;
950     op->operand_cnt = 3;
951     setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
952     setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
953     setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
954     op->regmask_dst = op->regmask_src;
955     break;
956
957   case OP_XCHG:
958     op->regmask_src |= op->regmask_dst;
959     op->regmask_dst |= op->regmask_src;
960     break;
961
962   case OP_JECXZ:
963     op->operand_cnt = 1;
964     op->regmask_src = 1 << xCX;
965     op->operand[0].type = OPT_REG;
966     op->operand[0].reg = xCX;
967     op->operand[0].lmod = OPLM_DWORD;
968     break;
969
970   case OP_IMUL:
971     if (op->operand_cnt != 1)
972       break;
973     // fallthrough
974   case OP_MUL:
975     // singleop mul
976     op->regmask_dst = (1 << xDX) | (1 << xAX);
977     op->regmask_src |= (1 << xAX);
978     if (op->operand[0].lmod == OPLM_UNSPEC)
979       op->operand[0].lmod = OPLM_DWORD;
980     break;
981
982   case OP_DIV:
983   case OP_IDIV:
984     // we could set up operands for edx:eax, but there is no real need to
985     // (see is_opr_modified())
986     regmask = (1 << xDX) | (1 << xAX);
987     op->regmask_dst = regmask;
988     op->regmask_src |= regmask;
989     if (op->operand[0].lmod == OPLM_UNSPEC)
990       op->operand[0].lmod = OPLM_DWORD;
991     break;
992
993   case OP_SHL:
994   case OP_SHR:
995   case OP_SAR:
996   case OP_ROL:
997   case OP_ROR:
998     if (op->operand[1].lmod == OPLM_UNSPEC)
999       op->operand[1].lmod = OPLM_BYTE;
1000     break;
1001
1002   case OP_PUSH:
1003     if (op->operand[0].lmod == OPLM_UNSPEC
1004         && (op->operand[0].type == OPT_CONST
1005          || op->operand[0].type == OPT_OFFSET
1006          || op->operand[0].type == OPT_LABEL))
1007       op->operand[0].lmod = OPLM_DWORD;
1008     break;
1009
1010   // alignment
1011   case OP_MOV:
1012     if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1013      && op->operand[0].reg == xDI && op->operand[1].reg == xDI)
1014     {
1015       op->flags |= OPF_RMD;
1016     }
1017     break;
1018
1019   case OP_LEA:
1020     if (op->operand[0].type == OPT_REG
1021      && op->operand[1].type == OPT_REGMEM)
1022     {
1023       char buf[16];
1024       snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1025       if (IS(buf, op->operand[1].name))
1026         op->flags |= OPF_RMD;
1027     }
1028     break;
1029
1030   case OP_CALL:
1031     // trashed regs must be explicitly detected later
1032     op->regmask_dst = 0;
1033     break;
1034
1035   default:
1036     break;
1037   }
1038 }
1039
1040 static const char *op_name(enum op_op op)
1041 {
1042   int i;
1043
1044   for (i = 0; i < ARRAY_SIZE(op_table); i++)
1045     if (op_table[i].op == op)
1046       return op_table[i].name;
1047
1048   return "???";
1049 }
1050
1051 // debug
1052 static const char *dump_op(struct parsed_op *po)
1053 {
1054   static char out[128];
1055   char *p = out;
1056   int i;
1057
1058   if (po == NULL)
1059     return "???";
1060
1061   snprintf(out, sizeof(out), "%s", op_name(po->op));
1062   for (i = 0; i < po->operand_cnt; i++) {
1063     p += strlen(p);
1064     if (i > 0)
1065       *p++ = ',';
1066     snprintf(p, sizeof(out) - (p - out),
1067       po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1068       po->operand[i].name);
1069   }
1070
1071   return out;
1072 }
1073
1074 static const char *lmod_type_u(struct parsed_op *po,
1075   enum opr_lenmod lmod)
1076 {
1077   switch (lmod) {
1078   case OPLM_DWORD:
1079     return "u32";
1080   case OPLM_WORD:
1081     return "u16";
1082   case OPLM_BYTE:
1083     return "u8";
1084   default:
1085     ferr(po, "invalid lmod: %d\n", lmod);
1086     return "(_invalid_)";
1087   }
1088 }
1089
1090 static const char *lmod_cast_u(struct parsed_op *po,
1091   enum opr_lenmod lmod)
1092 {
1093   switch (lmod) {
1094   case OPLM_DWORD:
1095     return "";
1096   case OPLM_WORD:
1097     return "(u16)";
1098   case OPLM_BYTE:
1099     return "(u8)";
1100   default:
1101     ferr(po, "invalid lmod: %d\n", lmod);
1102     return "(_invalid_)";
1103   }
1104 }
1105
1106 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1107   enum opr_lenmod lmod)
1108 {
1109   switch (lmod) {
1110   case OPLM_DWORD:
1111     return "*(u32 *)";
1112   case OPLM_WORD:
1113     return "*(u16 *)";
1114   case OPLM_BYTE:
1115     return "*(u8 *)";
1116   default:
1117     ferr(po, "invalid lmod: %d\n", lmod);
1118     return "(_invalid_)";
1119   }
1120 }
1121
1122 static const char *lmod_cast_s(struct parsed_op *po,
1123   enum opr_lenmod lmod)
1124 {
1125   switch (lmod) {
1126   case OPLM_DWORD:
1127     return "(s32)";
1128   case OPLM_WORD:
1129     return "(s16)";
1130   case OPLM_BYTE:
1131     return "(s8)";
1132   default:
1133     ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1134     return "(_invalid_)";
1135   }
1136 }
1137
1138 static const char *lmod_cast(struct parsed_op *po,
1139   enum opr_lenmod lmod, int is_signed)
1140 {
1141   return is_signed ?
1142     lmod_cast_s(po, lmod) :
1143     lmod_cast_u(po, lmod);
1144 }
1145
1146 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1147 {
1148   switch (lmod) {
1149   case OPLM_DWORD:
1150     return 4;
1151   case OPLM_WORD:
1152     return 2;
1153   case OPLM_BYTE:
1154     return 1;
1155   default:
1156     ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1157     return 0;
1158   }
1159 }
1160
1161 static const char *opr_name(struct parsed_op *po, int opr_num)
1162 {
1163   if (opr_num >= po->operand_cnt)
1164     ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1165   return po->operand[opr_num].name;
1166 }
1167
1168 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1169 {
1170   if (opr_num >= po->operand_cnt)
1171     ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1172   if (po->operand[opr_num].type != OPT_CONST)
1173     ferr(po, "opr %d: const expected\n", opr_num);
1174   return po->operand[opr_num].val;
1175 }
1176
1177 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1178 {
1179   if ((unsigned int)popr->reg >= MAX_REGS)
1180     ferr(po, "invalid reg: %d\n", popr->reg);
1181   return regs_r32[popr->reg];
1182 }
1183
1184 // cast1 is the "final" cast
1185 static const char *simplify_cast(const char *cast1, const char *cast2)
1186 {
1187   static char buf[256];
1188
1189   if (cast1[0] == 0)
1190     return cast2;
1191   if (cast2[0] == 0)
1192     return cast1;
1193   if (IS(cast1, cast2))
1194     return cast1;
1195   if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1196     return cast1;
1197   if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1198     return cast1;
1199   if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1200     return cast2;
1201   if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1202     return cast2;
1203   if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1204     return cast1;
1205
1206   snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1207   return buf;
1208 }
1209
1210 static const char *simplify_cast_num(const char *cast, unsigned int val)
1211 {
1212   if (IS(cast, "(u8)") && val < 0x100)
1213     return "";
1214   if (IS(cast, "(s8)") && val < 0x80)
1215     return "";
1216   if (IS(cast, "(u16)") && val < 0x10000)
1217     return "";
1218   if (IS(cast, "(s16)") && val < 0x8000)
1219     return "";
1220   if (IS(cast, "(s32)") && val < 0x80000000)
1221     return "";
1222
1223   return cast;
1224 }
1225
1226 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1227   int *extra_offs)
1228 {
1229   const char *p;
1230   char *endp;
1231   int namelen;
1232   int i;
1233
1234   *extra_offs = 0;
1235   namelen = strlen(name);
1236
1237   p = strchr(name, '+');
1238   if (p != NULL) {
1239     namelen = p - name;
1240     if (namelen <= 0)
1241       ferr(po, "equ parse failed for '%s'\n", name);
1242
1243     if (IS_START(p, "0x"))
1244       p += 2;
1245     *extra_offs = strtol(p, &endp, 16);
1246     if (*endp != 0)
1247       ferr(po, "equ parse failed for '%s'\n", name);
1248   }
1249
1250   for (i = 0; i < g_eqcnt; i++)
1251     if (strncmp(g_eqs[i].name, name, namelen) == 0
1252      && g_eqs[i].name[namelen] == 0)
1253       break;
1254   if (i >= g_eqcnt) {
1255     if (po != NULL)
1256       ferr(po, "unresolved equ name: '%s'\n", name);
1257     return NULL;
1258   }
1259
1260   return &g_eqs[i];
1261 }
1262
1263 static int is_stack_access(struct parsed_op *po,
1264   const struct parsed_opr *popr)
1265 {
1266   return (parse_stack_el(popr->name, NULL)
1267     || (g_bp_frame && !(po->flags & OPF_EBP_S)
1268         && IS_START(popr->name, "ebp")));
1269 }
1270
1271 static void parse_stack_access(struct parsed_op *po,
1272   const char *name, char *ofs_reg, int *offset_out,
1273   int *stack_ra_out, const char **bp_arg_out, int is_lea)
1274 {
1275   const char *bp_arg = "";
1276   const char *p = NULL;
1277   struct parsed_equ *eq;
1278   char *endp = NULL;
1279   int stack_ra = 0;
1280   int offset = 0;
1281
1282   ofs_reg[0] = 0;
1283
1284   if (IS_START(name, "ebp-")
1285    || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1286   {
1287     p = name + 4;
1288     if (IS_START(p, "0x"))
1289       p += 2;
1290     offset = strtoul(p, &endp, 16);
1291     if (name[3] == '-')
1292       offset = -offset;
1293     if (*endp != 0)
1294       ferr(po, "ebp- parse of '%s' failed\n", name);
1295   }
1296   else {
1297     bp_arg = parse_stack_el(name, ofs_reg);
1298     snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1299     eq = equ_find(po, bp_arg, &offset);
1300     if (eq == NULL)
1301       ferr(po, "detected but missing eq\n");
1302     offset += eq->offset;
1303   }
1304
1305   if (!strncmp(name, "ebp", 3))
1306     stack_ra = 4;
1307
1308   // yes it sometimes LEAs ra for compares..
1309   if (!is_lea && ofs_reg[0] == 0
1310     && stack_ra <= offset && offset < stack_ra + 4)
1311   {
1312     ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1313   }
1314
1315   *offset_out = offset;
1316   *stack_ra_out = stack_ra;
1317   if (bp_arg_out)
1318     *bp_arg_out = bp_arg;
1319 }
1320
1321 static void stack_frame_access(struct parsed_op *po,
1322   struct parsed_opr *popr, char *buf, size_t buf_size,
1323   const char *name, const char *cast, int is_src, int is_lea)
1324 {
1325   enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1326   const char *prefix = "";
1327   const char *bp_arg = NULL;
1328   char ofs_reg[16] = { 0, };
1329   int i, arg_i, arg_s;
1330   int unaligned = 0;
1331   int stack_ra = 0;
1332   int offset = 0;
1333   int sf_ofs;
1334   int lim;
1335
1336   if (po->flags & OPF_EBP_S)
1337     ferr(po, "stack_frame_access while ebp is scratch\n");
1338
1339   parse_stack_access(po, name, ofs_reg, &offset,
1340     &stack_ra, &bp_arg, is_lea);
1341
1342   if (offset > stack_ra)
1343   {
1344     arg_i = (offset - stack_ra - 4) / 4;
1345     if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1346     {
1347       if (g_func_pp->is_vararg
1348           && arg_i == g_func_pp->argc_stack && is_lea)
1349       {
1350         // should be va_list
1351         if (cast[0] == 0)
1352           cast = "(u32)";
1353         snprintf(buf, buf_size, "%sap", cast);
1354         return;
1355       }
1356       ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1357         offset, bp_arg, arg_i);
1358     }
1359     if (ofs_reg[0] != 0)
1360       ferr(po, "offset reg on arg access?\n");
1361
1362     for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1363       if (g_func_pp->arg[i].reg != NULL)
1364         continue;
1365       if (arg_s == arg_i)
1366         break;
1367       arg_s++;
1368     }
1369     if (i == g_func_pp->argc)
1370       ferr(po, "arg %d not in prototype?\n", arg_i);
1371
1372     popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1373
1374     switch (popr->lmod)
1375     {
1376     case OPLM_BYTE:
1377       if (is_lea)
1378         ferr(po, "lea/byte to arg?\n");
1379       if (is_src && (offset & 3) == 0)
1380         snprintf(buf, buf_size, "%sa%d",
1381           simplify_cast(cast, "(u8)"), i + 1);
1382       else
1383         snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1384           cast, offset & 3, i + 1);
1385       break;
1386
1387     case OPLM_WORD:
1388       if (is_lea)
1389         ferr(po, "lea/word to arg?\n");
1390       if (offset & 1) {
1391         unaligned = 1;
1392         if (!is_src) {
1393           if (offset & 2)
1394             ferr(po, "problematic arg store\n");
1395           snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1396             simplify_cast(cast, "*(u16 *)"), i + 1);
1397         }
1398         else
1399           ferr(po, "unaligned arg word load\n");
1400       }
1401       else if (is_src && (offset & 2) == 0)
1402         snprintf(buf, buf_size, "%sa%d",
1403           simplify_cast(cast, "(u16)"), i + 1);
1404       else
1405         snprintf(buf, buf_size, "%s%sWORD(a%d)",
1406           cast, (offset & 2) ? "HI" : "LO", i + 1);
1407       break;
1408
1409     case OPLM_DWORD:
1410       if (cast[0])
1411         prefix = cast;
1412       else if (is_src)
1413         prefix = "(u32)";
1414
1415       if (offset & 3) {
1416         unaligned = 1;
1417         if (is_lea)
1418           snprintf(buf, buf_size, "(u32)&a%d + %d",
1419             i + 1, offset & 3);
1420         else if (!is_src)
1421           ferr(po, "unaligned arg store\n");
1422         else {
1423           // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1424           snprintf(buf, buf_size, "%s(a%d >> %d)",
1425             prefix, i + 1, (offset & 3) * 8);
1426         }
1427       }
1428       else {
1429         snprintf(buf, buf_size, "%s%sa%d",
1430           prefix, is_lea ? "&" : "", i + 1);
1431       }
1432       break;
1433
1434     default:
1435       ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1436     }
1437
1438     if (unaligned)
1439       snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1440
1441     // common problem
1442     guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1443     if (tmp_lmod != OPLM_DWORD
1444       && (unaligned || (!is_src && tmp_lmod < popr->lmod)))
1445     {
1446       ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1447         i + 1, offset, g_func_pp->arg[i].type.name);
1448     }
1449     // can't check this because msvc likes to reuse
1450     // arg space for scratch..
1451     //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1452     //  ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1453   }
1454   else
1455   {
1456     if (g_stack_fsz == 0)
1457       ferr(po, "stack var access without stackframe\n");
1458     g_stack_frame_used = 1;
1459
1460     sf_ofs = g_stack_fsz + offset;
1461     lim = (ofs_reg[0] != 0) ? -4 : 0;
1462     if (offset > 0 || sf_ofs < lim)
1463       ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1464
1465     if (is_lea)
1466       prefix = "(u32)&";
1467     else
1468       prefix = cast;
1469
1470     switch (popr->lmod)
1471     {
1472     case OPLM_BYTE:
1473       snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1474         prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1475       break;
1476
1477     case OPLM_WORD:
1478       if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1479         // known unaligned or possibly unaligned
1480         strcat(g_comment, " unaligned");
1481         if (prefix[0] == 0)
1482           prefix = "*(u16 *)&";
1483         snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1484           prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1485         break;
1486       }
1487       snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1488       break;
1489
1490     case OPLM_DWORD:
1491       if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1492         // known unaligned or possibly unaligned
1493         strcat(g_comment, " unaligned");
1494         if (prefix[0] == 0)
1495           prefix = "*(u32 *)&";
1496         snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1497           prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1498         break;
1499       }
1500       snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1501       break;
1502
1503     default:
1504       ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1505     }
1506   }
1507 }
1508
1509 static void check_func_pp(struct parsed_op *po,
1510   const struct parsed_proto *pp, const char *pfx)
1511 {
1512   char buf[256];
1513
1514   if (pp->argc_reg != 0) {
1515     if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1516       pp_print(buf, sizeof(buf), pp);
1517       ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1518     }
1519     if (pp->argc_stack > 0 && pp->argc_reg != 2)
1520       ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1521         pfx, pp->argc_reg, pp->argc_stack);
1522   }
1523 }
1524
1525 static const char *check_label_read_ref(struct parsed_op *po,
1526   const char *name)
1527 {
1528   const struct parsed_proto *pp;
1529
1530   pp = proto_parse(g_fhdr, name, 0);
1531   if (pp == NULL)
1532     ferr(po, "proto_parse failed for ref '%s'\n", name);
1533
1534   if (pp->is_func)
1535     check_func_pp(po, pp, "ref");
1536
1537   return pp->name;
1538 }
1539
1540 static char *out_src_opr(char *buf, size_t buf_size,
1541   struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1542   int is_lea)
1543 {
1544   char tmp1[256], tmp2[256];
1545   char expr[256];
1546   const char *name;
1547   char *p;
1548   int ret;
1549
1550   if (cast == NULL)
1551     cast = "";
1552
1553   switch (popr->type) {
1554   case OPT_REG:
1555     if (is_lea)
1556       ferr(po, "lea from reg?\n");
1557
1558     switch (popr->lmod) {
1559     case OPLM_DWORD:
1560       snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1561       break;
1562     case OPLM_WORD:
1563       snprintf(buf, buf_size, "%s%s",
1564         simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1565       break;
1566     case OPLM_BYTE:
1567       if (popr->name[1] == 'h') // XXX..
1568         snprintf(buf, buf_size, "%s(%s >> 8)",
1569           simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1570       else
1571         snprintf(buf, buf_size, "%s%s",
1572           simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1573       break;
1574     default:
1575       ferr(po, "invalid src lmod: %d\n", popr->lmod);
1576     }
1577     break;
1578
1579   case OPT_REGMEM:
1580     if (is_stack_access(po, popr)) {
1581       stack_frame_access(po, popr, buf, buf_size,
1582         popr->name, cast, 1, is_lea);
1583       break;
1584     }
1585
1586     strcpy(expr, popr->name);
1587     if (strchr(expr, '[')) {
1588       // special case: '[' can only be left for label[reg] form
1589       ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1590       if (ret != 2)
1591         ferr(po, "parse failure for '%s'\n", expr);
1592       if (tmp1[0] == '(') {
1593         // (off_4FFF50+3)[eax]
1594         p = strchr(tmp1 + 1, ')');
1595         if (p == NULL || p[1] != 0)
1596           ferr(po, "parse failure (2) for '%s'\n", expr);
1597         *p = 0;
1598         memmove(tmp1, tmp1 + 1, strlen(tmp1));
1599       }
1600       snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1601     }
1602
1603     // XXX: do we need more parsing?
1604     if (is_lea) {
1605       snprintf(buf, buf_size, "%s", expr);
1606       break;
1607     }
1608
1609     snprintf(buf, buf_size, "%s(%s)",
1610       simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1611     break;
1612
1613   case OPT_LABEL:
1614     name = check_label_read_ref(po, popr->name);
1615     if (cast[0] == 0 && popr->is_ptr)
1616       cast = "(u32)";
1617
1618     if (is_lea)
1619       snprintf(buf, buf_size, "(u32)&%s", name);
1620     else if (popr->size_lt)
1621       snprintf(buf, buf_size, "%s%s%s%s", cast,
1622         lmod_cast_u_ptr(po, popr->lmod),
1623         popr->is_array ? "" : "&", name);
1624     else
1625       snprintf(buf, buf_size, "%s%s%s", cast, name,
1626         popr->is_array ? "[0]" : "");
1627     break;
1628
1629   case OPT_OFFSET:
1630     name = check_label_read_ref(po, popr->name);
1631     if (cast[0] == 0)
1632       cast = "(u32)";
1633     if (is_lea)
1634       ferr(po, "lea an offset?\n");
1635     snprintf(buf, buf_size, "%s&%s", cast, name);
1636     break;
1637
1638   case OPT_CONST:
1639     if (is_lea)
1640       ferr(po, "lea from const?\n");
1641
1642     printf_number(tmp1, sizeof(tmp1), popr->val);
1643     if (popr->val == 0 && strchr(cast, '*'))
1644       snprintf(buf, buf_size, "NULL");
1645     else
1646       snprintf(buf, buf_size, "%s%s",
1647         simplify_cast_num(cast, popr->val), tmp1);
1648     break;
1649
1650   default:
1651     ferr(po, "invalid src type: %d\n", popr->type);
1652   }
1653
1654   return buf;
1655 }
1656
1657 // note: may set is_ptr (we find that out late for ebp frame..)
1658 static char *out_dst_opr(char *buf, size_t buf_size,
1659         struct parsed_op *po, struct parsed_opr *popr)
1660 {
1661   switch (popr->type) {
1662   case OPT_REG:
1663     switch (popr->lmod) {
1664     case OPLM_DWORD:
1665       snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1666       break;
1667     case OPLM_WORD:
1668       // ugh..
1669       snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1670       break;
1671     case OPLM_BYTE:
1672       // ugh..
1673       if (popr->name[1] == 'h') // XXX..
1674         snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1675       else
1676         snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1677       break;
1678     default:
1679       ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1680     }
1681     break;
1682
1683   case OPT_REGMEM:
1684     if (is_stack_access(po, popr)) {
1685       stack_frame_access(po, popr, buf, buf_size,
1686         popr->name, "", 0, 0);
1687       break;
1688     }
1689
1690     return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1691
1692   case OPT_LABEL:
1693     if (popr->size_mismatch)
1694       snprintf(buf, buf_size, "%s%s%s",
1695         lmod_cast_u_ptr(po, popr->lmod),
1696         popr->is_array ? "" : "&", popr->name);
1697     else
1698       snprintf(buf, buf_size, "%s%s", popr->name,
1699         popr->is_array ? "[0]" : "");
1700     break;
1701
1702   default:
1703     ferr(po, "invalid dst type: %d\n", popr->type);
1704   }
1705
1706   return buf;
1707 }
1708
1709 static char *out_src_opr_u32(char *buf, size_t buf_size,
1710         struct parsed_op *po, struct parsed_opr *popr)
1711 {
1712   return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1713 }
1714
1715 static enum parsed_flag_op split_cond(struct parsed_op *po,
1716   enum op_op op, int *is_inv)
1717 {
1718   *is_inv = 0;
1719
1720   switch (op) {
1721   case OP_JO:
1722     return PFO_O;
1723   case OP_JC:
1724     return PFO_C;
1725   case OP_JZ:
1726     return PFO_Z;
1727   case OP_JBE:
1728     return PFO_BE;
1729   case OP_JS:
1730     return PFO_S;
1731   case OP_JP:
1732     return PFO_P;
1733   case OP_JL:
1734     return PFO_L;
1735   case OP_JLE:
1736     return PFO_LE;
1737
1738   case OP_JNO:
1739     *is_inv = 1;
1740     return PFO_O;
1741   case OP_JNC:
1742     *is_inv = 1;
1743     return PFO_C;
1744   case OP_JNZ:
1745     *is_inv = 1;
1746     return PFO_Z;
1747   case OP_JA:
1748     *is_inv = 1;
1749     return PFO_BE;
1750   case OP_JNS:
1751     *is_inv = 1;
1752     return PFO_S;
1753   case OP_JNP:
1754     *is_inv = 1;
1755     return PFO_P;
1756   case OP_JGE:
1757     *is_inv = 1;
1758     return PFO_L;
1759   case OP_JG:
1760     *is_inv = 1;
1761     return PFO_LE;
1762
1763   case OP_RCL:
1764   case OP_RCR:
1765   case OP_ADC:
1766   case OP_SBB:
1767     return PFO_C;
1768
1769   default:
1770     ferr(po, "split_cond: bad op %d\n", op);
1771     return -1;
1772   }
1773 }
1774
1775 static void out_test_for_cc(char *buf, size_t buf_size,
1776   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1777   enum opr_lenmod lmod, const char *expr)
1778 {
1779   const char *cast, *scast;
1780
1781   cast = lmod_cast_u(po, lmod);
1782   scast = lmod_cast_s(po, lmod);
1783
1784   switch (pfo) {
1785   case PFO_Z:
1786   case PFO_BE: // CF=1||ZF=1; CF=0
1787     snprintf(buf, buf_size, "(%s%s %s 0)",
1788       cast, expr, is_inv ? "!=" : "==");
1789     break;
1790
1791   case PFO_S:
1792   case PFO_L: // SF!=OF; OF=0
1793     snprintf(buf, buf_size, "(%s%s %s 0)",
1794       scast, expr, is_inv ? ">=" : "<");
1795     break;
1796
1797   case PFO_LE: // ZF=1||SF!=OF; OF=0
1798     snprintf(buf, buf_size, "(%s%s %s 0)",
1799       scast, expr, is_inv ? ">" : "<=");
1800     break;
1801
1802   default:
1803     ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1804   }
1805 }
1806
1807 static void out_cmp_for_cc(char *buf, size_t buf_size,
1808   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1809 {
1810   const char *cast, *scast, *cast_use;
1811   char buf1[256], buf2[256];
1812   enum opr_lenmod lmod;
1813
1814   if (po->operand[0].lmod != po->operand[1].lmod)
1815     ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1816       po->operand[0].lmod, po->operand[1].lmod);
1817   lmod = po->operand[0].lmod;
1818
1819   cast = lmod_cast_u(po, lmod);
1820   scast = lmod_cast_s(po, lmod);
1821
1822   switch (pfo) {
1823   case PFO_C:
1824   case PFO_Z:
1825   case PFO_BE: // !a
1826     cast_use = cast;
1827     break;
1828
1829   case PFO_S:
1830   case PFO_L: // !ge
1831   case PFO_LE:
1832     cast_use = scast;
1833     break;
1834
1835   default:
1836     ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1837   }
1838
1839   out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1840   out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1841
1842   switch (pfo) {
1843   case PFO_C:
1844     // note: must be unsigned compare
1845     snprintf(buf, buf_size, "(%s %s %s)",
1846       buf1, is_inv ? ">=" : "<", buf2);
1847     break;
1848
1849   case PFO_Z:
1850     snprintf(buf, buf_size, "(%s %s %s)",
1851       buf1, is_inv ? "!=" : "==", buf2);
1852     break;
1853
1854   case PFO_BE: // !a
1855     // note: must be unsigned compare
1856     snprintf(buf, buf_size, "(%s %s %s)",
1857       buf1, is_inv ? ">" : "<=", buf2);
1858
1859     // annoying case
1860     if (is_inv && lmod == OPLM_BYTE
1861       && po->operand[1].type == OPT_CONST
1862       && po->operand[1].val == 0xff)
1863     {
1864       snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1865       snprintf(buf, buf_size, "(0)");
1866     }
1867     break;
1868
1869   // note: must be signed compare
1870   case PFO_S:
1871     snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1872       scast, buf1, buf2, is_inv ? ">=" : "<");
1873     break;
1874
1875   case PFO_L: // !ge
1876     snprintf(buf, buf_size, "(%s %s %s)",
1877       buf1, is_inv ? ">=" : "<", buf2);
1878     break;
1879
1880   case PFO_LE:
1881     snprintf(buf, buf_size, "(%s %s %s)",
1882       buf1, is_inv ? ">" : "<=", buf2);
1883     break;
1884
1885   default:
1886     break;
1887   }
1888 }
1889
1890 static void out_cmp_test(char *buf, size_t buf_size,
1891   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1892 {
1893   char buf1[256], buf2[256], buf3[256];
1894
1895   if (po->op == OP_TEST) {
1896     if (IS(opr_name(po, 0), opr_name(po, 1))) {
1897       out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1898     }
1899     else {
1900       out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1901       out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1902       snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1903     }
1904     out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1905       po->operand[0].lmod, buf3);
1906   }
1907   else if (po->op == OP_CMP) {
1908     out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1909   }
1910   else
1911     ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1912 }
1913
1914 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1915         struct parsed_opr *popr2)
1916 {
1917   if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1918     ferr(po, "missing lmod for both operands\n");
1919
1920   if (popr1->lmod == OPLM_UNSPEC)
1921     popr1->lmod = popr2->lmod;
1922   else if (popr2->lmod == OPLM_UNSPEC)
1923     popr2->lmod = popr1->lmod;
1924   else if (popr1->lmod != popr2->lmod) {
1925     if (popr1->type_from_var) {
1926       popr1->size_mismatch = 1;
1927       if (popr1->lmod < popr2->lmod)
1928         popr1->size_lt = 1;
1929       popr1->lmod = popr2->lmod;
1930     }
1931     else if (popr2->type_from_var) {
1932       popr2->size_mismatch = 1;
1933       if (popr2->lmod < popr1->lmod)
1934         popr2->size_lt = 1;
1935       popr2->lmod = popr1->lmod;
1936     }
1937     else
1938       ferr(po, "conflicting lmods: %d vs %d\n",
1939         popr1->lmod, popr2->lmod);
1940   }
1941 }
1942
1943 static const char *op_to_c(struct parsed_op *po)
1944 {
1945   switch (po->op)
1946   {
1947     case OP_ADD:
1948     case OP_ADC:
1949       return "+";
1950     case OP_SUB:
1951     case OP_SBB:
1952       return "-";
1953     case OP_AND:
1954       return "&";
1955     case OP_OR:
1956       return "|";
1957     case OP_XOR:
1958       return "^";
1959     case OP_SHL:
1960       return "<<";
1961     case OP_SHR:
1962       return ">>";
1963     case OP_MUL:
1964     case OP_IMUL:
1965       return "*";
1966     default:
1967       ferr(po, "op_to_c was supplied with %d\n", po->op);
1968   }
1969 }
1970
1971 static void op_set_clear_flag(struct parsed_op *po,
1972   enum op_flags flag_set, enum op_flags flag_clear)
1973 {
1974   po->flags |= flag_set;
1975   po->flags &= ~flag_clear;
1976 }
1977
1978 // last op in stream - unconditional branch or ret
1979 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1980   || ((ops[_i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP \
1981       && ops[_i].op != OP_CALL))
1982
1983 static int scan_for_pop(int i, int opcnt, const char *reg,
1984   int magic, int depth, int *maxdepth, int do_flags)
1985 {
1986   const struct parsed_proto *pp;
1987   struct parsed_op *po;
1988   int ret = 0;
1989   int j;
1990
1991   for (; i < opcnt; i++) {
1992     po = &ops[i];
1993     if (po->cc_scratch == magic)
1994       break; // already checked
1995     po->cc_scratch = magic;
1996
1997     if (po->flags & OPF_TAIL) {
1998       if (po->op == OP_CALL) {
1999         pp = proto_parse(g_fhdr, po->operand[0].name, 0);
2000         if (pp != NULL && pp->is_noreturn)
2001           // no stack cleanup for noreturn
2002           return ret;
2003       }
2004       return -1; // deadend
2005     }
2006
2007     if ((po->flags & OPF_RMD)
2008         || (po->op == OP_PUSH && po->argnum != 0)) // arg push
2009       continue;
2010
2011     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2012       if (po->btj != NULL) {
2013         // jumptable
2014         for (j = 0; j < po->btj->count; j++) {
2015           ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
2016                    depth, maxdepth, do_flags);
2017           if (ret < 0)
2018             return ret; // dead end
2019         }
2020         return ret;
2021       }
2022
2023       if (po->bt_i < 0) {
2024         ferr(po, "dead branch\n");
2025         return -1;
2026       }
2027
2028       if (po->flags & OPF_CJMP) {
2029         ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
2030                  depth, maxdepth, do_flags);
2031         if (ret < 0)
2032           return ret; // dead end
2033       }
2034       else {
2035         i = po->bt_i - 1;
2036       }
2037       continue;
2038     }
2039
2040     if ((po->op == OP_POP || po->op == OP_PUSH)
2041         && po->operand[0].type == OPT_REG
2042         && IS(po->operand[0].name, reg))
2043     {
2044       if (po->op == OP_PUSH && !(po->flags & OPF_FARG)) {
2045         depth++;
2046         if (depth > *maxdepth)
2047           *maxdepth = depth;
2048         if (do_flags)
2049           op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2050       }
2051       else if (po->op == OP_POP) {
2052         if (depth == 0) {
2053           if (do_flags)
2054             op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2055           return 1;
2056         }
2057         else {
2058           depth--;
2059           if (depth < 0) // should not happen
2060             ferr(po, "fail with depth\n");
2061           if (do_flags)
2062             op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2063         }
2064       }
2065     }
2066   }
2067
2068   return ret;
2069 }
2070
2071 // scan for pop starting from 'ret' op (all paths)
2072 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2073   int flag_set)
2074 {
2075   int found = 0;
2076   int j;
2077
2078   for (; i < opcnt; i++) {
2079     if (!(ops[i].flags & OPF_TAIL))
2080       continue;
2081
2082     for (j = i - 1; j >= 0; j--) {
2083       if (ops[j].flags & OPF_RMD)
2084         continue;
2085       if (ops[j].flags & OPF_JMP)
2086         return -1;
2087
2088       if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2089           && IS(ops[j].operand[0].name, reg))
2090       {
2091         found = 1;
2092         ops[j].flags |= flag_set;
2093         break;
2094       }
2095
2096       if (g_labels[j][0] != 0)
2097         return -1;
2098     }
2099   }
2100
2101   return found ? 0 : -1;
2102 }
2103
2104 static void scan_propagate_df(int i, int opcnt)
2105 {
2106   struct parsed_op *po = &ops[i];
2107   int j;
2108
2109   for (; i < opcnt; i++) {
2110     po = &ops[i];
2111     if (po->flags & OPF_DF)
2112       return; // already resolved
2113     po->flags |= OPF_DF;
2114
2115     if (po->op == OP_CALL)
2116       ferr(po, "call with DF set?\n");
2117
2118     if (po->flags & OPF_JMP) {
2119       if (po->btj != NULL) {
2120         // jumptable
2121         for (j = 0; j < po->btj->count; j++)
2122           scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2123         return;
2124       }
2125
2126       if (po->bt_i < 0) {
2127         ferr(po, "dead branch\n");
2128         return;
2129       }
2130
2131       if (po->flags & OPF_CJMP)
2132         scan_propagate_df(po->bt_i, opcnt);
2133       else
2134         i = po->bt_i - 1;
2135       continue;
2136     }
2137
2138     if (po->flags & OPF_TAIL)
2139       break;
2140
2141     if (po->op == OP_CLD) {
2142       po->flags |= OPF_RMD;
2143       return;
2144     }
2145   }
2146
2147   ferr(po, "missing DF clear?\n");
2148 }
2149
2150 // is operand 'opr' modified by parsed_op 'po'?
2151 static int is_opr_modified(const struct parsed_opr *opr,
2152   const struct parsed_op *po)
2153 {
2154   int mask;
2155
2156   if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2157     return 0;
2158
2159   if (opr->type == OPT_REG) {
2160     if (po->op == OP_CALL) {
2161       mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2162       if ((1 << opr->reg) & mask)
2163         return 1;
2164       else
2165         return 0;
2166     }
2167
2168     if (po->operand[0].type == OPT_REG) {
2169       if (po->regmask_dst & (1 << opr->reg))
2170         return 1;
2171       else
2172         return 0;
2173     }
2174   }
2175
2176   return IS(po->operand[0].name, opr->name);
2177 }
2178
2179 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2180 static int is_any_opr_modified(const struct parsed_op *po_test,
2181   const struct parsed_op *po, int c_mode)
2182 {
2183   int mask;
2184   int i;
2185
2186   if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2187     return 0;
2188
2189   if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2190     return 0;
2191
2192   if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2193     return 1;
2194
2195   // in reality, it can wreck any register, but in decompiled C
2196   // version it can only overwrite eax or edx:eax
2197   mask = (1 << xAX) | (1 << xDX);
2198   if (!c_mode)
2199     mask |= 1 << xCX;
2200
2201   if (po->op == OP_CALL
2202    && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2203     return 1;
2204
2205   for (i = 0; i < po_test->operand_cnt; i++)
2206     if (IS(po_test->operand[i].name, po->operand[0].name))
2207       return 1;
2208
2209   return 0;
2210 }
2211
2212 // scan for any po_test operand modification in range given
2213 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2214   int c_mode)
2215 {
2216   if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2217     return -1;
2218
2219   for (; i < opcnt; i++) {
2220     if (is_any_opr_modified(po_test, &ops[i], c_mode))
2221       return i;
2222   }
2223
2224   return -1;
2225 }
2226
2227 // scan for po_test operand[0] modification in range given
2228 static int scan_for_mod_opr0(struct parsed_op *po_test,
2229   int i, int opcnt)
2230 {
2231   for (; i < opcnt; i++) {
2232     if (is_opr_modified(&po_test->operand[0], &ops[i]))
2233       return i;
2234   }
2235
2236   return -1;
2237 }
2238
2239 static int scan_for_flag_set(int i, int magic, int *branched,
2240   int *setters, int *setter_cnt)
2241 {
2242   struct label_ref *lr;
2243   int ret;
2244
2245   while (i >= 0) {
2246     if (ops[i].cc_scratch == magic) {
2247       ferr(&ops[i], "%s looped\n", __func__);
2248       return -1;
2249     }
2250     ops[i].cc_scratch = magic;
2251
2252     if (g_labels[i][0] != 0) {
2253       *branched = 1;
2254
2255       lr = &g_label_refs[i];
2256       for (; lr->next; lr = lr->next) {
2257         ret = scan_for_flag_set(lr->i, magic,
2258                 branched, setters, setter_cnt);
2259         if (ret < 0)
2260           return ret;
2261       }
2262
2263       if (i > 0 && LAST_OP(i - 1)) {
2264         i = lr->i;
2265         continue;
2266       }
2267       ret = scan_for_flag_set(lr->i, magic,
2268               branched, setters, setter_cnt);
2269       if (ret < 0)
2270         return ret;
2271     }
2272     i--;
2273
2274     if (ops[i].flags & OPF_FLAGS) {
2275       setters[*setter_cnt] = i;
2276       (*setter_cnt)++;
2277       return 0;
2278     }
2279
2280     if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2281       return -1;
2282   }
2283
2284   return -1;
2285 }
2286
2287 // scan back for cdq, if anything modifies edx, fail
2288 static int scan_for_cdq_edx(int i)
2289 {
2290   while (i >= 0) {
2291     if (g_labels[i][0] != 0) {
2292       if (g_label_refs[i].next != NULL)
2293         return -1;
2294       if (i > 0 && LAST_OP(i - 1)) {
2295         i = g_label_refs[i].i;
2296         continue;
2297       }
2298       return -1;
2299     }
2300     i--;
2301
2302     if (ops[i].op == OP_CDQ)
2303       return i;
2304
2305     if (ops[i].regmask_dst & (1 << xDX))
2306       return -1;
2307   }
2308
2309   return -1;
2310 }
2311
2312 static int scan_for_reg_clear(int i, int reg)
2313 {
2314   while (i >= 0) {
2315     if (g_labels[i][0] != 0) {
2316       if (g_label_refs[i].next != NULL)
2317         return -1;
2318       if (i > 0 && LAST_OP(i - 1)) {
2319         i = g_label_refs[i].i;
2320         continue;
2321       }
2322       return -1;
2323     }
2324     i--;
2325
2326     if (ops[i].op == OP_XOR
2327      && ops[i].operand[0].lmod == OPLM_DWORD
2328      && ops[i].operand[0].reg == ops[i].operand[1].reg
2329      && ops[i].operand[0].reg == reg)
2330       return i;
2331
2332     if (ops[i].regmask_dst & (1 << reg))
2333       return -1;
2334   }
2335
2336   return -1;
2337 }
2338
2339 // scan for positive, constant esp adjust
2340 static int scan_for_esp_adjust(int i, int opcnt, int *adj,
2341   int *multipath)
2342 {
2343   const struct parsed_proto *pp;
2344   struct parsed_op *po;
2345   int first_pop = -1;
2346
2347   *adj = *multipath = 0;
2348
2349   for (; i < opcnt; i++) {
2350     po = &ops[i];
2351
2352     if (g_labels[i][0] != 0)
2353       *multipath = 1;
2354
2355     if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2356       if (po->operand[1].type != OPT_CONST)
2357         ferr(&ops[i], "non-const esp adjust?\n");
2358       *adj += po->operand[1].val;
2359       if (*adj & 3)
2360         ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2361       return i;
2362     }
2363     else if (po->op == OP_PUSH && !(po->flags & OPF_RMD)) {
2364       //if (first_pop == -1)
2365       //  first_pop = -2; // none
2366       *adj -= lmod_bytes(po, po->operand[0].lmod);
2367     }
2368     else if (po->op == OP_POP && !(po->flags & OPF_RMD)) {
2369       // seems like msvc only uses 'pop ecx' for stack realignment..
2370       if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2371         break;
2372       if (first_pop == -1 && *adj >= 0)
2373         first_pop = i;
2374       *adj += lmod_bytes(po, po->operand[0].lmod);
2375     }
2376     else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2377       if (po->op == OP_JMP && po->btj == NULL) {
2378         i = po->bt_i - 1;
2379         continue;
2380       }
2381       if (po->op != OP_CALL)
2382         break;
2383       if (po->operand[0].type != OPT_LABEL)
2384         break;
2385       pp = po->datap;
2386       if (pp != NULL && pp->is_stdcall)
2387         break;
2388     }
2389   }
2390
2391   if (first_pop >= 0) {
2392     // probably 'pop ecx' was used..
2393     return first_pop;
2394   }
2395
2396   return -1;
2397 }
2398
2399 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2400 {
2401   struct parsed_op *po;
2402   int j;
2403
2404   if (i < 0)
2405     ferr(ops, "%s: followed bad branch?\n", __func__);
2406
2407   for (; i < opcnt; i++) {
2408     po = &ops[i];
2409     if (po->cc_scratch == magic)
2410       return;
2411     po->cc_scratch = magic;
2412     po->flags |= flags;
2413
2414     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2415       if (po->btj != NULL) {
2416         // jumptable
2417         for (j = 0; j < po->btj->count; j++)
2418           scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2419         return;
2420       }
2421
2422       scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2423       if (!(po->flags & OPF_CJMP))
2424         return;
2425     }
2426     if (po->flags & OPF_TAIL)
2427       return;
2428   }
2429 }
2430
2431 static const struct parsed_proto *try_recover_pp(
2432   struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2433 {
2434   const struct parsed_proto *pp = NULL;
2435   char buf[256];
2436   char *p;
2437
2438   // maybe an arg of g_func?
2439   if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2440   {
2441     char ofs_reg[16] = { 0, };
2442     int arg, arg_s, arg_i;
2443     int stack_ra = 0;
2444     int offset = 0;
2445
2446     parse_stack_access(po, opr->name, ofs_reg,
2447       &offset, &stack_ra, NULL, 0);
2448     if (ofs_reg[0] != 0)
2449       ferr(po, "offset reg on arg access?\n");
2450     if (offset <= stack_ra) {
2451       // search who set the stack var instead
2452       if (search_instead != NULL)
2453         *search_instead = 1;
2454       return NULL;
2455     }
2456
2457     arg_i = (offset - stack_ra - 4) / 4;
2458     for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2459       if (g_func_pp->arg[arg].reg != NULL)
2460         continue;
2461       if (arg_s == arg_i)
2462         break;
2463       arg_s++;
2464     }
2465     if (arg == g_func_pp->argc)
2466       ferr(po, "stack arg %d not in prototype?\n", arg_i);
2467
2468     pp = g_func_pp->arg[arg].fptr;
2469     if (pp == NULL)
2470       ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2471     check_func_pp(po, pp, "icall arg");
2472   }
2473   else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2474     // label[index]
2475     p = strchr(opr->name + 1, '[');
2476     memcpy(buf, opr->name, p - opr->name);
2477     buf[p - opr->name] = 0;
2478     pp = proto_parse(g_fhdr, buf, 0);
2479   }
2480   else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2481     pp = proto_parse(g_fhdr, opr->name, 0);
2482     if (pp == NULL)
2483       ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2484     check_func_pp(po, pp, "reg-fptr ref");
2485   }
2486
2487   return pp;
2488 }
2489
2490 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2491   int magic, const struct parsed_proto **pp_found, int *multi)
2492 {
2493   const struct parsed_proto *pp = NULL;
2494   struct parsed_op *po;
2495   struct label_ref *lr;
2496
2497   ops[i].cc_scratch = magic;
2498
2499   while (1) {
2500     if (g_labels[i][0] != 0) {
2501       lr = &g_label_refs[i];
2502       for (; lr != NULL; lr = lr->next)
2503         scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2504       if (i > 0 && LAST_OP(i - 1))
2505         return;
2506     }
2507
2508     i--;
2509     if (i < 0)
2510       break;
2511
2512     if (ops[i].cc_scratch == magic)
2513       return;
2514     ops[i].cc_scratch = magic;
2515
2516     if (!(ops[i].flags & OPF_DATA))
2517       continue;
2518     if (!is_opr_modified(opr, &ops[i]))
2519       continue;
2520     if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2521       // most probably trashed by some processing
2522       *pp_found = NULL;
2523       return;
2524     }
2525
2526     opr = &ops[i].operand[1];
2527     if (opr->type != OPT_REG)
2528       break;
2529   }
2530
2531   po = (i >= 0) ? &ops[i] : ops;
2532
2533   if (i < 0) {
2534     // reached the top - can only be an arg-reg
2535     if (opr->type != OPT_REG)
2536       return;
2537
2538     for (i = 0; i < g_func_pp->argc; i++) {
2539       if (g_func_pp->arg[i].reg == NULL)
2540         continue;
2541       if (IS(opr->name, g_func_pp->arg[i].reg))
2542         break;
2543     }
2544     if (i == g_func_pp->argc)
2545       return;
2546     pp = g_func_pp->arg[i].fptr;
2547     if (pp == NULL)
2548       ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2549         i + 1, g_func_pp->arg[i].reg);
2550     check_func_pp(po, pp, "icall reg-arg");
2551   }
2552   else
2553     pp = try_recover_pp(po, opr, NULL);
2554
2555   if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2556     if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2557       || (*pp_found)->is_stdcall != pp->is_stdcall
2558       || (*pp_found)->is_fptr != pp->is_fptr
2559       || (*pp_found)->argc != pp->argc
2560       || (*pp_found)->argc_reg != pp->argc_reg
2561       || (*pp_found)->argc_stack != pp->argc_stack)
2562     {
2563       ferr(po, "icall: parsed_proto mismatch\n");
2564     }
2565     *multi = 1;
2566   }
2567   if (pp != NULL)
2568     *pp_found = pp;
2569 }
2570
2571 static const struct parsed_proto *resolve_icall(int i, int opcnt,
2572   int *multi_src)
2573 {
2574   const struct parsed_proto *pp = NULL;
2575   int search_advice = 0;
2576
2577   *multi_src = 0;
2578
2579   switch (ops[i].operand[0].type) {
2580   case OPT_REGMEM:
2581   case OPT_LABEL:
2582   case OPT_OFFSET:
2583     pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
2584     if (!search_advice)
2585       break;
2586     // fallthrough
2587   default:
2588     scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
2589       multi_src);
2590     break;
2591   }
2592
2593   return pp;
2594 }
2595
2596 static int try_resolve_const(int i, const struct parsed_opr *opr,
2597   int magic, unsigned int *val)
2598 {
2599   struct label_ref *lr;
2600   int ret = 0;
2601
2602   ops[i].cc_scratch = magic;
2603
2604   while (1) {
2605     if (g_labels[i][0] != 0) {
2606       lr = &g_label_refs[i];
2607       for (; lr != NULL; lr = lr->next)
2608         ret |= try_resolve_const(lr->i, opr, magic, val);
2609       if (i > 0 && LAST_OP(i - 1))
2610         return ret;
2611     }
2612
2613     i--;
2614     if (i < 0)
2615       return -1;
2616
2617     if (ops[i].cc_scratch == magic)
2618       return 0;
2619     ops[i].cc_scratch = magic;
2620
2621     if (!(ops[i].flags & OPF_DATA))
2622       continue;
2623     if (!is_opr_modified(opr, &ops[i]))
2624       continue;
2625     if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
2626       return -1;
2627
2628     *val = ops[i].operand[1].val;
2629     return 1;
2630   }
2631 }
2632
2633 static int collect_call_args_r(struct parsed_op *po, int i,
2634   struct parsed_proto *pp, int *regmask, int *save_arg_vars, int arg,
2635   int magic, int need_op_saving, int may_reuse)
2636 {
2637   struct parsed_proto *pp_tmp;
2638   struct label_ref *lr;
2639   int need_to_save_current;
2640   int ret = 0;
2641   int j;
2642
2643   if (i < 0) {
2644     ferr(po, "dead label encountered\n");
2645     return -1;
2646   }
2647
2648   for (; arg < pp->argc; arg++)
2649     if (pp->arg[arg].reg == NULL)
2650       break;
2651   magic = (magic & 0xffffff) | (arg << 24);
2652
2653   for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
2654   {
2655     if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2656       if (ops[j].cc_scratch != magic) {
2657         ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2658            pp->name);
2659         return -1;
2660       }
2661       // ok: have already been here
2662       return 0;
2663     }
2664     ops[j].cc_scratch = magic;
2665
2666     if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2667       lr = &g_label_refs[j];
2668       if (lr->next != NULL)
2669         need_op_saving = 1;
2670       for (; lr->next; lr = lr->next) {
2671         if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2672           may_reuse = 1;
2673         ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2674                 arg, magic, need_op_saving, may_reuse);
2675         if (ret < 0)
2676           return ret;
2677       }
2678
2679       if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2680         may_reuse = 1;
2681       if (j > 0 && LAST_OP(j - 1)) {
2682         // follow last branch in reverse
2683         j = lr->i;
2684         continue;
2685       }
2686       need_op_saving = 1;
2687       ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2688                arg, magic, need_op_saving, may_reuse);
2689       if (ret < 0)
2690         return ret;
2691     }
2692     j--;
2693
2694     if (ops[j].op == OP_CALL)
2695     {
2696       if (pp->is_unresolved)
2697         break;
2698
2699       pp_tmp = ops[j].datap;
2700       if (pp_tmp == NULL)
2701         ferr(po, "arg collect hit unparsed call '%s'\n",
2702           ops[j].operand[0].name);
2703       if (may_reuse && pp_tmp->argc_stack > 0)
2704         ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2705           arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2706     }
2707     else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2708       if (pp->is_unresolved)
2709         break;
2710
2711       ferr(po, "arg collect %d/%d hit esp adjust\n",
2712         arg, pp->argc);
2713     }
2714     else if (ops[j].op == OP_POP) {
2715       if (pp->is_unresolved)
2716         break;
2717
2718       ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2719     }
2720     else if (ops[j].flags & OPF_CJMP)
2721     {
2722       if (pp->is_unresolved)
2723         break;
2724
2725       may_reuse = 1;
2726     }
2727     else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2728     {
2729       if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
2730         break;
2731
2732       pp->arg[arg].datap = &ops[j];
2733       need_to_save_current = 0;
2734       if (!need_op_saving) {
2735         ret = scan_for_mod(&ops[j], j + 1, i, 1);
2736         need_to_save_current = (ret >= 0);
2737       }
2738       if (need_op_saving || need_to_save_current) {
2739         // mark this push as one that needs operand saving
2740         ops[j].flags &= ~OPF_RMD;
2741         if (ops[j].argnum == 0) {
2742           ops[j].argnum = arg + 1;
2743           *save_arg_vars |= 1 << arg;
2744         }
2745         else if (ops[j].argnum < arg + 1)
2746           ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2747             ops[j].argnum, arg + 1, pp->name);
2748       }
2749       else if (ops[j].argnum == 0)
2750         ops[j].flags |= OPF_RMD;
2751
2752       // some PUSHes are reused by different calls on other branches,
2753       // but that can't happen if we didn't branch, so they
2754       // can be removed from future searches (handles nested calls)
2755       if (!may_reuse)
2756         ops[j].flags |= OPF_FARG;
2757
2758       ops[j].flags &= ~OPF_RSAVE;
2759
2760       arg++;
2761       if (!pp->is_unresolved) {
2762         // next arg
2763         for (; arg < pp->argc; arg++)
2764           if (pp->arg[arg].reg == NULL)
2765             break;
2766       }
2767       magic = (magic & 0xffffff) | (arg << 24);
2768
2769       // tracking reg usage
2770       if (ops[j].operand[0].type == OPT_REG)
2771         *regmask |= 1 << ops[j].operand[0].reg;
2772     }
2773   }
2774
2775   if (arg < pp->argc) {
2776     ferr(po, "arg collect failed for '%s': %d/%d\n",
2777       pp->name, arg, pp->argc);
2778     return -1;
2779   }
2780
2781   return arg;
2782 }
2783
2784 static int collect_call_args(struct parsed_op *po, int i,
2785   struct parsed_proto *pp, int *regmask, int *save_arg_vars,
2786   int magic)
2787 {
2788   int ret;
2789   int a;
2790
2791   ret = collect_call_args_r(po, i, pp, regmask, save_arg_vars,
2792           0, magic, 0, 0);
2793   if (ret < 0)
2794     return ret;
2795
2796   if (pp->is_unresolved) {
2797     pp->argc += ret;
2798     pp->argc_stack += ret;
2799     for (a = 0; a < pp->argc; a++)
2800       if (pp->arg[a].type.name == NULL)
2801         pp->arg[a].type.name = strdup("int");
2802   }
2803
2804   return ret;
2805 }
2806
2807 // early check for tail call or branch back
2808 static int is_like_tailjmp(int j)
2809 {
2810   if (!(ops[j].flags & OPF_JMP))
2811     return 0;
2812
2813   if (ops[j].op == OP_JMP && !ops[j].operand[0].had_ds)
2814     // probably local branch back..
2815     return 1;
2816   if (ops[j].op == OP_CALL)
2817     // probably noreturn call..
2818     return 1;
2819
2820   return 0;
2821 }
2822
2823 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
2824 {
2825   int i;
2826
2827   for (i = 0; i < pp->argc; i++)
2828     if (pp->arg[i].reg == NULL)
2829       break;
2830
2831   if (pp->argc_stack)
2832     memmove(&pp->arg[i + 1], &pp->arg[i],
2833       sizeof(pp->arg[0]) * pp->argc_stack);
2834   memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
2835   pp->arg[i].reg = strdup(reg);
2836   pp->arg[i].type.name = strdup("int");
2837   pp->argc++;
2838   pp->argc_reg++;
2839 }
2840
2841 static void add_label_ref(struct label_ref *lr, int op_i)
2842 {
2843   struct label_ref *lr_new;
2844
2845   if (lr->i == -1) {
2846     lr->i = op_i;
2847     return;
2848   }
2849
2850   lr_new = calloc(1, sizeof(*lr_new));
2851   lr_new->i = op_i;
2852   lr_new->next = lr->next;
2853   lr->next = lr_new;
2854 }
2855
2856 static void output_std_flags(FILE *fout, struct parsed_op *po,
2857   int *pfomask, const char *dst_opr_text)
2858 {
2859   if (*pfomask & (1 << PFO_Z)) {
2860     fprintf(fout, "\n  cond_z = (%s%s == 0);",
2861       lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2862     *pfomask &= ~(1 << PFO_Z);
2863   }
2864   if (*pfomask & (1 << PFO_S)) {
2865     fprintf(fout, "\n  cond_s = (%s%s < 0);",
2866       lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2867     *pfomask &= ~(1 << PFO_S);
2868   }
2869 }
2870
2871 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
2872   int is_noreturn)
2873 {
2874   if (pp->is_fastcall)
2875     fprintf(fout, "__fastcall ");
2876   else if (pp->is_stdcall && pp->argc_reg == 0)
2877     fprintf(fout, "__stdcall ");
2878   if (pp->is_noreturn || is_noreturn)
2879     fprintf(fout, "noreturn ");
2880 }
2881
2882 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2883 {
2884   struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2885   struct parsed_opr *last_arith_dst = NULL;
2886   char buf1[256], buf2[256], buf3[256], cast[64];
2887   const struct parsed_proto *pp_c;
2888   struct parsed_proto *pp, *pp_tmp;
2889   struct parsed_data *pd;
2890   const char *tmpname;
2891   enum parsed_flag_op pfo;
2892   unsigned int uval;
2893   int save_arg_vars = 0;
2894   int cond_vars = 0;
2895   int need_tmp_var = 0;
2896   int need_tmp64 = 0;
2897   int had_decl = 0;
2898   int label_pending = 0;
2899   int regmask_save = 0;
2900   int regmask_arg = 0;
2901   int regmask_now = 0;
2902   int regmask_init = 0;
2903   int regmask = 0;
2904   int pfomask = 0;
2905   int found = 0;
2906   int depth = 0;
2907   int no_output;
2908   int i, j, l;
2909   int dummy;
2910   int arg;
2911   int reg;
2912   int ret;
2913
2914   g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2915   g_stack_frame_used = 0;
2916
2917   g_func_pp = proto_parse(fhdr, funcn, 0);
2918   if (g_func_pp == NULL)
2919     ferr(ops, "proto_parse failed for '%s'\n", funcn);
2920
2921   fprintf(fout, "%s ", g_func_pp->ret_type.name);
2922   output_pp_attrs(fout, g_func_pp, g_ida_func_attr & IDAFA_NORETURN);
2923   fprintf(fout, "%s(", g_func_pp->name);
2924
2925   for (i = 0; i < g_func_pp->argc; i++) {
2926     if (i > 0)
2927       fprintf(fout, ", ");
2928     if (g_func_pp->arg[i].fptr != NULL) {
2929       // func pointer..
2930       pp = g_func_pp->arg[i].fptr;
2931       fprintf(fout, "%s (", pp->ret_type.name);
2932       output_pp_attrs(fout, pp, 0);
2933       fprintf(fout, "*a%d)(", i + 1);
2934       for (j = 0; j < pp->argc; j++) {
2935         if (j > 0)
2936           fprintf(fout, ", ");
2937         if (pp->arg[j].fptr)
2938           ferr(ops, "nested fptr\n");
2939         fprintf(fout, "%s", pp->arg[j].type.name);
2940       }
2941       if (pp->is_vararg) {
2942         if (j > 0)
2943           fprintf(fout, ", ");
2944         fprintf(fout, "...");
2945       }
2946       fprintf(fout, ")");
2947     }
2948     else if (g_func_pp->arg[i].type.is_retreg) {
2949       fprintf(fout, "u32 *r_%s", g_func_pp->arg[i].reg);
2950     }
2951     else {
2952       fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2953     }
2954     if (g_func_pp->arg[i].reg != NULL) {
2955       reg = char_array_i(regs_r32,
2956               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2957       if (reg < 0)
2958         ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2959       regmask_arg |= 1 << reg;
2960     }
2961   }
2962   if (g_func_pp->is_vararg) {
2963     if (i > 0)
2964       fprintf(fout, ", ");
2965     fprintf(fout, "...");
2966   }
2967
2968   fprintf(fout, ")\n{\n");
2969
2970   // pass1:
2971   // - handle ebp/esp frame, remove ops related to it
2972   if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2973       && ops[1].op == OP_MOV
2974       && IS(opr_name(&ops[1], 0), "ebp")
2975       && IS(opr_name(&ops[1], 1), "esp"))
2976   {
2977     int ecx_push = 0;
2978
2979     g_bp_frame = 1;
2980     ops[0].flags |= OPF_RMD;
2981     ops[1].flags |= OPF_RMD;
2982     i = 2;
2983
2984     if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2985       g_stack_fsz = opr_const(&ops[2], 1);
2986       ops[2].flags |= OPF_RMD;
2987       i++;
2988     }
2989     else {
2990       // another way msvc builds stack frame..
2991       i = 2;
2992       while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2993         g_stack_fsz += 4;
2994         ops[i].flags |= OPF_RMD;
2995         ecx_push++;
2996         i++;
2997       }
2998       // and another way..
2999       if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
3000           && ops[i].operand[1].type == OPT_CONST
3001           && ops[i + 1].op == OP_CALL
3002           && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
3003       {
3004         g_stack_fsz += ops[i].operand[1].val;
3005         ops[i].flags |= OPF_RMD;
3006         i++;
3007         ops[i].flags |= OPF_RMD;
3008         i++;
3009       }
3010     }
3011
3012     found = 0;
3013     do {
3014       for (; i < opcnt; i++)
3015         if (ops[i].op == OP_RET)
3016           break;
3017       j = i - 1;
3018       if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3019         if (found && is_like_tailjmp(j))
3020             break;
3021         j--;
3022       }
3023
3024       if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
3025           || ops[j].op == OP_LEAVE)
3026       {
3027         ops[j].flags |= OPF_RMD;
3028       }
3029       else if (!(g_ida_func_attr & IDAFA_NORETURN))
3030         ferr(&ops[j], "'pop ebp' expected\n");
3031
3032       if (g_stack_fsz != 0) {
3033         if (ops[j - 1].op == OP_MOV
3034             && IS(opr_name(&ops[j - 1], 0), "esp")
3035             && IS(opr_name(&ops[j - 1], 1), "ebp"))
3036         {
3037           ops[j - 1].flags |= OPF_RMD;
3038         }
3039         else if (ops[j].op != OP_LEAVE
3040           && !(g_ida_func_attr & IDAFA_NORETURN))
3041         {
3042           ferr(&ops[j - 1], "esp restore expected\n");
3043         }
3044
3045         if (ecx_push && ops[j - 2].op == OP_POP
3046           && IS(opr_name(&ops[j - 2], 0), "ecx"))
3047         {
3048           ferr(&ops[j - 2], "unexpected ecx pop\n");
3049         }
3050       }
3051
3052       found = 1;
3053       i++;
3054     } while (i < opcnt);
3055   }
3056   else {
3057     for (i = 0; i < opcnt; i++) {
3058       if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
3059         break;
3060       if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
3061         && ops[i].operand[1].type == OPT_CONST)
3062       {
3063         g_sp_frame = 1;
3064         break;
3065       }
3066     }
3067
3068     found = 0;
3069     if (g_sp_frame)
3070     {
3071       g_stack_fsz = ops[i].operand[1].val;
3072       ops[i].flags |= OPF_RMD;
3073
3074       i++;
3075       do {
3076         for (; i < opcnt; i++)
3077           if (ops[i].op == OP_RET)
3078             break;
3079         j = i - 1;
3080         if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3081           if (found && is_like_tailjmp(j))
3082               break;
3083           j--;
3084         }
3085
3086         if (ops[j].op != OP_ADD
3087             || !IS(opr_name(&ops[j], 0), "esp")
3088             || ops[j].operand[1].type != OPT_CONST
3089             || ops[j].operand[1].val != g_stack_fsz)
3090           ferr(&ops[j], "'add esp' expected\n");
3091         ops[j].flags |= OPF_RMD;
3092
3093         found = 1;
3094         i++;
3095       } while (i < opcnt);
3096     }
3097   }
3098
3099   // pass2:
3100   // - parse calls with labels
3101   // - resolve all branches
3102   for (i = 0; i < opcnt; i++)
3103   {
3104     po = &ops[i];
3105     po->bt_i = -1;
3106     po->btj = NULL;
3107
3108     if (po->flags & OPF_RMD)
3109       continue;
3110
3111     if (po->op == OP_CALL) {
3112       pp = NULL;
3113
3114       if (po->operand[0].type == OPT_LABEL) {
3115         tmpname = opr_name(po, 0);
3116         if (IS_START(tmpname, "loc_"))
3117           ferr(po, "call to loc_*\n");
3118         pp_c = proto_parse(fhdr, tmpname, 0);
3119         if (pp_c == NULL)
3120           ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3121
3122         pp = proto_clone(pp_c);
3123         my_assert_not(pp, NULL);
3124       }
3125       else if (po->datap != NULL) {
3126         pp = calloc(1, sizeof(*pp));
3127         my_assert_not(pp, NULL);
3128
3129         ret = parse_protostr(po->datap, pp);
3130         if (ret < 0)
3131           ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3132         free(po->datap);
3133         po->datap = NULL;
3134       }
3135
3136       if (pp != NULL) {
3137         if (pp->is_fptr)
3138           check_func_pp(po, pp, "fptr var call");
3139         if (pp->is_noreturn)
3140           po->flags |= OPF_TAIL;
3141         po->datap = pp;
3142       }
3143       continue;
3144     }
3145
3146     if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3147       continue;
3148
3149     if (po->operand[0].type == OPT_REGMEM) {
3150       char *p = strchr(po->operand[0].name, '[');
3151       if (p == NULL)
3152         goto tailcall;
3153       ret = p - po->operand[0].name;
3154       strncpy(buf1, po->operand[0].name, ret);
3155       buf1[ret] = 0;
3156
3157       for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3158         if (IS(g_func_pd[j].label, buf1)) {
3159           pd = &g_func_pd[j];
3160           break;
3161         }
3162       }
3163       if (pd == NULL)
3164         //ferr(po, "label '%s' not parsed?\n", buf1);
3165         goto tailcall;
3166       if (pd->type != OPT_OFFSET)
3167         ferr(po, "label '%s' with non-offset data?\n", buf1);
3168
3169       // find all labels, link
3170       for (j = 0; j < pd->count; j++) {
3171         for (l = 0; l < opcnt; l++) {
3172           if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
3173             add_label_ref(&g_label_refs[l], i);
3174             pd->d[j].bt_i = l;
3175             break;
3176           }
3177         }
3178       }
3179
3180       po->btj = pd;
3181       continue;
3182     }
3183
3184     for (l = 0; l < opcnt; l++) {
3185       if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
3186         add_label_ref(&g_label_refs[l], i);
3187         po->bt_i = l;
3188         break;
3189       }
3190     }
3191
3192     if (po->bt_i != -1)
3193       continue;
3194
3195     if (po->operand[0].type == OPT_LABEL)
3196       // assume tail call
3197       goto tailcall;
3198
3199     ferr(po, "unhandled branch\n");
3200
3201 tailcall:
3202     po->op = OP_CALL;
3203     po->flags |= OPF_TAIL;
3204     if (i > 0 && ops[i - 1].op == OP_POP)
3205       po->flags |= OPF_ATAIL;
3206     i--; // reprocess
3207   }
3208
3209   // pass3:
3210   // - remove dead labels
3211   // - process calls
3212   for (i = 0; i < opcnt; i++)
3213   {
3214     if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
3215       g_labels[i][0] = 0;
3216
3217     po = &ops[i];
3218     if (po->flags & OPF_RMD)
3219       continue;
3220
3221     if (po->op == OP_CALL)
3222     {
3223       tmpname = opr_name(po, 0);
3224       pp = po->datap;
3225       if (pp == NULL)
3226       {
3227         // indirect call
3228         pp_c = resolve_icall(i, opcnt, &l);
3229         if (pp_c != NULL) {
3230           pp = proto_clone(pp_c);
3231           my_assert_not(pp, NULL);
3232           if (l)
3233             // not resolved just to single func
3234             pp->is_fptr = 1;
3235
3236           switch (po->operand[0].type) {
3237           case OPT_REG:
3238             // we resolved this call and no longer need the register
3239             po->regmask_src &= ~(1 << po->operand[0].reg);
3240             break;
3241           case OPT_REGMEM:
3242             pp->is_fptr = 1;
3243             break;
3244           default:
3245             break;
3246           }
3247         }
3248         if (pp == NULL) {
3249           pp = calloc(1, sizeof(*pp));
3250           my_assert_not(pp, NULL);
3251           pp->is_fptr = 1;
3252           ret = scan_for_esp_adjust(i + 1, opcnt, &j, &l);
3253           if (ret < 0) {
3254             if (!g_allow_regfunc)
3255               ferr(po, "non-__cdecl indirect call unhandled yet\n");
3256             pp->is_unresolved = 1;
3257             j = 0;
3258           }
3259           j /= 4;
3260           if (j > ARRAY_SIZE(pp->arg))
3261             ferr(po, "esp adjust too large: %d\n", j);
3262           pp->ret_type.name = strdup("int");
3263           pp->argc = pp->argc_stack = j;
3264           for (arg = 0; arg < pp->argc; arg++)
3265             pp->arg[arg].type.name = strdup("int");
3266         }
3267         po->datap = pp;
3268       }
3269
3270       // look for and make use of esp adjust
3271       ret = -1;
3272       if (!pp->is_stdcall && pp->argc_stack > 0)
3273         ret = scan_for_esp_adjust(i + 1, opcnt, &j, &l);
3274       if (ret >= 0) {
3275         if (pp->is_vararg) {
3276           if (j / 4 < pp->argc_stack)
3277             ferr(po, "esp adjust is too small: %x < %x\n",
3278               j, pp->argc_stack * 4);
3279           // modify pp to make it have varargs as normal args
3280           arg = pp->argc;
3281           pp->argc += j / 4 - pp->argc_stack;
3282           for (; arg < pp->argc; arg++) {
3283             pp->arg[arg].type.name = strdup("int");
3284             pp->argc_stack++;
3285           }
3286           if (pp->argc > ARRAY_SIZE(pp->arg))
3287             ferr(po, "too many args for '%s'\n", tmpname);
3288         }
3289         if (pp->argc_stack != j / 4)
3290           ferr(po, "stack tracking failed for '%s': %x %x\n",
3291             tmpname, pp->argc_stack * 4, j);
3292
3293         ops[ret].flags |= OPF_RMD;
3294         if (ops[ret].op == OP_POP && j > 4) {
3295           // deal with multi-pop stack adjust
3296           j = pp->argc_stack;
3297           while (ops[ret].op == OP_POP && j > 0 && ret < opcnt) {
3298             ops[ret].flags |= OPF_RMD;
3299             j--;
3300             ret++;
3301           }
3302         }
3303         else if (!l) {
3304           // a bit of a hack, but deals with use of
3305           // single adj for multiple calls
3306           ops[ret].operand[1].val -= j;
3307         }
3308       }
3309       else if (pp->is_vararg)
3310         ferr(po, "missing esp_adjust for vararg func '%s'\n",
3311           pp->name);
3312
3313       if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
3314         // since we know the args, collect them
3315         collect_call_args(po, i, pp, &regmask, &save_arg_vars,
3316           i + opcnt * 2);
3317       }
3318
3319       if (strstr(pp->ret_type.name, "int64"))
3320         need_tmp64 = 1;
3321     }
3322   }
3323
3324   // pass4:
3325   // - find POPs for PUSHes, rm both
3326   // - scan for STD/CLD, propagate DF
3327   // - scan for all used registers
3328   // - find flag set ops for their users
3329   // - do unreselved calls
3330   // - declare indirect functions
3331   for (i = 0; i < opcnt; i++) {
3332     po = &ops[i];
3333     if (po->flags & OPF_RMD)
3334       continue;
3335
3336     if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3337       reg = po->operand[0].reg;
3338       if (!(regmask & (1 << reg)))
3339         // not a reg save after all, rerun scan_for_pop
3340         po->flags &= ~OPF_RSAVE;
3341       else
3342         regmask_save |= 1 << reg;
3343     }
3344
3345     if (po->op == OP_PUSH && po->argnum == 0
3346       && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
3347     {
3348       if (po->operand[0].type == OPT_REG)
3349       {
3350         reg = po->operand[0].reg;
3351         if (reg < 0)
3352           ferr(po, "reg not set for push?\n");
3353
3354         depth = 0;
3355         ret = scan_for_pop(i + 1, opcnt,
3356                 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3357         if (ret == 1) {
3358           if (depth > 1)
3359             ferr(po, "too much depth: %d\n", depth);
3360
3361           po->flags |= OPF_RMD;
3362           scan_for_pop(i + 1, opcnt, po->operand[0].name,
3363             i + opcnt * 4, 0, &depth, 1);
3364           continue;
3365         }
3366         ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3367         if (ret == 0) {
3368           arg = OPF_RMD;
3369           if (regmask & (1 << reg)) {
3370             if (regmask_save & (1 << reg))
3371               ferr(po, "%s already saved?\n", po->operand[0].name);
3372             arg = OPF_RSAVE;
3373           }
3374           po->flags |= arg;
3375           scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3376           continue;
3377         }
3378       }
3379       else if (po->operand[0].type == OPT_CONST) {
3380         for (j = i + 1; j < opcnt; j++) {
3381           if ((ops[j].flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
3382             || ops[j].op == OP_PUSH || g_labels[i][0] != 0)
3383           {
3384             break;
3385           }
3386
3387           if (!(ops[j].flags & OPF_RMD) && ops[j].op == OP_POP)
3388           {
3389             po->flags |= OPF_RMD;
3390             ops[j].datap = po;
3391             break;
3392           }
3393         }
3394       }
3395     }
3396
3397     if (po->op == OP_STD) {
3398       po->flags |= OPF_DF | OPF_RMD;
3399       scan_propagate_df(i + 1, opcnt);
3400     }
3401
3402     regmask_now = po->regmask_src | po->regmask_dst;
3403     if (regmask_now & (1 << xBP)) {
3404       if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3405         if (po->regmask_dst & (1 << xBP))
3406           // compiler decided to drop bp frame and use ebp as scratch
3407           scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
3408         else
3409           regmask_now &= ~(1 << xBP);
3410       }
3411     }
3412
3413     regmask |= regmask_now;
3414
3415     if (po->flags & OPF_CC)
3416     {
3417       int setters[16], cnt = 0, branched = 0;
3418
3419       ret = scan_for_flag_set(i, i + opcnt * 6,
3420               &branched, setters, &cnt);
3421       if (ret < 0 || cnt <= 0)
3422         ferr(po, "unable to trace flag setter(s)\n");
3423       if (cnt > ARRAY_SIZE(setters))
3424         ferr(po, "too many flag setters\n");
3425
3426       pfo = split_cond(po, po->op, &dummy);
3427       for (j = 0; j < cnt; j++)
3428       {
3429         tmp_op = &ops[setters[j]]; // flag setter
3430         pfomask = 0;
3431
3432         // to get nicer code, we try to delay test and cmp;
3433         // if we can't because of operand modification, or if we
3434         // have arith op, or branch, make it calculate flags explicitly
3435         if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
3436         {
3437           if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
3438             pfomask = 1 << pfo;
3439         }
3440         else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
3441           pfomask = 1 << pfo;
3442         }
3443         else {
3444           // see if we'll be able to handle based on op result
3445           if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3446                && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3447               || branched
3448               || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3449             pfomask = 1 << pfo;
3450
3451           if (tmp_op->op == OP_ADD && pfo == PFO_C)
3452             need_tmp64 = 1;
3453         }
3454         if (pfomask) {
3455           tmp_op->pfomask |= pfomask;
3456           cond_vars |= pfomask;
3457         }
3458         // note: may overwrite, currently not a problem
3459         po->datap = tmp_op;
3460       }
3461
3462       if (po->op == OP_RCL || po->op == OP_RCR
3463        || po->op == OP_ADC || po->op == OP_SBB)
3464         cond_vars |= 1 << PFO_C;
3465     }
3466     else if (po->op == OP_CMPS || po->op == OP_SCAS) {
3467       cond_vars |= 1 << PFO_Z;
3468     }
3469     else if (po->op == OP_MUL
3470       || (po->op == OP_IMUL && po->operand_cnt == 1))
3471     {
3472       need_tmp64 = 1;
3473     }
3474     else if (po->op == OP_CALL) {
3475       pp = po->datap;
3476       if (pp == NULL)
3477         ferr(po, "NULL pp\n");
3478
3479       if (pp->is_unresolved) {
3480         int regmask_stack = 0;
3481         collect_call_args(po, i, pp, &regmask, &save_arg_vars,
3482           i + opcnt * 2);
3483
3484         // this is pretty rough guess:
3485         // see ecx and edx were pushed (and not their saved versions)
3486         for (arg = 0; arg < pp->argc; arg++) {
3487           if (pp->arg[arg].reg != NULL)
3488             continue;
3489
3490           tmp_op = pp->arg[arg].datap;
3491           if (tmp_op == NULL)
3492             ferr(po, "parsed_op missing for arg%d\n", arg);
3493           if (tmp_op->argnum == 0 && tmp_op->operand[0].type == OPT_REG)
3494             regmask_stack |= 1 << tmp_op->operand[0].reg;
3495         }
3496
3497         if (!((regmask_stack & (1 << xCX))
3498           && (regmask_stack & (1 << xDX))))
3499         {
3500           if (pp->argc_stack != 0
3501            || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
3502           {
3503             pp_insert_reg_arg(pp, "ecx");
3504             pp->is_fastcall = 1;
3505             regmask_init |= 1 << xCX;
3506             regmask |= 1 << xCX;
3507           }
3508           if (pp->argc_stack != 0
3509            || ((regmask | regmask_arg) & (1 << xDX)))
3510           {
3511             pp_insert_reg_arg(pp, "edx");
3512             regmask_init |= 1 << xDX;
3513             regmask |= 1 << xDX;
3514           }
3515         }
3516
3517         // note: __cdecl doesn't fall into is_unresolved category
3518         if (pp->argc_stack > 0)
3519           pp->is_stdcall = 1;
3520       }
3521
3522       for (arg = 0; arg < pp->argc; arg++) {
3523         if (pp->arg[arg].reg != NULL) {
3524           reg = char_array_i(regs_r32,
3525                   ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
3526           if (reg < 0)
3527             ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
3528           if (!(regmask & (1 << reg))) {
3529             regmask_init |= 1 << reg;
3530             regmask |= 1 << reg;
3531           }
3532         }
3533       }
3534
3535       // declare indirect funcs
3536       if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
3537         if (pp->name[0] != 0) {
3538           memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
3539           memcpy(pp->name, "i_", 2);
3540
3541           // might be declared already
3542           found = 0;
3543           for (j = 0; j < i; j++) {
3544             if (ops[j].op == OP_CALL && (pp_tmp = ops[j].datap)) {
3545               if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
3546                 found = 1;
3547                 break;
3548               }
3549             }
3550           }
3551           if (found)
3552             continue;
3553         }
3554         else
3555           snprintf(pp->name, sizeof(pp->name), "icall%d", i);
3556
3557         fprintf(fout, "  %s (", pp->ret_type.name);
3558         output_pp_attrs(fout, pp, 0);
3559         fprintf(fout, "*%s)(", pp->name);
3560         for (j = 0; j < pp->argc; j++) {
3561           if (j > 0)
3562             fprintf(fout, ", ");
3563           fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3564         }
3565         fprintf(fout, ");\n");
3566       }
3567     }
3568     else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3569       regmask |= 1 << xAX;
3570     else if (po->op == OP_DIV || po->op == OP_IDIV) {
3571       // 32bit division is common, look for it
3572       if (po->op == OP_DIV)
3573         ret = scan_for_reg_clear(i, xDX);
3574       else
3575         ret = scan_for_cdq_edx(i);
3576       if (ret >= 0)
3577         po->flags |= OPF_32BIT;
3578       else
3579         need_tmp64 = 1;
3580     }
3581     else if (po->op == OP_CLD)
3582       po->flags |= OPF_RMD;
3583
3584     if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
3585       need_tmp_var = 1;
3586     }
3587   }
3588
3589   // pass4:
3590   // - confirm regmask_save, it might have been reduced
3591   if (regmask_save != 0)
3592   {
3593     regmask_save = 0;
3594     for (i = 0; i < opcnt; i++) {
3595       po = &ops[i];
3596       if (po->flags & OPF_RMD)
3597         continue;
3598
3599       if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
3600         regmask_save |= 1 << po->operand[0].reg;
3601     }
3602   }
3603
3604
3605   // output LUTs/jumptables
3606   for (i = 0; i < g_func_pd_cnt; i++) {
3607     pd = &g_func_pd[i];
3608     fprintf(fout, "  static const ");
3609     if (pd->type == OPT_OFFSET) {
3610       fprintf(fout, "void *jt_%s[] =\n    { ", pd->label);
3611
3612       for (j = 0; j < pd->count; j++) {
3613         if (j > 0)
3614           fprintf(fout, ", ");
3615         fprintf(fout, "&&%s", pd->d[j].u.label);
3616       }
3617     }
3618     else {
3619       fprintf(fout, "%s %s[] =\n    { ",
3620         lmod_type_u(ops, pd->lmod), pd->label);
3621
3622       for (j = 0; j < pd->count; j++) {
3623         if (j > 0)
3624           fprintf(fout, ", ");
3625         fprintf(fout, "%u", pd->d[j].u.val);
3626       }
3627     }
3628     fprintf(fout, " };\n");
3629     had_decl = 1;
3630   }
3631
3632   // declare stack frame, va_arg
3633   if (g_stack_fsz) {
3634     fprintf(fout, "  union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3635       (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3636     had_decl = 1;
3637   }
3638
3639   if (g_func_pp->is_userstack) {
3640     fprintf(fout, "  u32 fake_sf[1024];\n");
3641     fprintf(fout, "  u32 *esp = &fake_sf[1024];\n");
3642     had_decl = 1;
3643   }
3644
3645   if (g_func_pp->is_vararg) {
3646     fprintf(fout, "  va_list ap;\n");
3647     had_decl = 1;
3648   }
3649
3650   // declare arg-registers
3651   for (i = 0; i < g_func_pp->argc; i++) {
3652     if (g_func_pp->arg[i].reg != NULL) {
3653       reg = char_array_i(regs_r32,
3654               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3655       if (regmask & (1 << reg)) {
3656         if (g_func_pp->arg[i].type.is_retreg)
3657           fprintf(fout, "  u32 %s = *r_%s;\n",
3658             g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
3659         else
3660           fprintf(fout, "  u32 %s = (u32)a%d;\n",
3661             g_func_pp->arg[i].reg, i + 1);
3662       }
3663       else {
3664         if (g_func_pp->arg[i].type.is_retreg)
3665           ferr(ops, "retreg '%s' is unused?\n",
3666             g_func_pp->arg[i].reg);
3667         fprintf(fout, "  // %s = a%d; // unused\n",
3668           g_func_pp->arg[i].reg, i + 1);
3669       }
3670       had_decl = 1;
3671     }
3672   }
3673
3674   regmask_now = regmask & ~regmask_arg;
3675   regmask_now &= ~(1 << xSP);
3676   if (regmask_now) {
3677     for (reg = 0; reg < 8; reg++) {
3678       if (regmask_now & (1 << reg)) {
3679         fprintf(fout, "  u32 %s", regs_r32[reg]);
3680         if (regmask_init & (1 << reg))
3681           fprintf(fout, " = 0");
3682         fprintf(fout, ";\n");
3683         had_decl = 1;
3684       }
3685     }
3686   }
3687
3688   if (regmask_save) {
3689     for (reg = 0; reg < 8; reg++) {
3690       if (regmask_save & (1 << reg)) {
3691         fprintf(fout, "  u32 s_%s;\n", regs_r32[reg]);
3692         had_decl = 1;
3693       }
3694     }
3695   }
3696
3697   if (save_arg_vars) {
3698     for (reg = 0; reg < 32; reg++) {
3699       if (save_arg_vars & (1 << reg)) {
3700         fprintf(fout, "  u32 s_a%d;\n", reg + 1);
3701         had_decl = 1;
3702       }
3703     }
3704   }
3705
3706   if (cond_vars) {
3707     for (i = 0; i < 8; i++) {
3708       if (cond_vars & (1 << i)) {
3709         fprintf(fout, "  u32 cond_%s;\n", parsed_flag_op_names[i]);
3710         had_decl = 1;
3711       }
3712     }
3713   }
3714
3715   if (need_tmp_var) {
3716     fprintf(fout, "  u32 tmp;\n");
3717     had_decl = 1;
3718   }
3719
3720   if (need_tmp64) {
3721     fprintf(fout, "  u64 tmp64;\n");
3722     had_decl = 1;
3723   }
3724
3725   if (had_decl)
3726     fprintf(fout, "\n");
3727
3728   if (g_func_pp->is_vararg) {
3729     if (g_func_pp->argc_stack == 0)
3730       ferr(ops, "vararg func without stack args?\n");
3731     fprintf(fout, "  va_start(ap, a%d);\n", g_func_pp->argc);
3732   }
3733
3734   // output ops
3735   for (i = 0; i < opcnt; i++)
3736   {
3737     if (g_labels[i][0] != 0) {
3738       fprintf(fout, "\n%s:\n", g_labels[i]);
3739       label_pending = 1;
3740
3741       delayed_flag_op = NULL;
3742       last_arith_dst = NULL;
3743     }
3744
3745     po = &ops[i];
3746     if (po->flags & OPF_RMD)
3747       continue;
3748
3749     no_output = 0;
3750
3751     #define assert_operand_cnt(n_) \
3752       if (po->operand_cnt != n_) \
3753         ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3754
3755     // conditional/flag using op?
3756     if (po->flags & OPF_CC)
3757     {
3758       int is_delayed = 0;
3759       int is_inv = 0;
3760
3761       pfo = split_cond(po, po->op, &is_inv);
3762       tmp_op = po->datap;
3763
3764       // we go through all this trouble to avoid using parsed_flag_op,
3765       // which makes generated code much nicer
3766       if (delayed_flag_op != NULL)
3767       {
3768         out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3769         is_delayed = 1;
3770       }
3771       else if (last_arith_dst != NULL
3772         && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3773            || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3774            ))
3775       {
3776         out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3777         out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3778           last_arith_dst->lmod, buf3);
3779         is_delayed = 1;
3780       }
3781       else if (tmp_op != NULL) {
3782         // use preprocessed flag calc results
3783         if (!(tmp_op->pfomask & (1 << pfo)))
3784           ferr(po, "not prepared for pfo %d\n", pfo);
3785
3786         // note: is_inv was not yet applied
3787         snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3788           is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3789       }
3790       else {
3791         ferr(po, "all methods of finding comparison failed\n");
3792       }
3793  
3794       if (po->flags & OPF_JMP) {
3795         fprintf(fout, "  if %s\n", buf1);
3796       }
3797       else if (po->op == OP_RCL || po->op == OP_RCR
3798                || po->op == OP_ADC || po->op == OP_SBB)
3799       {
3800         if (is_delayed)
3801           fprintf(fout, "  cond_%s = %s;\n",
3802             parsed_flag_op_names[pfo], buf1);
3803       }
3804       else if (po->flags & OPF_DATA) { // SETcc
3805         out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3806         fprintf(fout, "  %s = %s;", buf2, buf1);
3807       }
3808       else {
3809         ferr(po, "unhandled conditional op\n");
3810       }
3811     }
3812
3813     pfomask = po->pfomask;
3814
3815     if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
3816       struct parsed_opr opr = {0,};
3817       opr.type = OPT_REG;
3818       opr.reg = xCX;
3819       opr.lmod = OPLM_DWORD;
3820       ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
3821
3822       if (ret != 1 || uval == 0) {
3823         // we need initial flags for ecx=0 case..
3824         if (i > 0 && ops[i - 1].op == OP_XOR
3825           && IS(ops[i - 1].operand[0].name,
3826                 ops[i - 1].operand[1].name))
3827         {
3828           fprintf(fout, "  cond_z = ");
3829           if (pfomask & (1 << PFO_C))
3830             fprintf(fout, "cond_c = ");
3831           fprintf(fout, "0;\n");
3832         }
3833         else if (last_arith_dst != NULL) {
3834           out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3835           out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
3836             last_arith_dst->lmod, buf3);
3837           fprintf(fout, "  cond_z = %s;\n", buf1);
3838         }
3839         else
3840           ferr(po, "missing initial ZF\n");
3841       }
3842     }
3843
3844     switch (po->op)
3845     {
3846       case OP_MOV:
3847         assert_operand_cnt(2);
3848         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3849         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3850         fprintf(fout, "  %s = %s;", buf1,
3851             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3852               po->operand[0].is_ptr ? "(void *)" : "", 0));
3853         break;
3854
3855       case OP_LEA:
3856         assert_operand_cnt(2);
3857         po->operand[1].lmod = OPLM_DWORD; // always
3858         fprintf(fout, "  %s = %s;",
3859             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3860             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3861               NULL, 1));
3862         break;
3863
3864       case OP_MOVZX:
3865         assert_operand_cnt(2);
3866         fprintf(fout, "  %s = %s;",
3867             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3868             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3869         break;
3870
3871       case OP_MOVSX:
3872         assert_operand_cnt(2);
3873         switch (po->operand[1].lmod) {
3874         case OPLM_BYTE:
3875           strcpy(buf3, "(s8)");
3876           break;
3877         case OPLM_WORD:
3878           strcpy(buf3, "(s16)");
3879           break;
3880         default:
3881           ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3882         }
3883         fprintf(fout, "  %s = %s;",
3884             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3885             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3886               buf3, 0));
3887         break;
3888
3889       case OP_XCHG:
3890         assert_operand_cnt(2);
3891         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3892         fprintf(fout, "  tmp = %s;",
3893           out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
3894         fprintf(fout, " %s = %s;",
3895           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3896           out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], "", 0));
3897         fprintf(fout, " %s = tmp;",
3898           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]));
3899         snprintf(g_comment, sizeof(g_comment), "xchg");
3900         break;
3901
3902       case OP_NOT:
3903         assert_operand_cnt(1);
3904         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3905         fprintf(fout, "  %s = ~%s;", buf1, buf1);
3906         break;
3907
3908       case OP_CDQ:
3909         assert_operand_cnt(2);
3910         fprintf(fout, "  %s = (s32)%s >> 31;",
3911             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3912             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3913         strcpy(g_comment, "cdq");
3914         break;
3915
3916       case OP_STOS:
3917         assert_operand_cnt(3);
3918         if (po->flags & OPF_REP) {
3919           fprintf(fout, "  for (; ecx != 0; ecx--, edi %c= %d)\n",
3920             (po->flags & OPF_DF) ? '-' : '+',
3921             lmod_bytes(po, po->operand[0].lmod));
3922           fprintf(fout, "    %sedi = eax;",
3923             lmod_cast_u_ptr(po, po->operand[0].lmod));
3924           strcpy(g_comment, "rep stos");
3925         }
3926         else {
3927           fprintf(fout, "    %sedi = eax; edi %c= %d;",
3928             lmod_cast_u_ptr(po, po->operand[0].lmod),
3929             (po->flags & OPF_DF) ? '-' : '+',
3930             lmod_bytes(po, po->operand[0].lmod));
3931           strcpy(g_comment, "stos");
3932         }
3933         break;
3934
3935       case OP_MOVS:
3936         assert_operand_cnt(3);
3937         j = lmod_bytes(po, po->operand[0].lmod);
3938         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3939         l = (po->flags & OPF_DF) ? '-' : '+';
3940         if (po->flags & OPF_REP) {
3941           fprintf(fout,
3942             "  for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
3943             l, j, l, j);
3944           fprintf(fout,
3945             "    %sedi = %sesi;", buf1, buf1);
3946           strcpy(g_comment, "rep movs");
3947         }
3948         else {
3949           fprintf(fout, "    %sedi = %sesi; edi %c= %d; esi %c= %d;",
3950             buf1, buf1, l, j, l, j);
3951           strcpy(g_comment, "movs");
3952         }
3953         break;
3954
3955       case OP_CMPS:
3956         // repe ~ repeat while ZF=1
3957         assert_operand_cnt(3);
3958         j = lmod_bytes(po, po->operand[0].lmod);
3959         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3960         l = (po->flags & OPF_DF) ? '-' : '+';
3961         if (po->flags & OPF_REP) {
3962           fprintf(fout,
3963             "  for (; ecx != 0; ecx--) {\n");
3964           if (pfomask & (1 << PFO_C)) {
3965             // ugh..
3966             fprintf(fout,
3967             "    cond_c = %sedi < %sesi;\n", buf1, buf1);
3968             pfomask &= ~(1 << PFO_C);
3969           }
3970           fprintf(fout,
3971             "    cond_z = (%sedi == %sesi); edi %c= %d, esi %c= %d;\n",
3972               buf1, buf1, l, j, l, j);
3973           fprintf(fout,
3974             "    if (cond_z %s 0) break;\n",
3975               (po->flags & OPF_REPZ) ? "==" : "!=");
3976           fprintf(fout,
3977             "  }");
3978           snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3979             (po->flags & OPF_REPZ) ? "e" : "ne");
3980         }
3981         else {
3982           fprintf(fout,
3983             "    cond_z = (%sedi = %sesi); edi %c= %d; esi %c= %d;",
3984             buf1, buf1, l, j, l, j);
3985           strcpy(g_comment, "cmps");
3986         }
3987         pfomask &= ~(1 << PFO_Z);
3988         last_arith_dst = NULL;
3989         delayed_flag_op = NULL;
3990         break;
3991
3992       case OP_SCAS:
3993         // only does ZF (for now)
3994         // repe ~ repeat while ZF=1
3995         assert_operand_cnt(3);
3996         j = lmod_bytes(po, po->operand[0].lmod);
3997         l = (po->flags & OPF_DF) ? '-' : '+';
3998         if (po->flags & OPF_REP) {
3999           fprintf(fout,
4000             "  for (; ecx != 0; ecx--) {\n");
4001           fprintf(fout,
4002             "    cond_z = (%seax == %sedi); edi %c= %d;\n",
4003               lmod_cast_u(po, po->operand[0].lmod),
4004               lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4005           fprintf(fout,
4006             "    if (cond_z %s 0) break;\n",
4007               (po->flags & OPF_REPZ) ? "==" : "!=");
4008           fprintf(fout,
4009             "  }");
4010           snprintf(g_comment, sizeof(g_comment), "rep%s scas",
4011             (po->flags & OPF_REPZ) ? "e" : "ne");
4012         }
4013         else {
4014           fprintf(fout, "  cond_z = (%seax = %sedi); edi %c= %d;",
4015               lmod_cast_u(po, po->operand[0].lmod),
4016               lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4017           strcpy(g_comment, "scas");
4018         }
4019         pfomask &= ~(1 << PFO_Z);
4020         last_arith_dst = NULL;
4021         delayed_flag_op = NULL;
4022         break;
4023
4024       // arithmetic w/flags
4025       case OP_AND:
4026       case OP_OR:
4027         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4028         // fallthrough
4029       dualop_arith:
4030         assert_operand_cnt(2);
4031         fprintf(fout, "  %s %s= %s;",
4032             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4033             op_to_c(po),
4034             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4035         output_std_flags(fout, po, &pfomask, buf1);
4036         last_arith_dst = &po->operand[0];
4037         delayed_flag_op = NULL;
4038         break;
4039
4040       case OP_SHL:
4041       case OP_SHR:
4042         assert_operand_cnt(2);
4043         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4044         if (pfomask & (1 << PFO_C)) {
4045           if (po->operand[1].type == OPT_CONST) {
4046             l = lmod_bytes(po, po->operand[0].lmod) * 8;
4047             j = po->operand[1].val;
4048             j %= l;
4049             if (j != 0) {
4050               if (po->op == OP_SHL)
4051                 j = l - j;
4052               else
4053                 j -= 1;
4054               fprintf(fout, "  cond_c = (%s >> %d) & 1;\n",
4055                 buf1, j);
4056             }
4057             else
4058               ferr(po, "zero shift?\n");
4059           }
4060           else
4061             ferr(po, "TODO\n");
4062           pfomask &= ~(1 << PFO_C);
4063         }
4064         fprintf(fout, "  %s %s= %s;", buf1, op_to_c(po),
4065             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4066         output_std_flags(fout, po, &pfomask, buf1);
4067         last_arith_dst = &po->operand[0];
4068         delayed_flag_op = NULL;
4069         break;
4070
4071       case OP_SAR:
4072         assert_operand_cnt(2);
4073         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4074         fprintf(fout, "  %s = %s%s >> %s;", buf1,
4075           lmod_cast_s(po, po->operand[0].lmod), buf1,
4076           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4077         output_std_flags(fout, po, &pfomask, buf1);
4078         last_arith_dst = &po->operand[0];
4079         delayed_flag_op = NULL;
4080         break;
4081
4082       case OP_ROL:
4083       case OP_ROR:
4084         assert_operand_cnt(2);
4085         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4086         if (po->operand[1].type == OPT_CONST) {
4087           j = po->operand[1].val;
4088           j %= lmod_bytes(po, po->operand[0].lmod) * 8;
4089           fprintf(fout, po->op == OP_ROL ?
4090             "  %s = (%s << %d) | (%s >> %d);" :
4091             "  %s = (%s >> %d) | (%s << %d);",
4092             buf1, buf1, j, buf1,
4093             lmod_bytes(po, po->operand[0].lmod) * 8 - j);
4094         }
4095         else
4096           ferr(po, "TODO\n");
4097         output_std_flags(fout, po, &pfomask, buf1);
4098         last_arith_dst = &po->operand[0];
4099         delayed_flag_op = NULL;
4100         break;
4101
4102       case OP_RCL:
4103       case OP_RCR:
4104         assert_operand_cnt(2);
4105         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4106         l = lmod_bytes(po, po->operand[0].lmod) * 8;
4107         if (po->operand[1].type == OPT_CONST) {
4108           j = po->operand[1].val % l;
4109           if (j == 0)
4110             ferr(po, "zero rotate\n");
4111           fprintf(fout, "  tmp = (%s >> %d) & 1;\n",
4112             buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
4113           if (po->op == OP_RCL) {
4114             fprintf(fout,
4115               "  %s = (%s << %d) | (cond_c << %d)",
4116               buf1, buf1, j, j - 1);
4117             if (j != 1)
4118               fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
4119           }
4120           else {
4121             fprintf(fout,
4122               "  %s = (%s >> %d) | (cond_c << %d)",
4123               buf1, buf1, j, l - j);
4124             if (j != 1)
4125               fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
4126           }
4127           fprintf(fout, ";\n");
4128           fprintf(fout, "  cond_c = tmp;");
4129         }
4130         else
4131           ferr(po, "TODO\n");
4132         strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
4133         output_std_flags(fout, po, &pfomask, buf1);
4134         last_arith_dst = &po->operand[0];
4135         delayed_flag_op = NULL;
4136         break;
4137
4138       case OP_XOR:
4139         assert_operand_cnt(2);
4140         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4141         if (IS(opr_name(po, 0), opr_name(po, 1))) {
4142           // special case for XOR
4143           if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
4144             fprintf(fout, "  cond_be = 1;\n");
4145             pfomask &= ~(1 << PFO_BE);
4146           }
4147           fprintf(fout, "  %s = 0;",
4148             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4149           last_arith_dst = &po->operand[0];
4150           delayed_flag_op = NULL;
4151           break;
4152         }
4153         goto dualop_arith;
4154
4155       case OP_ADD:
4156         assert_operand_cnt(2);
4157         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4158         if (pfomask & (1 << PFO_C)) {
4159           fprintf(fout, "  tmp64 = (u64)%s + %s;\n",
4160             out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]),
4161             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4162           fprintf(fout, "  cond_c = tmp64 >> 32;\n");
4163           fprintf(fout, "  %s = (u32)tmp64;",
4164             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4165           strcat(g_comment, "add64");
4166           pfomask &= ~(1 << PFO_C);
4167           output_std_flags(fout, po, &pfomask, buf1);
4168           last_arith_dst = &po->operand[0];
4169           delayed_flag_op = NULL;
4170           break;
4171         }
4172         goto dualop_arith;
4173
4174       case OP_SUB:
4175         assert_operand_cnt(2);
4176         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4177         if (pfomask & (1 << PFO_C)) {
4178           fprintf(fout, "  cond_c = %s < %s;\n",
4179             out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]),
4180             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4181           pfomask &= ~(1 << PFO_C);
4182         }
4183         goto dualop_arith;
4184
4185       case OP_ADC:
4186       case OP_SBB:
4187         assert_operand_cnt(2);
4188         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4189         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4190         if (po->op == OP_SBB
4191           && IS(po->operand[0].name, po->operand[1].name))
4192         {
4193           // avoid use of unitialized var
4194           fprintf(fout, "  %s = -cond_c;", buf1);
4195           // carry remains what it was
4196           pfomask &= ~(1 << PFO_C);
4197         }
4198         else {
4199           fprintf(fout, "  %s %s= %s + cond_c;", buf1, op_to_c(po),
4200             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4201         }
4202         output_std_flags(fout, po, &pfomask, buf1);
4203         last_arith_dst = &po->operand[0];
4204         delayed_flag_op = NULL;
4205         break;
4206
4207       case OP_BSF:
4208         assert_operand_cnt(2);
4209         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4210         fprintf(fout, "  %s = %s ? __builtin_ffs(%s) - 1 : 0;",
4211           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4212           buf2, buf2);
4213         output_std_flags(fout, po, &pfomask, buf1);
4214         last_arith_dst = &po->operand[0];
4215         delayed_flag_op = NULL;
4216         strcat(g_comment, "bsf");
4217         break;
4218
4219       case OP_INC:
4220       case OP_DEC:
4221         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4222         if (po->operand[0].type == OPT_REG) {
4223           strcpy(buf2, po->op == OP_INC ? "++" : "--");
4224           fprintf(fout, "  %s%s;", buf1, buf2);
4225         }
4226         else {
4227           strcpy(buf2, po->op == OP_INC ? "+" : "-");
4228           fprintf(fout, "  %s %s= 1;", buf1, buf2);
4229         }
4230         output_std_flags(fout, po, &pfomask, buf1);
4231         last_arith_dst = &po->operand[0];
4232         delayed_flag_op = NULL;
4233         break;
4234
4235       case OP_NEG:
4236         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4237         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
4238         fprintf(fout, "  %s = -%s%s;", buf1,
4239           lmod_cast_s(po, po->operand[0].lmod), buf2);
4240         last_arith_dst = &po->operand[0];
4241         delayed_flag_op = NULL;
4242         if (pfomask & (1 << PFO_C)) {
4243           fprintf(fout, "\n  cond_c = (%s != 0);", buf1);
4244           pfomask &= ~(1 << PFO_C);
4245         }
4246         break;
4247
4248       case OP_IMUL:
4249         if (po->operand_cnt == 2) {
4250           propagate_lmod(po, &po->operand[0], &po->operand[1]);
4251           goto dualop_arith;
4252         }
4253         if (po->operand_cnt == 3)
4254           ferr(po, "TODO imul3\n");
4255         // fallthrough
4256       case OP_MUL:
4257         assert_operand_cnt(1);
4258         strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
4259         fprintf(fout, "  tmp64 = %seax * %s%s;\n", buf1, buf1,
4260           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
4261         fprintf(fout, "  edx = tmp64 >> 32;\n");
4262         fprintf(fout, "  eax = tmp64;");
4263         last_arith_dst = NULL;
4264         delayed_flag_op = NULL;
4265         break;
4266
4267       case OP_DIV:
4268       case OP_IDIV:
4269         assert_operand_cnt(1);
4270         if (po->operand[0].lmod != OPLM_DWORD)
4271           ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
4272
4273         out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4274         strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
4275           po->op == OP_IDIV));
4276         switch (po->operand[0].lmod) {
4277         case OPLM_DWORD:
4278           if (po->flags & OPF_32BIT)
4279             snprintf(buf3, sizeof(buf3), "%seax", buf2);
4280           else {
4281             fprintf(fout, "  tmp64 = ((u64)edx << 32) | eax;\n");
4282             snprintf(buf3, sizeof(buf3), "%stmp64",
4283               (po->op == OP_IDIV) ? "(s64)" : "");
4284           }
4285           if (po->operand[0].type == OPT_REG
4286             && po->operand[0].reg == xDX)
4287           {
4288             fprintf(fout, "  eax = %s / %s%s;", buf3, buf2, buf1);
4289             fprintf(fout, "  edx = %s %% %s%s;\n", buf3, buf2, buf1);
4290           }
4291           else {
4292             fprintf(fout, "  edx = %s %% %s%s;\n", buf3, buf2, buf1);
4293             fprintf(fout, "  eax = %s / %s%s;", buf3, buf2, buf1);
4294           }
4295           break;
4296         default:
4297           ferr(po, "unhandled division type\n");
4298         }
4299         last_arith_dst = NULL;
4300         delayed_flag_op = NULL;
4301         break;
4302
4303       case OP_TEST:
4304       case OP_CMP:
4305         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4306         if (pfomask != 0) {
4307           for (j = 0; j < 8; j++) {
4308             if (pfomask & (1 << j)) {
4309               out_cmp_test(buf1, sizeof(buf1), po, j, 0);
4310               fprintf(fout, "  cond_%s = %s;",
4311                 parsed_flag_op_names[j], buf1);
4312             }
4313           }
4314           pfomask = 0;
4315         }
4316         else
4317           no_output = 1;
4318         last_arith_dst = NULL;
4319         delayed_flag_op = po;
4320         break;
4321
4322       // note: we reuse OP_Jcc for SETcc, only flags differ
4323       case OP_JO ... OP_JG:
4324         if (po->flags & OPF_JMP)
4325           fprintf(fout, "    goto %s;", po->operand[0].name);
4326         // else SETcc - should already be handled
4327         break;
4328
4329       case OP_JECXZ:
4330         fprintf(fout, "  if (ecx == 0)\n");
4331         fprintf(fout, "    goto %s;", po->operand[0].name);
4332         strcat(g_comment, "jecxz");
4333         break;
4334
4335       case OP_JMP:
4336         assert_operand_cnt(1);
4337         last_arith_dst = NULL;
4338         delayed_flag_op = NULL;
4339
4340         if (po->operand[0].type == OPT_REGMEM) {
4341           ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
4342                   buf1, buf2);
4343           if (ret != 2)
4344             ferr(po, "parse failure for jmp '%s'\n",
4345               po->operand[0].name);
4346           fprintf(fout, "  goto *jt_%s[%s];", buf1, buf2);
4347           break;
4348         }
4349         else if (po->operand[0].type != OPT_LABEL)
4350           ferr(po, "unhandled jmp type\n");
4351
4352         fprintf(fout, "  goto %s;", po->operand[0].name);
4353         break;
4354
4355       case OP_CALL:
4356         assert_operand_cnt(1);
4357         pp = po->datap;
4358         my_assert_not(pp, NULL);
4359
4360         if (pp->is_fptr && !pp->is_arg)
4361           fprintf(fout, "  %s = %s;\n", pp->name,
4362             out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
4363               "(void *)", 0));
4364
4365         fprintf(fout, "  ");
4366         if (strstr(pp->ret_type.name, "int64")) {
4367           if (po->flags & OPF_TAIL)
4368             ferr(po, "int64 and tail?\n");
4369           fprintf(fout, "tmp64 = ");
4370         }
4371         else if (!IS(pp->ret_type.name, "void")) {
4372           if (po->flags & OPF_TAIL) {
4373             if (!IS(g_func_pp->ret_type.name, "void")) {
4374               fprintf(fout, "return ");
4375               if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
4376                 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
4377             }
4378           }
4379           else if (regmask & (1 << xAX)) {
4380             fprintf(fout, "eax = ");
4381             if (pp->ret_type.is_ptr)
4382               fprintf(fout, "(u32)");
4383           }
4384         }
4385
4386         if (pp->name[0] == 0)
4387           ferr(po, "missing pp->name\n");
4388         fprintf(fout, "%s%s(", pp->name,
4389           pp->has_structarg ? "_sa" : "");
4390
4391         if (po->flags & OPF_ATAIL) {
4392           if (pp->argc_stack != g_func_pp->argc_stack
4393             || (pp->argc_stack > 0
4394                 && pp->is_stdcall != g_func_pp->is_stdcall))
4395             ferr(po, "incompatible tailcall\n");
4396           if (g_func_pp->has_retreg)
4397             ferr(po, "TODO: retreg+tailcall\n");
4398
4399           for (arg = j = 0; arg < pp->argc; arg++) {
4400             if (arg > 0)
4401               fprintf(fout, ", ");
4402
4403             cast[0] = 0;
4404             if (pp->arg[arg].type.is_ptr)
4405               snprintf(cast, sizeof(cast), "(%s)",
4406                 pp->arg[arg].type.name);
4407
4408             if (pp->arg[arg].reg != NULL) {
4409               fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4410               continue;
4411             }
4412             // stack arg
4413             for (; j < g_func_pp->argc; j++)
4414               if (g_func_pp->arg[j].reg == NULL)
4415                 break;
4416             fprintf(fout, "%sa%d", cast, j + 1);
4417             j++;
4418           }
4419         }
4420         else {
4421           for (arg = 0; arg < pp->argc; arg++) {
4422             if (arg > 0)
4423               fprintf(fout, ", ");
4424
4425             cast[0] = 0;
4426             if (pp->arg[arg].type.is_ptr)
4427               snprintf(cast, sizeof(cast), "(%s)",
4428                 pp->arg[arg].type.name);
4429
4430             if (pp->arg[arg].reg != NULL) {
4431               if (pp->arg[arg].type.is_retreg)
4432                 fprintf(fout, "&%s", pp->arg[arg].reg);
4433               else
4434                 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4435               continue;
4436             }
4437
4438             // stack arg
4439             tmp_op = pp->arg[arg].datap;
4440             if (tmp_op == NULL)
4441               ferr(po, "parsed_op missing for arg%d\n", arg);
4442             if (tmp_op->argnum != 0) {
4443               fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
4444             }
4445             else {
4446               fprintf(fout, "%s",
4447                 out_src_opr(buf1, sizeof(buf1),
4448                   tmp_op, &tmp_op->operand[0], cast, 0));
4449             }
4450           }
4451         }
4452         fprintf(fout, ");");
4453
4454         if (strstr(pp->ret_type.name, "int64")) {
4455           fprintf(fout, "\n");
4456           fprintf(fout, "  edx = tmp64 >> 32;\n");
4457           fprintf(fout, "  eax = tmp64;");
4458         }
4459
4460         if (pp->is_unresolved) {
4461           snprintf(buf3, sizeof(buf3), " unresoved %dreg",
4462             pp->argc_reg);
4463           strcat(g_comment, buf3);
4464         }
4465
4466         if (po->flags & OPF_TAIL) {
4467           ret = 0;
4468           if (i == opcnt - 1 || pp->is_noreturn)
4469             ret = 0;
4470           else if (IS(pp->ret_type.name, "void"))
4471             ret = 1;
4472           else if (IS(g_func_pp->ret_type.name, "void"))
4473             ret = 1;
4474           // else already handled as 'return f()'
4475
4476           if (ret) {
4477             if (!IS(g_func_pp->ret_type.name, "void")) {
4478               ferr(po, "int func -> void func tailcall?\n");
4479             }
4480             else {
4481               fprintf(fout, "\n  return;");
4482               strcat(g_comment, " ^ tailcall");
4483             }
4484           }
4485           else
4486             strcat(g_comment, " tailcall");
4487         }
4488         if (pp->is_noreturn)
4489           strcat(g_comment, " noreturn");
4490         if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
4491           strcat(g_comment, " argframe");
4492         delayed_flag_op = NULL;
4493         last_arith_dst = NULL;
4494         break;
4495
4496       case OP_RET:
4497         if (g_func_pp->is_vararg)
4498           fprintf(fout, "  va_end(ap);\n");
4499         if (g_func_pp->has_retreg) {
4500           for (arg = 0; arg < g_func_pp->argc; arg++)
4501             if (g_func_pp->arg[arg].type.is_retreg)
4502               fprintf(fout, "  *r_%s = %s;\n",
4503                 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
4504         }
4505  
4506         if (IS(g_func_pp->ret_type.name, "void")) {
4507           if (i != opcnt - 1 || label_pending)
4508             fprintf(fout, "  return;");
4509         }
4510         else if (g_func_pp->ret_type.is_ptr) {
4511           fprintf(fout, "  return (%s)eax;",
4512             g_func_pp->ret_type.name);
4513         }
4514         else if (IS(g_func_pp->ret_type.name, "__int64"))
4515           fprintf(fout, "  return ((u64)edx << 32) | eax;");
4516         else
4517           fprintf(fout, "  return eax;");
4518
4519         last_arith_dst = NULL;
4520         delayed_flag_op = NULL;
4521         break;
4522
4523       case OP_PUSH:
4524         out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4525         if (po->argnum != 0) {
4526           // special case - saved func arg
4527           fprintf(fout, "  s_a%d = %s;", po->argnum, buf1);
4528           break;
4529         }
4530         else if (po->flags & OPF_RSAVE) {
4531           fprintf(fout, "  s_%s = %s;", buf1, buf1);
4532           break;
4533         }
4534         else if (g_func_pp->is_userstack) {
4535           fprintf(fout, "  *(--esp) = %s;", buf1);
4536           break;
4537         }
4538         if (!(g_ida_func_attr & IDAFA_NORETURN))
4539           ferr(po, "stray push encountered\n");
4540         no_output = 1;
4541         break;
4542
4543       case OP_POP:
4544         if (po->flags & OPF_RSAVE) {
4545           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4546           fprintf(fout, "  %s = s_%s;", buf1, buf1);
4547           break;
4548         }
4549         else if (po->datap != NULL) {
4550           // push/pop pair
4551           tmp_op = po->datap;
4552           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4553           fprintf(fout, "  %s = %s;", buf1,
4554             out_src_opr(buf2, sizeof(buf2),
4555               tmp_op, &tmp_op->operand[0],
4556               po->operand[0].is_ptr ? "(void *)" : "", 0));
4557           break;
4558         }
4559         else if (g_func_pp->is_userstack) {
4560           fprintf(fout, "  %s = *esp++;",
4561             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4562           break;
4563         }
4564         else
4565           ferr(po, "stray pop encountered\n");
4566         break;
4567
4568       case OP_NOP:
4569         no_output = 1;
4570         break;
4571
4572       default:
4573         no_output = 1;
4574         ferr(po, "unhandled op type %d, flags %x\n",
4575           po->op, po->flags);
4576         break;
4577     }
4578
4579     if (g_comment[0] != 0) {
4580       char *p = g_comment;
4581       while (my_isblank(*p))
4582         p++;
4583       fprintf(fout, "  // %s", p);
4584       g_comment[0] = 0;
4585       no_output = 0;
4586     }
4587     if (!no_output)
4588       fprintf(fout, "\n");
4589
4590     // some sanity checking
4591     if (po->flags & OPF_REP) {
4592       if (po->op != OP_STOS && po->op != OP_MOVS
4593           && po->op != OP_CMPS && po->op != OP_SCAS)
4594         ferr(po, "unexpected rep\n");
4595       if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
4596           && (po->op == OP_CMPS || po->op == OP_SCAS))
4597         ferr(po, "cmps/scas with plain rep\n");
4598     }
4599     if ((po->flags & (OPF_REPZ|OPF_REPNZ))
4600         && po->op != OP_CMPS && po->op != OP_SCAS)
4601       ferr(po, "unexpected repz/repnz\n");
4602
4603     if (pfomask != 0)
4604       ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
4605
4606     // see is delayed flag stuff is still valid
4607     if (delayed_flag_op != NULL && delayed_flag_op != po) {
4608       if (is_any_opr_modified(delayed_flag_op, po, 0))
4609         delayed_flag_op = NULL;
4610     }
4611
4612     if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
4613       if (is_opr_modified(last_arith_dst, po))
4614         last_arith_dst = NULL;
4615     }
4616
4617     label_pending = 0;
4618   }
4619
4620   if (g_stack_fsz && !g_stack_frame_used)
4621     fprintf(fout, "  (void)sf;\n");
4622
4623   fprintf(fout, "}\n\n");
4624
4625   // cleanup
4626   for (i = 0; i < opcnt; i++) {
4627     struct label_ref *lr, *lr_del;
4628
4629     lr = g_label_refs[i].next;
4630     while (lr != NULL) {
4631       lr_del = lr;
4632       lr = lr->next;
4633       free(lr_del);
4634     }
4635     g_label_refs[i].i = -1;
4636     g_label_refs[i].next = NULL;
4637
4638     if (ops[i].op == OP_CALL) {
4639       pp = ops[i].datap;
4640       if (pp)
4641         proto_release(pp);
4642     }
4643   }
4644   g_func_pp = NULL;
4645 }
4646
4647 static void set_label(int i, const char *name)
4648 {
4649   const char *p;
4650   int len;
4651
4652   len = strlen(name);
4653   p = strchr(name, ':');
4654   if (p != NULL)
4655     len = p - name;
4656
4657   if (len > sizeof(g_labels[0]) - 1)
4658     aerr("label '%s' too long: %d\n", name, len);
4659   if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
4660     aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
4661   memcpy(g_labels[i], name, len);
4662   g_labels[i][len] = 0;
4663 }
4664
4665 // '=' needs special treatment..
4666 static char *next_word_s(char *w, size_t wsize, char *s)
4667 {
4668         size_t i;
4669
4670         s = sskip(s);
4671
4672         for (i = 0; i < wsize - 1; i++) {
4673                 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
4674                         break;
4675                 w[i] = s[i];
4676         }
4677         w[i] = 0;
4678
4679         if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
4680                 printf("warning: '%s' truncated\n", w);
4681
4682         return s + i;
4683 }
4684
4685 struct chunk_item {
4686   char *name;
4687   long fptr;
4688   int asmln;
4689 };
4690
4691 static struct chunk_item *func_chunks;
4692 static int func_chunk_cnt;
4693 static int func_chunk_alloc;
4694
4695 static void add_func_chunk(FILE *fasm, const char *name, int line)
4696 {
4697   if (func_chunk_cnt >= func_chunk_alloc) {
4698     func_chunk_alloc *= 2;
4699     func_chunks = realloc(func_chunks,
4700       func_chunk_alloc * sizeof(func_chunks[0]));
4701     my_assert_not(func_chunks, NULL);
4702   }
4703   func_chunks[func_chunk_cnt].fptr = ftell(fasm);
4704   func_chunks[func_chunk_cnt].name = strdup(name);
4705   func_chunks[func_chunk_cnt].asmln = line;
4706   func_chunk_cnt++;
4707 }
4708
4709 static int cmp_chunks(const void *p1, const void *p2)
4710 {
4711   const struct chunk_item *c1 = p1, *c2 = p2;
4712   return strcmp(c1->name, c2->name);
4713 }
4714
4715 static int cmpstringp(const void *p1, const void *p2)
4716 {
4717   return strcmp(*(char * const *)p1, *(char * const *)p2);
4718 }
4719
4720 static void scan_ahead(FILE *fasm)
4721 {
4722   char words[2][256];
4723   char line[256];
4724   long oldpos;
4725   int oldasmln;
4726   int wordc;
4727   char *p;
4728   int i;
4729
4730   oldpos = ftell(fasm);
4731   oldasmln = asmln;
4732
4733   while (fgets(line, sizeof(line), fasm))
4734   {
4735     wordc = 0;
4736     asmln++;
4737
4738     p = sskip(line);
4739     if (*p == 0)
4740       continue;
4741
4742     if (*p == ';')
4743     {
4744       // get rid of random tabs
4745       for (i = 0; line[i] != 0; i++)
4746         if (line[i] == '\t')
4747           line[i] = ' ';
4748
4749       if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4750       {
4751         p += 30;
4752         next_word(words[0], sizeof(words[0]), p);
4753         if (words[0][0] == 0)
4754           aerr("missing name for func chunk?\n");
4755
4756         add_func_chunk(fasm, words[0], asmln);
4757       }
4758       continue;
4759     } // *p == ';'
4760
4761     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4762       words[wordc][0] = 0;
4763       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4764       if (*p == 0 || *p == ';') {
4765         wordc++;
4766         break;
4767       }
4768     }
4769
4770     if (wordc == 2 && IS(words[1], "ends"))
4771       break;
4772   }
4773
4774   fseek(fasm, oldpos, SEEK_SET);
4775   asmln = oldasmln;
4776 }
4777
4778 int main(int argc, char *argv[])
4779 {
4780   FILE *fout, *fasm, *frlist;
4781   struct parsed_data *pd = NULL;
4782   int pd_alloc = 0;
4783   char **rlist = NULL;
4784   int rlist_len = 0;
4785   int rlist_alloc = 0;
4786   int func_chunks_used = 0;
4787   int func_chunks_sorted = 0;
4788   int func_chunk_i = -1;
4789   long func_chunk_ret = 0;
4790   int func_chunk_ret_ln = 0;
4791   int scanned_ahead = 0;
4792   char line[256];
4793   char words[20][256];
4794   enum opr_lenmod lmod;
4795   char *sctproto = NULL;
4796   int in_func = 0;
4797   int pending_endp = 0;
4798   int skip_func = 0;
4799   int skip_warned = 0;
4800   int eq_alloc;
4801   int verbose = 0;
4802   int multi_seg = 0;
4803   int arg_out;
4804   int arg;
4805   int pi = 0;
4806   int i, j;
4807   int ret, len;
4808   char *p;
4809   int wordc;
4810
4811   for (arg = 1; arg < argc; arg++) {
4812     if (IS(argv[arg], "-v"))
4813       verbose = 1;
4814     else if (IS(argv[arg], "-rf"))
4815       g_allow_regfunc = 1;
4816     else if (IS(argv[arg], "-m"))
4817       multi_seg = 1;
4818     else
4819       break;
4820   }
4821
4822   if (argc < arg + 3) {
4823     printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdrf> [rlist]*\n",
4824       argv[0]);
4825     return 1;
4826   }
4827
4828   arg_out = arg++;
4829
4830   asmfn = argv[arg++];
4831   fasm = fopen(asmfn, "r");
4832   my_assert_not(fasm, NULL);
4833
4834   hdrfn = argv[arg++];
4835   g_fhdr = fopen(hdrfn, "r");
4836   my_assert_not(g_fhdr, NULL);
4837
4838   rlist_alloc = 64;
4839   rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4840   my_assert_not(rlist, NULL);
4841   // needs special handling..
4842   rlist[rlist_len++] = "__alloca_probe";
4843
4844   func_chunk_alloc = 32;
4845   func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4846   my_assert_not(func_chunks, NULL);
4847
4848   memset(words, 0, sizeof(words));
4849
4850   for (; arg < argc; arg++) {
4851     frlist = fopen(argv[arg], "r");
4852     my_assert_not(frlist, NULL);
4853
4854     while (fgets(line, sizeof(line), frlist)) {
4855       p = sskip(line);
4856       if (*p == 0 || *p == ';')
4857         continue;
4858       if (*p == '#') {
4859         if (IS_START(p, "#if 0")
4860          || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
4861         {
4862           skip_func = 1;
4863         }
4864         else if (IS_START(p, "#endif"))
4865           skip_func = 0;
4866         continue;
4867       }
4868       if (skip_func)
4869         continue;
4870
4871       p = next_word(words[0], sizeof(words[0]), p);
4872       if (words[0][0] == 0)
4873         continue;
4874
4875       if (rlist_len >= rlist_alloc) {
4876         rlist_alloc = rlist_alloc * 2 + 64;
4877         rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4878         my_assert_not(rlist, NULL);
4879       }
4880       rlist[rlist_len++] = strdup(words[0]);
4881     }
4882     skip_func = 0;
4883
4884     fclose(frlist);
4885     frlist = NULL;
4886   }
4887
4888   if (rlist_len > 0)
4889     qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4890
4891   fout = fopen(argv[arg_out], "w");
4892   my_assert_not(fout, NULL);
4893
4894   eq_alloc = 128;
4895   g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4896   my_assert_not(g_eqs, NULL);
4897
4898   for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4899     g_label_refs[i].i = -1;
4900     g_label_refs[i].next = NULL;
4901   }
4902
4903   while (fgets(line, sizeof(line), fasm))
4904   {
4905     wordc = 0;
4906     asmln++;
4907
4908     p = sskip(line);
4909     if (*p == 0)
4910       continue;
4911
4912     // get rid of random tabs
4913     for (i = 0; line[i] != 0; i++)
4914       if (line[i] == '\t')
4915         line[i] = ' ';
4916
4917     if (*p == ';')
4918     {
4919       if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4920         goto do_pending_endp; // eww..
4921
4922       if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4923       {
4924         static const char *attrs[] = {
4925           "bp-based frame",
4926           "library function",
4927           "static",
4928           "noreturn",
4929           "thunk",
4930           "fpd=",
4931         };
4932
4933         // parse IDA's attribute-list comment
4934         g_ida_func_attr = 0;
4935         p = sskip(p + 13);
4936
4937         for (; *p != 0; p = sskip(p)) {
4938           for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4939             if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4940               g_ida_func_attr |= 1 << i;
4941               p += strlen(attrs[i]);
4942               break;
4943             }
4944           }
4945           if (i == ARRAY_SIZE(attrs)) {
4946             anote("unparsed IDA attr: %s\n", p);
4947             break;
4948           }
4949           if (IS(attrs[i], "fpd=")) {
4950             p = next_word(words[0], sizeof(words[0]), p);
4951             // ignore for now..
4952           }
4953         }
4954       }
4955       else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4956       {
4957         p += 30;
4958         next_word(words[0], sizeof(words[0]), p);
4959         if (words[0][0] == 0)
4960           aerr("missing name for func chunk?\n");
4961
4962         if (!scanned_ahead) {
4963           add_func_chunk(fasm, words[0], asmln);
4964           func_chunks_sorted = 0;
4965         }
4966       }
4967       else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4968       {
4969         if (func_chunk_i >= 0) {
4970           if (func_chunk_i < func_chunk_cnt
4971             && IS(func_chunks[func_chunk_i].name, g_func))
4972           {
4973             // move on to next chunk
4974             ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4975             if (ret)
4976               aerr("seek failed for '%s' chunk #%d\n",
4977                 g_func, func_chunk_i);
4978             asmln = func_chunks[func_chunk_i].asmln;
4979             func_chunk_i++;
4980           }
4981           else {
4982             if (func_chunk_ret == 0)
4983               aerr("no return from chunk?\n");
4984             fseek(fasm, func_chunk_ret, SEEK_SET);
4985             asmln = func_chunk_ret_ln;
4986             func_chunk_ret = 0;
4987             pending_endp = 1;
4988           }
4989         }
4990       }
4991       else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4992         func_chunks_used = 1;
4993         p += 20;
4994         if (IS_START(g_func, "sub_")) {
4995           unsigned long addr = strtoul(p, NULL, 16);
4996           unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4997           if (addr > f_addr && !scanned_ahead) {
4998             anote("scan_ahead caused by '%s', addr %lx\n",
4999               g_func, addr);
5000             scan_ahead(fasm);
5001             scanned_ahead = 1;
5002             func_chunks_sorted = 0;
5003           }
5004         }
5005       }
5006       continue;
5007     } // *p == ';'
5008
5009 parse_words:
5010     for (i = wordc; i < ARRAY_SIZE(words); i++)
5011       words[i][0] = 0;
5012     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
5013       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
5014       if (*p == 0 || *p == ';') {
5015         wordc++;
5016         break;
5017       }
5018     }
5019     if (*p != 0 && *p != ';')
5020       aerr("too many words\n");
5021
5022     // alow asm patches in comments
5023     if (*p == ';') {
5024       if (IS_START(p, "; sctpatch:")) {
5025         p = sskip(p + 11);
5026         if (*p == 0 || *p == ';')
5027           continue;
5028         goto parse_words; // lame
5029       }
5030       if (IS_START(p, "; sctproto:")) {
5031         sctproto = strdup(p + 11);
5032       }
5033     }
5034
5035     if (wordc == 0) {
5036       // shouldn't happen
5037       awarn("wordc == 0?\n");
5038       continue;
5039     }
5040
5041     // don't care about this:
5042     if (words[0][0] == '.'
5043         || IS(words[0], "include")
5044         || IS(words[0], "assume") || IS(words[1], "segment")
5045         || IS(words[0], "align"))
5046     {
5047       continue;
5048     }
5049
5050 do_pending_endp:
5051     // do delayed endp processing to collect switch jumptables
5052     if (pending_endp) {
5053       if (in_func && !skip_func && wordc >= 2
5054           && ((words[0][0] == 'd' && words[0][2] == 0)
5055               || (words[1][0] == 'd' && words[1][2] == 0)))
5056       {
5057         i = 1;
5058         if (words[1][0] == 'd' && words[1][2] == 0) {
5059           // label
5060           if (g_func_pd_cnt >= pd_alloc) {
5061             pd_alloc = pd_alloc * 2 + 16;
5062             g_func_pd = realloc(g_func_pd,
5063               sizeof(g_func_pd[0]) * pd_alloc);
5064             my_assert_not(g_func_pd, NULL);
5065           }
5066           pd = &g_func_pd[g_func_pd_cnt];
5067           g_func_pd_cnt++;
5068           memset(pd, 0, sizeof(*pd));
5069           strcpy(pd->label, words[0]);
5070           pd->type = OPT_CONST;
5071           pd->lmod = lmod_from_directive(words[1]);
5072           i = 2;
5073         }
5074         else {
5075           if (pd == NULL) {
5076             if (verbose)
5077               anote("skipping alignment byte?\n");
5078             continue;
5079           }
5080           lmod = lmod_from_directive(words[0]);
5081           if (lmod != pd->lmod)
5082             aerr("lmod change? %d->%d\n", pd->lmod, lmod);
5083         }
5084
5085         if (pd->count_alloc < pd->count + wordc) {
5086           pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
5087           pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
5088           my_assert_not(pd->d, NULL);
5089         }
5090         for (; i < wordc; i++) {
5091           if (IS(words[i], "offset")) {
5092             pd->type = OPT_OFFSET;
5093             i++;
5094           }
5095           p = strchr(words[i], ',');
5096           if (p != NULL)
5097             *p = 0;
5098           if (pd->type == OPT_OFFSET)
5099             pd->d[pd->count].u.label = strdup(words[i]);
5100           else
5101             pd->d[pd->count].u.val = parse_number(words[i]);
5102           pd->d[pd->count].bt_i = -1;
5103           pd->count++;
5104         }
5105         continue;
5106       }
5107
5108       if (in_func && !skip_func)
5109         gen_func(fout, g_fhdr, g_func, pi);
5110
5111       pending_endp = 0;
5112       in_func = 0;
5113       g_ida_func_attr = 0;
5114       skip_warned = 0;
5115       skip_func = 0;
5116       g_func[0] = 0;
5117       func_chunks_used = 0;
5118       func_chunk_i = -1;
5119       if (pi != 0) {
5120         memset(&ops, 0, pi * sizeof(ops[0]));
5121         memset(g_labels, 0, pi * sizeof(g_labels[0]));
5122         pi = 0;
5123       }
5124       g_eqcnt = 0;
5125       for (i = 0; i < g_func_pd_cnt; i++) {
5126         pd = &g_func_pd[i];
5127         if (pd->type == OPT_OFFSET) {
5128           for (j = 0; j < pd->count; j++)
5129             free(pd->d[j].u.label);
5130         }
5131         free(pd->d);
5132         pd->d = NULL;
5133       }
5134       g_func_pd_cnt = 0;
5135       pd = NULL;
5136       if (wordc == 0)
5137         continue;
5138     }
5139
5140     if (IS(words[1], "proc")) {
5141       if (in_func)
5142         aerr("proc '%s' while in_func '%s'?\n",
5143           words[0], g_func);
5144       p = words[0];
5145       if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
5146         skip_func = 1;
5147       strcpy(g_func, words[0]);
5148       set_label(0, words[0]);
5149       in_func = 1;
5150       continue;
5151     }
5152
5153     if (IS(words[1], "endp"))
5154     {
5155       if (!in_func)
5156         aerr("endp '%s' while not in_func?\n", words[0]);
5157       if (!IS(g_func, words[0]))
5158         aerr("endp '%s' while in_func '%s'?\n",
5159           words[0], g_func);
5160
5161       if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
5162         && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
5163       {
5164         // import jump
5165         skip_func = 1;
5166       }
5167
5168       if (!skip_func && func_chunks_used) {
5169         // start processing chunks
5170         struct chunk_item *ci, key = { g_func, 0 };
5171
5172         func_chunk_ret = ftell(fasm);
5173         func_chunk_ret_ln = asmln;
5174         if (!func_chunks_sorted) {
5175           qsort(func_chunks, func_chunk_cnt,
5176             sizeof(func_chunks[0]), cmp_chunks);
5177           func_chunks_sorted = 1;
5178         }
5179         ci = bsearch(&key, func_chunks, func_chunk_cnt,
5180                sizeof(func_chunks[0]), cmp_chunks);
5181         if (ci == NULL)
5182           aerr("'%s' needs chunks, but none found\n", g_func);
5183         func_chunk_i = ci - func_chunks;
5184         for (; func_chunk_i > 0; func_chunk_i--)
5185           if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
5186             break;
5187
5188         ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
5189         if (ret)
5190           aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
5191         asmln = func_chunks[func_chunk_i].asmln;
5192         func_chunk_i++;
5193         continue;
5194       }
5195       pending_endp = 1;
5196       continue;
5197     }
5198
5199     if (wordc == 2 && IS(words[1], "ends")) {
5200       if (!multi_seg)
5201         break;
5202
5203       // scan for next text segment
5204       while (fgets(line, sizeof(line), fasm)) {
5205         asmln++;
5206         p = sskip(line);
5207         if (*p == 0 || *p == ';')
5208           continue;
5209
5210         if (strstr(p, "segment para public 'CODE' use32"))
5211           break;
5212       }
5213
5214       continue;
5215     }
5216
5217     p = strchr(words[0], ':');
5218     if (p != NULL) {
5219       set_label(pi, words[0]);
5220       continue;
5221     }
5222
5223     if (!in_func || skip_func) {
5224       if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
5225         if (verbose)
5226           anote("skipping from '%s'\n", g_labels[pi]);
5227         skip_warned = 1;
5228       }
5229       g_labels[pi][0] = 0;
5230       continue;
5231     }
5232
5233     if (wordc > 1 && IS(words[1], "="))
5234     {
5235       if (wordc != 5)
5236         aerr("unhandled equ, wc=%d\n", wordc);
5237       if (g_eqcnt >= eq_alloc) {
5238         eq_alloc *= 2;
5239         g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
5240         my_assert_not(g_eqs, NULL);
5241       }
5242
5243       len = strlen(words[0]);
5244       if (len > sizeof(g_eqs[0].name) - 1)
5245         aerr("equ name too long: %d\n", len);
5246       strcpy(g_eqs[g_eqcnt].name, words[0]);
5247
5248       if (!IS(words[3], "ptr"))
5249         aerr("unhandled equ\n");
5250       if (IS(words[2], "dword"))
5251         g_eqs[g_eqcnt].lmod = OPLM_DWORD;
5252       else if (IS(words[2], "word"))
5253         g_eqs[g_eqcnt].lmod = OPLM_WORD;
5254       else if (IS(words[2], "byte"))
5255         g_eqs[g_eqcnt].lmod = OPLM_BYTE;
5256       else
5257         aerr("bad lmod: '%s'\n", words[2]);
5258
5259       g_eqs[g_eqcnt].offset = parse_number(words[4]);
5260       g_eqcnt++;
5261       continue;
5262     }
5263
5264     if (pi >= ARRAY_SIZE(ops))
5265       aerr("too many ops\n");
5266
5267     parse_op(&ops[pi], words, wordc);
5268
5269     if (sctproto != NULL) {
5270       if (ops[pi].op == OP_CALL)
5271         ops[pi].datap = sctproto;
5272       sctproto = NULL;
5273     }
5274     pi++;
5275   }
5276
5277   fclose(fout);
5278   fclose(fasm);
5279   fclose(g_fhdr);
5280
5281   return 0;
5282 }
5283
5284 // vim:ts=2:shiftwidth=2:expandtab