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