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