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