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