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