translate: start outputing after analysis, use define for userstack
[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   for (i = 0; i < g_func_pp->argc; i++) {
2897     if (g_func_pp->arg[i].reg != NULL) {
2898       reg = char_array_i(regs_r32,
2899               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2900       if (reg < 0)
2901         ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2902       regmask_arg |= 1 << reg;
2903     }
2904   }
2905
2906   // pass1:
2907   // - handle ebp/esp frame, remove ops related to it
2908   if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2909       && ops[1].op == OP_MOV
2910       && IS(opr_name(&ops[1], 0), "ebp")
2911       && IS(opr_name(&ops[1], 1), "esp"))
2912   {
2913     int ecx_push = 0;
2914
2915     g_bp_frame = 1;
2916     ops[0].flags |= OPF_RMD;
2917     ops[1].flags |= OPF_RMD;
2918     i = 2;
2919
2920     if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2921       g_stack_fsz = opr_const(&ops[2], 1);
2922       ops[2].flags |= OPF_RMD;
2923       i++;
2924     }
2925     else {
2926       // another way msvc builds stack frame..
2927       i = 2;
2928       while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2929         g_stack_fsz += 4;
2930         ops[i].flags |= OPF_RMD;
2931         ecx_push++;
2932         i++;
2933       }
2934       // and another way..
2935       if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2936           && ops[i].operand[1].type == OPT_CONST
2937           && ops[i + 1].op == OP_CALL
2938           && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2939       {
2940         g_stack_fsz += ops[i].operand[1].val;
2941         ops[i].flags |= OPF_RMD;
2942         i++;
2943         ops[i].flags |= OPF_RMD;
2944         i++;
2945       }
2946     }
2947
2948     found = 0;
2949     do {
2950       for (; i < opcnt; i++)
2951         if (ops[i].op == OP_RET)
2952           break;
2953       j = i - 1;
2954       if (i == opcnt && (ops[j].flags & OPF_JMP)) {
2955         if (found && is_like_tailjmp(j))
2956             break;
2957         j--;
2958       }
2959
2960       if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
2961           || ops[j].op == OP_LEAVE)
2962       {
2963         ops[j].flags |= OPF_RMD;
2964       }
2965       else if (!(g_ida_func_attr & IDAFA_NORETURN))
2966         ferr(&ops[j], "'pop ebp' expected\n");
2967
2968       if (g_stack_fsz != 0) {
2969         if (ops[j - 1].op == OP_MOV
2970             && IS(opr_name(&ops[j - 1], 0), "esp")
2971             && IS(opr_name(&ops[j - 1], 1), "ebp"))
2972         {
2973           ops[j - 1].flags |= OPF_RMD;
2974         }
2975         else if (ops[j].op != OP_LEAVE
2976           && !(g_ida_func_attr & IDAFA_NORETURN))
2977         {
2978           ferr(&ops[j - 1], "esp restore expected\n");
2979         }
2980
2981         if (ecx_push && ops[j - 2].op == OP_POP
2982           && IS(opr_name(&ops[j - 2], 0), "ecx"))
2983         {
2984           ferr(&ops[j - 2], "unexpected ecx pop\n");
2985         }
2986       }
2987
2988       found = 1;
2989       i++;
2990     } while (i < opcnt);
2991   }
2992   else {
2993     for (i = 0; i < opcnt; i++) {
2994       if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2995         break;
2996       if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2997         && ops[i].operand[1].type == OPT_CONST)
2998       {
2999         g_sp_frame = 1;
3000         break;
3001       }
3002     }
3003
3004     found = 0;
3005     if (g_sp_frame)
3006     {
3007       g_stack_fsz = ops[i].operand[1].val;
3008       ops[i].flags |= OPF_RMD;
3009
3010       i++;
3011       do {
3012         for (; i < opcnt; i++)
3013           if (ops[i].op == OP_RET)
3014             break;
3015         j = i - 1;
3016         if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3017           if (found && is_like_tailjmp(j))
3018               break;
3019           j--;
3020         }
3021
3022         if (ops[j].op != OP_ADD
3023             || !IS(opr_name(&ops[j], 0), "esp")
3024             || ops[j].operand[1].type != OPT_CONST
3025             || ops[j].operand[1].val != g_stack_fsz)
3026           ferr(&ops[j], "'add esp' expected\n");
3027         ops[j].flags |= OPF_RMD;
3028
3029         found = 1;
3030         i++;
3031       } while (i < opcnt);
3032     }
3033   }
3034
3035   // pass2:
3036   // - parse calls with labels
3037   // - resolve all branches
3038   for (i = 0; i < opcnt; i++)
3039   {
3040     po = &ops[i];
3041     po->bt_i = -1;
3042     po->btj = NULL;
3043
3044     if (po->flags & OPF_RMD)
3045       continue;
3046
3047     if (po->op == OP_CALL) {
3048       pp = NULL;
3049
3050       if (po->operand[0].type == OPT_LABEL) {
3051         tmpname = opr_name(po, 0);
3052         if (IS_START(tmpname, "loc_"))
3053           ferr(po, "call to loc_*\n");
3054         pp_c = proto_parse(fhdr, tmpname, 0);
3055         if (pp_c == NULL)
3056           ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3057
3058         pp = proto_clone(pp_c);
3059         my_assert_not(pp, NULL);
3060       }
3061       else if (po->datap != NULL) {
3062         pp = calloc(1, sizeof(*pp));
3063         my_assert_not(pp, NULL);
3064
3065         ret = parse_protostr(po->datap, pp);
3066         if (ret < 0)
3067           ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3068         free(po->datap);
3069         po->datap = NULL;
3070       }
3071
3072       if (pp != NULL) {
3073         if (pp->is_fptr)
3074           check_func_pp(po, pp, "fptr var call");
3075         if (pp->is_noreturn)
3076           po->flags |= OPF_TAIL;
3077       }
3078       po->pp = pp;
3079       continue;
3080     }
3081
3082     if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3083       continue;
3084
3085     if (po->operand[0].type == OPT_REGMEM) {
3086       char *p = strchr(po->operand[0].name, '[');
3087       if (p == NULL)
3088         goto tailcall;
3089       ret = p - po->operand[0].name;
3090       strncpy(buf1, po->operand[0].name, ret);
3091       buf1[ret] = 0;
3092
3093       for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3094         if (IS(g_func_pd[j].label, buf1)) {
3095           pd = &g_func_pd[j];
3096           break;
3097         }
3098       }
3099       if (pd == NULL)
3100         //ferr(po, "label '%s' not parsed?\n", buf1);
3101         goto tailcall;
3102       if (pd->type != OPT_OFFSET)
3103         ferr(po, "label '%s' with non-offset data?\n", buf1);
3104
3105       // find all labels, link
3106       for (j = 0; j < pd->count; j++) {
3107         for (l = 0; l < opcnt; l++) {
3108           if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
3109             add_label_ref(&g_label_refs[l], i);
3110             pd->d[j].bt_i = l;
3111             break;
3112           }
3113         }
3114       }
3115
3116       po->btj = pd;
3117       continue;
3118     }
3119
3120     for (l = 0; l < opcnt; l++) {
3121       if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
3122         if (l == i + 1 && po->op == OP_JMP) {
3123           // yet another alignment type..
3124           po->flags |= OPF_RMD;
3125           break;
3126         }
3127         add_label_ref(&g_label_refs[l], i);
3128         po->bt_i = l;
3129         break;
3130       }
3131     }
3132
3133     if (po->bt_i != -1 || (po->flags & OPF_RMD))
3134       continue;
3135
3136     if (po->operand[0].type == OPT_LABEL)
3137       // assume tail call
3138       goto tailcall;
3139
3140     ferr(po, "unhandled branch\n");
3141
3142 tailcall:
3143     po->op = OP_CALL;
3144     po->flags |= OPF_TAIL;
3145     if (i > 0 && ops[i - 1].op == OP_POP)
3146       po->flags |= OPF_ATAIL;
3147     i--; // reprocess
3148   }
3149
3150   // pass3:
3151   // - remove dead labels
3152   // - process calls
3153   for (i = 0; i < opcnt; i++)
3154   {
3155     if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
3156       g_labels[i][0] = 0;
3157
3158     po = &ops[i];
3159     if (po->flags & OPF_RMD)
3160       continue;
3161
3162     if (po->op == OP_CALL)
3163     {
3164       tmpname = opr_name(po, 0);
3165       pp = po->pp;
3166       if (pp == NULL)
3167       {
3168         // indirect call
3169         pp_c = resolve_icall(i, opcnt, &l);
3170         if (pp_c != NULL) {
3171           pp = proto_clone(pp_c);
3172           my_assert_not(pp, NULL);
3173           if (l)
3174             // not resolved just to single func
3175             pp->is_fptr = 1;
3176
3177           switch (po->operand[0].type) {
3178           case OPT_REG:
3179             // we resolved this call and no longer need the register
3180             po->regmask_src &= ~(1 << po->operand[0].reg);
3181             break;
3182           case OPT_REGMEM:
3183             pp->is_fptr = 1;
3184             break;
3185           default:
3186             break;
3187           }
3188         }
3189         if (pp == NULL) {
3190           pp = calloc(1, sizeof(*pp));
3191           my_assert_not(pp, NULL);
3192           pp->is_fptr = 1;
3193           ret = scan_for_esp_adjust(i + 1, opcnt, &j, &l);
3194           if (ret < 0) {
3195             if (!g_allow_regfunc)
3196               ferr(po, "non-__cdecl indirect call unhandled yet\n");
3197             pp->is_unresolved = 1;
3198             j = 0;
3199           }
3200           j /= 4;
3201           if (j > ARRAY_SIZE(pp->arg))
3202             ferr(po, "esp adjust too large: %d\n", j);
3203           pp->ret_type.name = strdup("int");
3204           pp->argc = pp->argc_stack = j;
3205           for (arg = 0; arg < pp->argc; arg++)
3206             pp->arg[arg].type.name = strdup("int");
3207         }
3208         po->pp = pp;
3209       }
3210
3211       // look for and make use of esp adjust
3212       ret = -1;
3213       if (!pp->is_stdcall && pp->argc_stack > 0)
3214         ret = scan_for_esp_adjust(i + 1, opcnt, &j, &l);
3215       if (ret >= 0) {
3216         if (pp->is_vararg) {
3217           if (j / 4 < pp->argc_stack)
3218             ferr(po, "esp adjust is too small: %x < %x\n",
3219               j, pp->argc_stack * 4);
3220           // modify pp to make it have varargs as normal args
3221           arg = pp->argc;
3222           pp->argc += j / 4 - pp->argc_stack;
3223           for (; arg < pp->argc; arg++) {
3224             pp->arg[arg].type.name = strdup("int");
3225             pp->argc_stack++;
3226           }
3227           if (pp->argc > ARRAY_SIZE(pp->arg))
3228             ferr(po, "too many args for '%s'\n", tmpname);
3229         }
3230         if (pp->argc_stack != j / 4)
3231           ferr(po, "stack tracking failed for '%s': %x %x\n",
3232             tmpname, pp->argc_stack * 4, j);
3233
3234         ops[ret].flags |= OPF_RMD;
3235         if (ops[ret].op == OP_POP && j > 4) {
3236           // deal with multi-pop stack adjust
3237           j = pp->argc_stack;
3238           while (ops[ret].op == OP_POP && j > 0 && ret < opcnt) {
3239             ops[ret].flags |= OPF_RMD;
3240             j--;
3241             ret++;
3242           }
3243         }
3244         else if (!l) {
3245           // a bit of a hack, but deals with use of
3246           // single adj for multiple calls
3247           ops[ret].operand[1].val -= j;
3248         }
3249       }
3250       else if (pp->is_vararg)
3251         ferr(po, "missing esp_adjust for vararg func '%s'\n",
3252           pp->name);
3253
3254       if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
3255         // since we know the args, collect them
3256         collect_call_args(po, i, pp, &regmask, &save_arg_vars,
3257           i + opcnt * 2);
3258       }
3259
3260       if (strstr(pp->ret_type.name, "int64"))
3261         need_tmp64 = 1;
3262     }
3263   }
3264
3265   // pass4:
3266   // - find POPs for PUSHes, rm both
3267   // - scan for STD/CLD, propagate DF
3268   // - scan for all used registers
3269   // - find flag set ops for their users
3270   // - do unreselved calls
3271   // - declare indirect functions
3272   for (i = 0; i < opcnt; i++) {
3273     po = &ops[i];
3274     if (po->flags & OPF_RMD)
3275       continue;
3276
3277     if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3278       reg = po->operand[0].reg;
3279       if (!(regmask & (1 << reg)))
3280         // not a reg save after all, rerun scan_for_pop
3281         po->flags &= ~OPF_RSAVE;
3282       else
3283         regmask_save |= 1 << reg;
3284     }
3285
3286     if (po->op == OP_PUSH && po->argnum == 0
3287       && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
3288     {
3289       if (po->operand[0].type == OPT_REG)
3290       {
3291         reg = po->operand[0].reg;
3292         if (reg < 0)
3293           ferr(po, "reg not set for push?\n");
3294
3295         depth = 0;
3296         ret = scan_for_pop(i + 1, opcnt,
3297                 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3298         if (ret == 1) {
3299           if (depth > 1)
3300             ferr(po, "too much depth: %d\n", depth);
3301
3302           po->flags |= OPF_RMD;
3303           scan_for_pop(i + 1, opcnt, po->operand[0].name,
3304             i + opcnt * 4, 0, &depth, 1);
3305           continue;
3306         }
3307         ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3308         if (ret == 0) {
3309           arg = OPF_RMD;
3310           if (regmask & (1 << reg)) {
3311             if (regmask_save & (1 << reg))
3312               ferr(po, "%s already saved?\n", po->operand[0].name);
3313             arg = OPF_RSAVE;
3314           }
3315           po->flags |= arg;
3316           scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3317           continue;
3318         }
3319       }
3320       else if (po->operand[0].type == OPT_CONST) {
3321         for (j = i + 1; j < opcnt; j++) {
3322           if ((ops[j].flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
3323             || ops[j].op == OP_PUSH || g_labels[i][0] != 0)
3324           {
3325             break;
3326           }
3327
3328           if (!(ops[j].flags & OPF_RMD) && ops[j].op == OP_POP)
3329           {
3330             po->flags |= OPF_RMD;
3331             ops[j].datap = po;
3332             break;
3333           }
3334         }
3335       }
3336     }
3337
3338     if (po->op == OP_STD) {
3339       po->flags |= OPF_DF | OPF_RMD;
3340       scan_propagate_df(i + 1, opcnt);
3341     }
3342
3343     regmask_now = po->regmask_src | po->regmask_dst;
3344     if (regmask_now & (1 << xBP)) {
3345       if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3346         if (po->regmask_dst & (1 << xBP))
3347           // compiler decided to drop bp frame and use ebp as scratch
3348           scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
3349         else
3350           regmask_now &= ~(1 << xBP);
3351       }
3352     }
3353
3354     regmask |= regmask_now;
3355
3356     if (po->flags & OPF_CC)
3357     {
3358       int setters[16], cnt = 0, branched = 0;
3359
3360       ret = scan_for_flag_set(i, i + opcnt * 6,
3361               &branched, setters, &cnt);
3362       if (ret < 0 || cnt <= 0)
3363         ferr(po, "unable to trace flag setter(s)\n");
3364       if (cnt > ARRAY_SIZE(setters))
3365         ferr(po, "too many flag setters\n");
3366
3367       for (j = 0; j < cnt; j++)
3368       {
3369         tmp_op = &ops[setters[j]]; // flag setter
3370         pfomask = 0;
3371
3372         // to get nicer code, we try to delay test and cmp;
3373         // if we can't because of operand modification, or if we
3374         // have arith op, or branch, make it calculate flags explicitly
3375         if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
3376         {
3377           if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
3378             pfomask = 1 << po->pfo;
3379         }
3380         else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
3381           pfomask = 1 << po->pfo;
3382         }
3383         else {
3384           // see if we'll be able to handle based on op result
3385           if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3386                && po->pfo != PFO_Z && po->pfo != PFO_S
3387                && po->pfo != PFO_P)
3388               || branched
3389               || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3390           {
3391             pfomask = 1 << po->pfo;
3392           }
3393
3394           if (tmp_op->op == OP_ADD && po->pfo == PFO_C)
3395             need_tmp64 = 1;
3396         }
3397         if (pfomask) {
3398           tmp_op->pfomask |= pfomask;
3399           cond_vars |= pfomask;
3400         }
3401         // note: may overwrite, currently not a problem
3402         po->datap = tmp_op;
3403       }
3404
3405       if (po->op == OP_RCL || po->op == OP_RCR
3406        || po->op == OP_ADC || po->op == OP_SBB)
3407         cond_vars |= 1 << PFO_C;
3408     }
3409
3410     if (po->op == OP_CMPS || po->op == OP_SCAS) {
3411       cond_vars |= 1 << PFO_Z;
3412     }
3413     else if (po->op == OP_MUL
3414       || (po->op == OP_IMUL && po->operand_cnt == 1))
3415     {
3416       need_tmp64 = 1;
3417     }
3418     else if (po->op == OP_CALL) {
3419       pp = po->pp;
3420       if (pp == NULL)
3421         ferr(po, "NULL pp\n");
3422
3423       if (pp->is_unresolved) {
3424         int regmask_stack = 0;
3425         collect_call_args(po, i, pp, &regmask, &save_arg_vars,
3426           i + opcnt * 2);
3427
3428         // this is pretty rough guess:
3429         // see ecx and edx were pushed (and not their saved versions)
3430         for (arg = 0; arg < pp->argc; arg++) {
3431           if (pp->arg[arg].reg != NULL)
3432             continue;
3433
3434           tmp_op = pp->arg[arg].datap;
3435           if (tmp_op == NULL)
3436             ferr(po, "parsed_op missing for arg%d\n", arg);
3437           if (tmp_op->argnum == 0 && tmp_op->operand[0].type == OPT_REG)
3438             regmask_stack |= 1 << tmp_op->operand[0].reg;
3439         }
3440
3441         if (!((regmask_stack & (1 << xCX))
3442           && (regmask_stack & (1 << xDX))))
3443         {
3444           if (pp->argc_stack != 0
3445            || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
3446           {
3447             pp_insert_reg_arg(pp, "ecx");
3448             pp->is_fastcall = 1;
3449             regmask_init |= 1 << xCX;
3450             regmask |= 1 << xCX;
3451           }
3452           if (pp->argc_stack != 0
3453            || ((regmask | regmask_arg) & (1 << xDX)))
3454           {
3455             pp_insert_reg_arg(pp, "edx");
3456             regmask_init |= 1 << xDX;
3457             regmask |= 1 << xDX;
3458           }
3459         }
3460
3461         // note: __cdecl doesn't fall into is_unresolved category
3462         if (pp->argc_stack > 0)
3463           pp->is_stdcall = 1;
3464       }
3465
3466       for (arg = 0; arg < pp->argc; arg++) {
3467         if (pp->arg[arg].reg != NULL) {
3468           reg = char_array_i(regs_r32,
3469                   ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
3470           if (reg < 0)
3471             ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
3472           if (!(regmask & (1 << reg))) {
3473             regmask_init |= 1 << reg;
3474             regmask |= 1 << reg;
3475           }
3476         }
3477       }
3478     }
3479     else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3480       regmask |= 1 << xAX;
3481     else if (po->op == OP_DIV || po->op == OP_IDIV) {
3482       // 32bit division is common, look for it
3483       if (po->op == OP_DIV)
3484         ret = scan_for_reg_clear(i, xDX);
3485       else
3486         ret = scan_for_cdq_edx(i);
3487       if (ret >= 0)
3488         po->flags |= OPF_32BIT;
3489       else
3490         need_tmp64 = 1;
3491     }
3492     else if (po->op == OP_CLD)
3493       po->flags |= OPF_RMD;
3494
3495     if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
3496       need_tmp_var = 1;
3497     }
3498   }
3499
3500   // pass4:
3501   // - confirm regmask_save, it might have been reduced
3502   if (regmask_save != 0)
3503   {
3504     regmask_save = 0;
3505     for (i = 0; i < opcnt; i++) {
3506       po = &ops[i];
3507       if (po->flags & OPF_RMD)
3508         continue;
3509
3510       if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
3511         regmask_save |= 1 << po->operand[0].reg;
3512     }
3513   }
3514
3515   // output starts here
3516
3517   // define userstack size
3518   if (g_func_pp->is_userstack) {
3519     fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
3520     fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
3521     fprintf(fout, "#endif\n");
3522   }
3523
3524   // the function itself
3525   fprintf(fout, "%s ", g_func_pp->ret_type.name);
3526   output_pp_attrs(fout, g_func_pp, g_ida_func_attr & IDAFA_NORETURN);
3527   fprintf(fout, "%s(", g_func_pp->name);
3528
3529   for (i = 0; i < g_func_pp->argc; i++) {
3530     if (i > 0)
3531       fprintf(fout, ", ");
3532     if (g_func_pp->arg[i].fptr != NULL) {
3533       // func pointer..
3534       pp = g_func_pp->arg[i].fptr;
3535       fprintf(fout, "%s (", pp->ret_type.name);
3536       output_pp_attrs(fout, pp, 0);
3537       fprintf(fout, "*a%d)(", i + 1);
3538       for (j = 0; j < pp->argc; j++) {
3539         if (j > 0)
3540           fprintf(fout, ", ");
3541         if (pp->arg[j].fptr)
3542           ferr(ops, "nested fptr\n");
3543         fprintf(fout, "%s", pp->arg[j].type.name);
3544       }
3545       if (pp->is_vararg) {
3546         if (j > 0)
3547           fprintf(fout, ", ");
3548         fprintf(fout, "...");
3549       }
3550       fprintf(fout, ")");
3551     }
3552     else if (g_func_pp->arg[i].type.is_retreg) {
3553       fprintf(fout, "u32 *r_%s", g_func_pp->arg[i].reg);
3554     }
3555     else {
3556       fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
3557     }
3558   }
3559   if (g_func_pp->is_vararg) {
3560     if (i > 0)
3561       fprintf(fout, ", ");
3562     fprintf(fout, "...");
3563   }
3564
3565   fprintf(fout, ")\n{\n");
3566
3567   // declare indirect functions
3568   for (i = 0; i < opcnt; i++) {
3569     po = &ops[i];
3570     if (po->flags & OPF_RMD)
3571       continue;
3572
3573     if (po->op == OP_CALL) {
3574       pp = po->pp;
3575       if (pp == NULL)
3576         ferr(po, "NULL pp\n");
3577
3578       if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
3579         if (pp->name[0] != 0) {
3580           memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
3581           memcpy(pp->name, "i_", 2);
3582
3583           // might be declared already
3584           found = 0;
3585           for (j = 0; j < i; j++) {
3586             if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
3587               if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
3588                 found = 1;
3589                 break;
3590               }
3591             }
3592           }
3593           if (found)
3594             continue;
3595         }
3596         else
3597           snprintf(pp->name, sizeof(pp->name), "icall%d", i);
3598
3599         fprintf(fout, "  %s (", pp->ret_type.name);
3600         output_pp_attrs(fout, pp, 0);
3601         fprintf(fout, "*%s)(", pp->name);
3602         for (j = 0; j < pp->argc; j++) {
3603           if (j > 0)
3604             fprintf(fout, ", ");
3605           fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3606         }
3607         fprintf(fout, ");\n");
3608       }
3609     }
3610   }
3611
3612   // output LUTs/jumptables
3613   for (i = 0; i < g_func_pd_cnt; i++) {
3614     pd = &g_func_pd[i];
3615     fprintf(fout, "  static const ");
3616     if (pd->type == OPT_OFFSET) {
3617       fprintf(fout, "void *jt_%s[] =\n    { ", pd->label);
3618
3619       for (j = 0; j < pd->count; j++) {
3620         if (j > 0)
3621           fprintf(fout, ", ");
3622         fprintf(fout, "&&%s", pd->d[j].u.label);
3623       }
3624     }
3625     else {
3626       fprintf(fout, "%s %s[] =\n    { ",
3627         lmod_type_u(ops, pd->lmod), pd->label);
3628
3629       for (j = 0; j < pd->count; j++) {
3630         if (j > 0)
3631           fprintf(fout, ", ");
3632         fprintf(fout, "%u", pd->d[j].u.val);
3633       }
3634     }
3635     fprintf(fout, " };\n");
3636     had_decl = 1;
3637   }
3638
3639   // declare stack frame, va_arg
3640   if (g_stack_fsz) {
3641     fprintf(fout, "  union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3642       (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3643     had_decl = 1;
3644   }
3645
3646   if (g_func_pp->is_userstack) {
3647     fprintf(fout, "  u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
3648     fprintf(fout, "  u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
3649     had_decl = 1;
3650   }
3651
3652   if (g_func_pp->is_vararg) {
3653     fprintf(fout, "  va_list ap;\n");
3654     had_decl = 1;
3655   }
3656
3657   // declare arg-registers
3658   for (i = 0; i < g_func_pp->argc; i++) {
3659     if (g_func_pp->arg[i].reg != NULL) {
3660       reg = char_array_i(regs_r32,
3661               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3662       if (regmask & (1 << reg)) {
3663         if (g_func_pp->arg[i].type.is_retreg)
3664           fprintf(fout, "  u32 %s = *r_%s;\n",
3665             g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
3666         else
3667           fprintf(fout, "  u32 %s = (u32)a%d;\n",
3668             g_func_pp->arg[i].reg, i + 1);
3669       }
3670       else {
3671         if (g_func_pp->arg[i].type.is_retreg)
3672           ferr(ops, "retreg '%s' is unused?\n",
3673             g_func_pp->arg[i].reg);
3674         fprintf(fout, "  // %s = a%d; // unused\n",
3675           g_func_pp->arg[i].reg, i + 1);
3676       }
3677       had_decl = 1;
3678     }
3679   }
3680
3681   regmask_now = regmask & ~regmask_arg;
3682   regmask_now &= ~(1 << xSP);
3683   if (regmask_now) {
3684     for (reg = 0; reg < 8; reg++) {
3685       if (regmask_now & (1 << reg)) {
3686         fprintf(fout, "  u32 %s", regs_r32[reg]);
3687         if (regmask_init & (1 << reg))
3688           fprintf(fout, " = 0");
3689         fprintf(fout, ";\n");
3690         had_decl = 1;
3691       }
3692     }
3693   }
3694
3695   if (regmask_save) {
3696     for (reg = 0; reg < 8; reg++) {
3697       if (regmask_save & (1 << reg)) {
3698         fprintf(fout, "  u32 s_%s;\n", regs_r32[reg]);
3699         had_decl = 1;
3700       }
3701     }
3702   }
3703
3704   if (save_arg_vars) {
3705     for (reg = 0; reg < 32; reg++) {
3706       if (save_arg_vars & (1 << reg)) {
3707         fprintf(fout, "  u32 s_a%d;\n", reg + 1);
3708         had_decl = 1;
3709       }
3710     }
3711   }
3712
3713   if (cond_vars) {
3714     for (i = 0; i < 8; i++) {
3715       if (cond_vars & (1 << i)) {
3716         fprintf(fout, "  u32 cond_%s;\n", parsed_flag_op_names[i]);
3717         had_decl = 1;
3718       }
3719     }
3720   }
3721
3722   if (need_tmp_var) {
3723     fprintf(fout, "  u32 tmp;\n");
3724     had_decl = 1;
3725   }
3726
3727   if (need_tmp64) {
3728     fprintf(fout, "  u64 tmp64;\n");
3729     had_decl = 1;
3730   }
3731
3732   if (had_decl)
3733     fprintf(fout, "\n");
3734
3735   if (g_func_pp->is_vararg) {
3736     if (g_func_pp->argc_stack == 0)
3737       ferr(ops, "vararg func without stack args?\n");
3738     fprintf(fout, "  va_start(ap, a%d);\n", g_func_pp->argc);
3739   }
3740
3741   // output ops
3742   for (i = 0; i < opcnt; i++)
3743   {
3744     if (g_labels[i][0] != 0) {
3745       fprintf(fout, "\n%s:\n", g_labels[i]);
3746       label_pending = 1;
3747
3748       delayed_flag_op = NULL;
3749       last_arith_dst = NULL;
3750     }
3751
3752     po = &ops[i];
3753     if (po->flags & OPF_RMD)
3754       continue;
3755
3756     no_output = 0;
3757
3758     #define assert_operand_cnt(n_) \
3759       if (po->operand_cnt != n_) \
3760         ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3761
3762     // conditional/flag using op?
3763     if (po->flags & OPF_CC)
3764     {
3765       int is_delayed = 0;
3766
3767       tmp_op = po->datap;
3768
3769       // we go through all this trouble to avoid using parsed_flag_op,
3770       // which makes generated code much nicer
3771       if (delayed_flag_op != NULL)
3772       {
3773         out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
3774           po->pfo, po->pfo_inv);
3775         is_delayed = 1;
3776       }
3777       else if (last_arith_dst != NULL
3778         && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
3779            || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3780            ))
3781       {
3782         out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3783         out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
3784           last_arith_dst->lmod, buf3);
3785         is_delayed = 1;
3786       }
3787       else if (tmp_op != NULL) {
3788         // use preprocessed flag calc results
3789         if (!(tmp_op->pfomask & (1 << po->pfo)))
3790           ferr(po, "not prepared for pfo %d\n", po->pfo);
3791
3792         // note: pfo_inv was not yet applied
3793         snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3794           po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
3795       }
3796       else {
3797         ferr(po, "all methods of finding comparison failed\n");
3798       }
3799  
3800       if (po->flags & OPF_JMP) {
3801         fprintf(fout, "  if %s", buf1);
3802       }
3803       else if (po->op == OP_RCL || po->op == OP_RCR
3804                || po->op == OP_ADC || po->op == OP_SBB)
3805       {
3806         if (is_delayed)
3807           fprintf(fout, "  cond_%s = %s;\n",
3808             parsed_flag_op_names[po->pfo], buf1);
3809       }
3810       else if (po->flags & OPF_DATA) { // SETcc
3811         out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3812         fprintf(fout, "  %s = %s;", buf2, buf1);
3813       }
3814       else {
3815         ferr(po, "unhandled conditional op\n");
3816       }
3817     }
3818
3819     pfomask = po->pfomask;
3820
3821     if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
3822       struct parsed_opr opr = {0,};
3823       opr.type = OPT_REG;
3824       opr.reg = xCX;
3825       opr.lmod = OPLM_DWORD;
3826       ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
3827
3828       if (ret != 1 || uval == 0) {
3829         // we need initial flags for ecx=0 case..
3830         if (i > 0 && ops[i - 1].op == OP_XOR
3831           && IS(ops[i - 1].operand[0].name,
3832                 ops[i - 1].operand[1].name))
3833         {
3834           fprintf(fout, "  cond_z = ");
3835           if (pfomask & (1 << PFO_C))
3836             fprintf(fout, "cond_c = ");
3837           fprintf(fout, "0;\n");
3838         }
3839         else if (last_arith_dst != NULL) {
3840           out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3841           out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
3842             last_arith_dst->lmod, buf3);
3843           fprintf(fout, "  cond_z = %s;\n", buf1);
3844         }
3845         else
3846           ferr(po, "missing initial ZF\n");
3847       }
3848     }
3849
3850     switch (po->op)
3851     {
3852       case OP_MOV:
3853         assert_operand_cnt(2);
3854         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3855         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3856         default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
3857         fprintf(fout, "  %s = %s;", buf1,
3858             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3859               buf3, 0));
3860         break;
3861
3862       case OP_LEA:
3863         assert_operand_cnt(2);
3864         po->operand[1].lmod = OPLM_DWORD; // always
3865         fprintf(fout, "  %s = %s;",
3866             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3867             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3868               NULL, 1));
3869         break;
3870
3871       case OP_MOVZX:
3872         assert_operand_cnt(2);
3873         fprintf(fout, "  %s = %s;",
3874             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3875             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3876         break;
3877
3878       case OP_MOVSX:
3879         assert_operand_cnt(2);
3880         switch (po->operand[1].lmod) {
3881         case OPLM_BYTE:
3882           strcpy(buf3, "(s8)");
3883           break;
3884         case OPLM_WORD:
3885           strcpy(buf3, "(s16)");
3886           break;
3887         default:
3888           ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3889         }
3890         fprintf(fout, "  %s = %s;",
3891             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3892             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3893               buf3, 0));
3894         break;
3895
3896       case OP_XCHG:
3897         assert_operand_cnt(2);
3898         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3899         fprintf(fout, "  tmp = %s;",
3900           out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
3901         fprintf(fout, " %s = %s;",
3902           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3903           out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3904             default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
3905         fprintf(fout, " %s = %stmp;",
3906           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
3907           default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
3908         snprintf(g_comment, sizeof(g_comment), "xchg");
3909         break;
3910
3911       case OP_NOT:
3912         assert_operand_cnt(1);
3913         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3914         fprintf(fout, "  %s = ~%s;", buf1, buf1);
3915         break;
3916
3917       case OP_CDQ:
3918         assert_operand_cnt(2);
3919         fprintf(fout, "  %s = (s32)%s >> 31;",
3920             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3921             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3922         strcpy(g_comment, "cdq");
3923         break;
3924
3925       case OP_LODS:
3926         assert_operand_cnt(3);
3927         if (po->flags & OPF_REP) {
3928           // hmh..
3929           ferr(po, "TODO\n");
3930         }
3931         else {
3932           fprintf(fout, "  eax = %sesi; esi %c= %d;",
3933             lmod_cast_u_ptr(po, po->operand[0].lmod),
3934             (po->flags & OPF_DF) ? '-' : '+',
3935             lmod_bytes(po, po->operand[0].lmod));
3936           strcpy(g_comment, "lods");
3937         }
3938         break;
3939
3940       case OP_STOS:
3941         assert_operand_cnt(3);
3942         if (po->flags & OPF_REP) {
3943           fprintf(fout, "  for (; ecx != 0; ecx--, edi %c= %d)\n",
3944             (po->flags & OPF_DF) ? '-' : '+',
3945             lmod_bytes(po, po->operand[0].lmod));
3946           fprintf(fout, "    %sedi = eax;",
3947             lmod_cast_u_ptr(po, po->operand[0].lmod));
3948           strcpy(g_comment, "rep stos");
3949         }
3950         else {
3951           fprintf(fout, "  %sedi = eax; edi %c= %d;",
3952             lmod_cast_u_ptr(po, po->operand[0].lmod),
3953             (po->flags & OPF_DF) ? '-' : '+',
3954             lmod_bytes(po, po->operand[0].lmod));
3955           strcpy(g_comment, "stos");
3956         }
3957         break;
3958
3959       case OP_MOVS:
3960         assert_operand_cnt(3);
3961         j = lmod_bytes(po, po->operand[0].lmod);
3962         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3963         l = (po->flags & OPF_DF) ? '-' : '+';
3964         if (po->flags & OPF_REP) {
3965           fprintf(fout,
3966             "  for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
3967             l, j, l, j);
3968           fprintf(fout,
3969             "    %sedi = %sesi;", buf1, buf1);
3970           strcpy(g_comment, "rep movs");
3971         }
3972         else {
3973           fprintf(fout, "  %sedi = %sesi; edi %c= %d; esi %c= %d;",
3974             buf1, buf1, l, j, l, j);
3975           strcpy(g_comment, "movs");
3976         }
3977         break;
3978
3979       case OP_CMPS:
3980         // repe ~ repeat while ZF=1
3981         assert_operand_cnt(3);
3982         j = lmod_bytes(po, po->operand[0].lmod);
3983         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3984         l = (po->flags & OPF_DF) ? '-' : '+';
3985         if (po->flags & OPF_REP) {
3986           fprintf(fout,
3987             "  for (; ecx != 0; ecx--) {\n");
3988           if (pfomask & (1 << PFO_C)) {
3989             // ugh..
3990             fprintf(fout,
3991             "    cond_c = %sesi < %sedi;\n", buf1, buf1);
3992             pfomask &= ~(1 << PFO_C);
3993           }
3994           fprintf(fout,
3995             "    cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
3996               buf1, buf1, l, j, l, j);
3997           fprintf(fout,
3998             "    if (cond_z %s 0) break;\n",
3999               (po->flags & OPF_REPZ) ? "==" : "!=");
4000           fprintf(fout,
4001             "  }");
4002           snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
4003             (po->flags & OPF_REPZ) ? "e" : "ne");
4004         }
4005         else {
4006           fprintf(fout,
4007             "  cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
4008             buf1, buf1, l, j, l, j);
4009           strcpy(g_comment, "cmps");
4010         }
4011         pfomask &= ~(1 << PFO_Z);
4012         last_arith_dst = NULL;
4013         delayed_flag_op = NULL;
4014         break;
4015
4016       case OP_SCAS:
4017         // only does ZF (for now)
4018         // repe ~ repeat while ZF=1
4019         assert_operand_cnt(3);
4020         j = lmod_bytes(po, po->operand[0].lmod);
4021         l = (po->flags & OPF_DF) ? '-' : '+';
4022         if (po->flags & OPF_REP) {
4023           fprintf(fout,
4024             "  for (; ecx != 0; ecx--) {\n");
4025           fprintf(fout,
4026             "    cond_z = (%seax == %sedi); edi %c= %d;\n",
4027               lmod_cast_u(po, po->operand[0].lmod),
4028               lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4029           fprintf(fout,
4030             "    if (cond_z %s 0) break;\n",
4031               (po->flags & OPF_REPZ) ? "==" : "!=");
4032           fprintf(fout,
4033             "  }");
4034           snprintf(g_comment, sizeof(g_comment), "rep%s scas",
4035             (po->flags & OPF_REPZ) ? "e" : "ne");
4036         }
4037         else {
4038           fprintf(fout, "  cond_z = (%seax == %sedi); edi %c= %d;",
4039               lmod_cast_u(po, po->operand[0].lmod),
4040               lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4041           strcpy(g_comment, "scas");
4042         }
4043         pfomask &= ~(1 << PFO_Z);
4044         last_arith_dst = NULL;
4045         delayed_flag_op = NULL;
4046         break;
4047
4048       // arithmetic w/flags
4049       case OP_AND:
4050       case OP_OR:
4051         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4052         // fallthrough
4053       dualop_arith:
4054         assert_operand_cnt(2);
4055         fprintf(fout, "  %s %s= %s;",
4056             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4057             op_to_c(po),
4058             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4059         output_std_flags(fout, po, &pfomask, buf1);
4060         last_arith_dst = &po->operand[0];
4061         delayed_flag_op = NULL;
4062         break;
4063
4064       case OP_SHL:
4065       case OP_SHR:
4066         assert_operand_cnt(2);
4067         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4068         if (pfomask & (1 << PFO_C)) {
4069           if (po->operand[1].type == OPT_CONST) {
4070             l = lmod_bytes(po, po->operand[0].lmod) * 8;
4071             j = po->operand[1].val;
4072             j %= l;
4073             if (j != 0) {
4074               if (po->op == OP_SHL)
4075                 j = l - j;
4076               else
4077                 j -= 1;
4078               fprintf(fout, "  cond_c = (%s >> %d) & 1;\n",
4079                 buf1, j);
4080             }
4081             else
4082               ferr(po, "zero shift?\n");
4083           }
4084           else
4085             ferr(po, "TODO\n");
4086           pfomask &= ~(1 << PFO_C);
4087         }
4088         fprintf(fout, "  %s %s= %s;", buf1, op_to_c(po),
4089             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4090         output_std_flags(fout, po, &pfomask, buf1);
4091         last_arith_dst = &po->operand[0];
4092         delayed_flag_op = NULL;
4093         break;
4094
4095       case OP_SAR:
4096         assert_operand_cnt(2);
4097         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4098         fprintf(fout, "  %s = %s%s >> %s;", buf1,
4099           lmod_cast_s(po, po->operand[0].lmod), buf1,
4100           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4101         output_std_flags(fout, po, &pfomask, buf1);
4102         last_arith_dst = &po->operand[0];
4103         delayed_flag_op = NULL;
4104         break;
4105
4106       case OP_ROL:
4107       case OP_ROR:
4108         assert_operand_cnt(2);
4109         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4110         if (po->operand[1].type == OPT_CONST) {
4111           j = po->operand[1].val;
4112           j %= lmod_bytes(po, po->operand[0].lmod) * 8;
4113           fprintf(fout, po->op == OP_ROL ?
4114             "  %s = (%s << %d) | (%s >> %d);" :
4115             "  %s = (%s >> %d) | (%s << %d);",
4116             buf1, buf1, j, buf1,
4117             lmod_bytes(po, po->operand[0].lmod) * 8 - j);
4118         }
4119         else
4120           ferr(po, "TODO\n");
4121         output_std_flags(fout, po, &pfomask, buf1);
4122         last_arith_dst = &po->operand[0];
4123         delayed_flag_op = NULL;
4124         break;
4125
4126       case OP_RCL:
4127       case OP_RCR:
4128         assert_operand_cnt(2);
4129         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4130         l = lmod_bytes(po, po->operand[0].lmod) * 8;
4131         if (po->operand[1].type == OPT_CONST) {
4132           j = po->operand[1].val % l;
4133           if (j == 0)
4134             ferr(po, "zero rotate\n");
4135           fprintf(fout, "  tmp = (%s >> %d) & 1;\n",
4136             buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
4137           if (po->op == OP_RCL) {
4138             fprintf(fout,
4139               "  %s = (%s << %d) | (cond_c << %d)",
4140               buf1, buf1, j, j - 1);
4141             if (j != 1)
4142               fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
4143           }
4144           else {
4145             fprintf(fout,
4146               "  %s = (%s >> %d) | (cond_c << %d)",
4147               buf1, buf1, j, l - j);
4148             if (j != 1)
4149               fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
4150           }
4151           fprintf(fout, ";\n");
4152           fprintf(fout, "  cond_c = tmp;");
4153         }
4154         else
4155           ferr(po, "TODO\n");
4156         strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
4157         output_std_flags(fout, po, &pfomask, buf1);
4158         last_arith_dst = &po->operand[0];
4159         delayed_flag_op = NULL;
4160         break;
4161
4162       case OP_XOR:
4163         assert_operand_cnt(2);
4164         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4165         if (IS(opr_name(po, 0), opr_name(po, 1))) {
4166           // special case for XOR
4167           if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
4168             fprintf(fout, "  cond_be = 1;\n");
4169             pfomask &= ~(1 << PFO_BE);
4170           }
4171           fprintf(fout, "  %s = 0;",
4172             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4173           last_arith_dst = &po->operand[0];
4174           delayed_flag_op = NULL;
4175           break;
4176         }
4177         goto dualop_arith;
4178
4179       case OP_ADD:
4180         assert_operand_cnt(2);
4181         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4182         if (pfomask & (1 << PFO_C)) {
4183           fprintf(fout, "  tmp64 = (u64)%s + %s;\n",
4184             out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]),
4185             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4186           fprintf(fout, "  cond_c = tmp64 >> 32;\n");
4187           fprintf(fout, "  %s = (u32)tmp64;",
4188             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4189           strcat(g_comment, "add64");
4190           pfomask &= ~(1 << PFO_C);
4191           output_std_flags(fout, po, &pfomask, buf1);
4192           last_arith_dst = &po->operand[0];
4193           delayed_flag_op = NULL;
4194           break;
4195         }
4196         goto dualop_arith;
4197
4198       case OP_SUB:
4199         assert_operand_cnt(2);
4200         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4201         if (pfomask & (1 << PFO_C)) {
4202           fprintf(fout, "  cond_c = %s < %s;\n",
4203             out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]),
4204             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4205           pfomask &= ~(1 << PFO_C);
4206         }
4207         goto dualop_arith;
4208
4209       case OP_ADC:
4210       case OP_SBB:
4211         assert_operand_cnt(2);
4212         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4213         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4214         if (po->op == OP_SBB
4215           && IS(po->operand[0].name, po->operand[1].name))
4216         {
4217           // avoid use of unitialized var
4218           fprintf(fout, "  %s = -cond_c;", buf1);
4219           // carry remains what it was
4220           pfomask &= ~(1 << PFO_C);
4221         }
4222         else {
4223           fprintf(fout, "  %s %s= %s + cond_c;", buf1, op_to_c(po),
4224             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4225         }
4226         output_std_flags(fout, po, &pfomask, buf1);
4227         last_arith_dst = &po->operand[0];
4228         delayed_flag_op = NULL;
4229         break;
4230
4231       case OP_BSF:
4232         assert_operand_cnt(2);
4233         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4234         fprintf(fout, "  %s = %s ? __builtin_ffs(%s) - 1 : 0;",
4235           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4236           buf2, buf2);
4237         output_std_flags(fout, po, &pfomask, buf1);
4238         last_arith_dst = &po->operand[0];
4239         delayed_flag_op = NULL;
4240         strcat(g_comment, "bsf");
4241         break;
4242
4243       case OP_INC:
4244       case OP_DEC:
4245         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4246         if (po->operand[0].type == OPT_REG) {
4247           strcpy(buf2, po->op == OP_INC ? "++" : "--");
4248           fprintf(fout, "  %s%s;", buf1, buf2);
4249         }
4250         else {
4251           strcpy(buf2, po->op == OP_INC ? "+" : "-");
4252           fprintf(fout, "  %s %s= 1;", buf1, buf2);
4253         }
4254         output_std_flags(fout, po, &pfomask, buf1);
4255         last_arith_dst = &po->operand[0];
4256         delayed_flag_op = NULL;
4257         break;
4258
4259       case OP_NEG:
4260         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4261         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
4262         fprintf(fout, "  %s = -%s%s;", buf1,
4263           lmod_cast_s(po, po->operand[0].lmod), buf2);
4264         last_arith_dst = &po->operand[0];
4265         delayed_flag_op = NULL;
4266         if (pfomask & (1 << PFO_C)) {
4267           fprintf(fout, "\n  cond_c = (%s != 0);", buf1);
4268           pfomask &= ~(1 << PFO_C);
4269         }
4270         break;
4271
4272       case OP_IMUL:
4273         if (po->operand_cnt == 2) {
4274           propagate_lmod(po, &po->operand[0], &po->operand[1]);
4275           goto dualop_arith;
4276         }
4277         if (po->operand_cnt == 3)
4278           ferr(po, "TODO imul3\n");
4279         // fallthrough
4280       case OP_MUL:
4281         assert_operand_cnt(1);
4282         strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
4283         fprintf(fout, "  tmp64 = %seax * %s%s;\n", buf1, buf1,
4284           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
4285         fprintf(fout, "  edx = tmp64 >> 32;\n");
4286         fprintf(fout, "  eax = tmp64;");
4287         last_arith_dst = NULL;
4288         delayed_flag_op = NULL;
4289         break;
4290
4291       case OP_DIV:
4292       case OP_IDIV:
4293         assert_operand_cnt(1);
4294         if (po->operand[0].lmod != OPLM_DWORD)
4295           ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
4296
4297         out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4298         strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
4299           po->op == OP_IDIV));
4300         switch (po->operand[0].lmod) {
4301         case OPLM_DWORD:
4302           if (po->flags & OPF_32BIT)
4303             snprintf(buf3, sizeof(buf3), "%seax", buf2);
4304           else {
4305             fprintf(fout, "  tmp64 = ((u64)edx << 32) | eax;\n");
4306             snprintf(buf3, sizeof(buf3), "%stmp64",
4307               (po->op == OP_IDIV) ? "(s64)" : "");
4308           }
4309           if (po->operand[0].type == OPT_REG
4310             && po->operand[0].reg == xDX)
4311           {
4312             fprintf(fout, "  eax = %s / %s%s;", buf3, buf2, buf1);
4313             fprintf(fout, "  edx = %s %% %s%s;\n", buf3, buf2, buf1);
4314           }
4315           else {
4316             fprintf(fout, "  edx = %s %% %s%s;\n", buf3, buf2, buf1);
4317             fprintf(fout, "  eax = %s / %s%s;", buf3, buf2, buf1);
4318           }
4319           break;
4320         default:
4321           ferr(po, "unhandled division type\n");
4322         }
4323         last_arith_dst = NULL;
4324         delayed_flag_op = NULL;
4325         break;
4326
4327       case OP_TEST:
4328       case OP_CMP:
4329         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4330         if (pfomask != 0) {
4331           for (j = 0; j < 8; j++) {
4332             if (pfomask & (1 << j)) {
4333               out_cmp_test(buf1, sizeof(buf1), po, j, 0);
4334               fprintf(fout, "  cond_%s = %s;",
4335                 parsed_flag_op_names[j], buf1);
4336             }
4337           }
4338           pfomask = 0;
4339         }
4340         else
4341           no_output = 1;
4342         last_arith_dst = NULL;
4343         delayed_flag_op = po;
4344         break;
4345
4346       case OP_SCC:
4347         // SETcc - should already be handled
4348         break;
4349
4350       // note: we reuse OP_Jcc for SETcc, only flags differ
4351       case OP_JCC:
4352         fprintf(fout, "\n    goto %s;", po->operand[0].name);
4353         break;
4354
4355       case OP_JECXZ:
4356         fprintf(fout, "  if (ecx == 0)\n");
4357         fprintf(fout, "    goto %s;", po->operand[0].name);
4358         strcat(g_comment, "jecxz");
4359         break;
4360
4361       case OP_JMP:
4362         assert_operand_cnt(1);
4363         last_arith_dst = NULL;
4364         delayed_flag_op = NULL;
4365
4366         if (po->operand[0].type == OPT_REGMEM) {
4367           ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
4368                   buf1, buf2);
4369           if (ret != 2)
4370             ferr(po, "parse failure for jmp '%s'\n",
4371               po->operand[0].name);
4372           fprintf(fout, "  goto *jt_%s[%s];", buf1, buf2);
4373           break;
4374         }
4375         else if (po->operand[0].type != OPT_LABEL)
4376           ferr(po, "unhandled jmp type\n");
4377
4378         fprintf(fout, "  goto %s;", po->operand[0].name);
4379         break;
4380
4381       case OP_CALL:
4382         assert_operand_cnt(1);
4383         pp = po->pp;
4384         my_assert_not(pp, NULL);
4385
4386         strcpy(buf3, "  ");
4387         if (po->flags & OPF_CC) {
4388           // we treat conditional branch to another func
4389           // (yes such code exists..) as conditional tailcall
4390           strcat(buf3, "  ");
4391           fprintf(fout, " {\n");
4392         }
4393
4394         if (pp->is_fptr && !pp->is_arg) {
4395           fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
4396             out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
4397               "(void *)", 0));
4398           if (pp->is_unresolved)
4399             fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
4400               buf3, asmfn, po->asmln, pp->name);
4401         }
4402
4403         fprintf(fout, "%s", buf3);
4404         if (strstr(pp->ret_type.name, "int64")) {
4405           if (po->flags & OPF_TAIL)
4406             ferr(po, "int64 and tail?\n");
4407           fprintf(fout, "tmp64 = ");
4408         }
4409         else if (!IS(pp->ret_type.name, "void")) {
4410           if (po->flags & OPF_TAIL) {
4411             if (!IS(g_func_pp->ret_type.name, "void")) {
4412               fprintf(fout, "return ");
4413               if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
4414                 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
4415             }
4416           }
4417           else if (regmask & (1 << xAX)) {
4418             fprintf(fout, "eax = ");
4419             if (pp->ret_type.is_ptr)
4420               fprintf(fout, "(u32)");
4421           }
4422         }
4423
4424         if (pp->name[0] == 0)
4425           ferr(po, "missing pp->name\n");
4426         fprintf(fout, "%s%s(", pp->name,
4427           pp->has_structarg ? "_sa" : "");
4428
4429         if (po->flags & OPF_ATAIL) {
4430           if (pp->argc_stack != g_func_pp->argc_stack
4431             || (pp->argc_stack > 0
4432                 && pp->is_stdcall != g_func_pp->is_stdcall))
4433             ferr(po, "incompatible tailcall\n");
4434           if (g_func_pp->has_retreg)
4435             ferr(po, "TODO: retreg+tailcall\n");
4436
4437           for (arg = j = 0; arg < pp->argc; arg++) {
4438             if (arg > 0)
4439               fprintf(fout, ", ");
4440
4441             cast[0] = 0;
4442             if (pp->arg[arg].type.is_ptr)
4443               snprintf(cast, sizeof(cast), "(%s)",
4444                 pp->arg[arg].type.name);
4445
4446             if (pp->arg[arg].reg != NULL) {
4447               fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4448               continue;
4449             }
4450             // stack arg
4451             for (; j < g_func_pp->argc; j++)
4452               if (g_func_pp->arg[j].reg == NULL)
4453                 break;
4454             fprintf(fout, "%sa%d", cast, j + 1);
4455             j++;
4456           }
4457         }
4458         else {
4459           for (arg = 0; arg < pp->argc; arg++) {
4460             if (arg > 0)
4461               fprintf(fout, ", ");
4462
4463             cast[0] = 0;
4464             if (pp->arg[arg].type.is_ptr)
4465               snprintf(cast, sizeof(cast), "(%s)",
4466                 pp->arg[arg].type.name);
4467
4468             if (pp->arg[arg].reg != NULL) {
4469               if (pp->arg[arg].type.is_retreg)
4470                 fprintf(fout, "&%s", pp->arg[arg].reg);
4471               else
4472                 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4473               continue;
4474             }
4475
4476             // stack arg
4477             tmp_op = pp->arg[arg].datap;
4478             if (tmp_op == NULL)
4479               ferr(po, "parsed_op missing for arg%d\n", arg);
4480             if (tmp_op->argnum != 0) {
4481               fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
4482             }
4483             else {
4484               fprintf(fout, "%s",
4485                 out_src_opr(buf1, sizeof(buf1),
4486                   tmp_op, &tmp_op->operand[0], cast, 0));
4487             }
4488           }
4489         }
4490         fprintf(fout, ");");
4491
4492         if (strstr(pp->ret_type.name, "int64")) {
4493           fprintf(fout, "\n");
4494           fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
4495           fprintf(fout, "%seax = tmp64;", buf3);
4496         }
4497
4498         if (pp->is_unresolved) {
4499           snprintf(buf2, sizeof(buf2), " unresolved %dreg",
4500             pp->argc_reg);
4501           strcat(g_comment, buf2);
4502         }
4503
4504         if (po->flags & OPF_TAIL) {
4505           ret = 0;
4506           if (i == opcnt - 1 || pp->is_noreturn)
4507             ret = 0;
4508           else if (IS(pp->ret_type.name, "void"))
4509             ret = 1;
4510           else if (IS(g_func_pp->ret_type.name, "void"))
4511             ret = 1;
4512           // else already handled as 'return f()'
4513
4514           if (ret) {
4515             if (!IS(g_func_pp->ret_type.name, "void")) {
4516               ferr(po, "int func -> void func tailcall?\n");
4517             }
4518             else {
4519               fprintf(fout, "\n%sreturn;", buf3);
4520               strcat(g_comment, " ^ tailcall");
4521             }
4522           }
4523           else
4524             strcat(g_comment, " tailcall");
4525         }
4526         if (pp->is_noreturn)
4527           strcat(g_comment, " noreturn");
4528         if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
4529           strcat(g_comment, " argframe");
4530         if (po->flags & OPF_CC)
4531           strcat(g_comment, " cond");
4532
4533         if (po->flags & OPF_CC)
4534           fprintf(fout, "\n  }");
4535
4536         delayed_flag_op = NULL;
4537         last_arith_dst = NULL;
4538         break;
4539
4540       case OP_RET:
4541         if (g_func_pp->is_vararg)
4542           fprintf(fout, "  va_end(ap);\n");
4543         if (g_func_pp->has_retreg) {
4544           for (arg = 0; arg < g_func_pp->argc; arg++)
4545             if (g_func_pp->arg[arg].type.is_retreg)
4546               fprintf(fout, "  *r_%s = %s;\n",
4547                 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
4548         }
4549  
4550         if (IS(g_func_pp->ret_type.name, "void")) {
4551           if (i != opcnt - 1 || label_pending)
4552             fprintf(fout, "  return;");
4553         }
4554         else if (g_func_pp->ret_type.is_ptr) {
4555           fprintf(fout, "  return (%s)eax;",
4556             g_func_pp->ret_type.name);
4557         }
4558         else if (IS(g_func_pp->ret_type.name, "__int64"))
4559           fprintf(fout, "  return ((u64)edx << 32) | eax;");
4560         else
4561           fprintf(fout, "  return eax;");
4562
4563         last_arith_dst = NULL;
4564         delayed_flag_op = NULL;
4565         break;
4566
4567       case OP_PUSH:
4568         out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4569         if (po->argnum != 0) {
4570           // special case - saved func arg
4571           fprintf(fout, "  s_a%d = %s;", po->argnum, buf1);
4572           break;
4573         }
4574         else if (po->flags & OPF_RSAVE) {
4575           fprintf(fout, "  s_%s = %s;", buf1, buf1);
4576           break;
4577         }
4578         else if (g_func_pp->is_userstack) {
4579           fprintf(fout, "  *(--esp) = %s;", buf1);
4580           break;
4581         }
4582         if (!(g_ida_func_attr & IDAFA_NORETURN))
4583           ferr(po, "stray push encountered\n");
4584         no_output = 1;
4585         break;
4586
4587       case OP_POP:
4588         if (po->flags & OPF_RSAVE) {
4589           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4590           fprintf(fout, "  %s = s_%s;", buf1, buf1);
4591           break;
4592         }
4593         else if (po->datap != NULL) {
4594           // push/pop pair
4595           tmp_op = po->datap;
4596           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4597           fprintf(fout, "  %s = %s;", buf1,
4598             out_src_opr(buf2, sizeof(buf2),
4599               tmp_op, &tmp_op->operand[0],
4600               default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4601           break;
4602         }
4603         else if (g_func_pp->is_userstack) {
4604           fprintf(fout, "  %s = *esp++;",
4605             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4606           break;
4607         }
4608         else
4609           ferr(po, "stray pop encountered\n");
4610         break;
4611
4612       case OP_NOP:
4613         no_output = 1;
4614         break;
4615
4616       default:
4617         no_output = 1;
4618         ferr(po, "unhandled op type %d, flags %x\n",
4619           po->op, po->flags);
4620         break;
4621     }
4622
4623     if (g_comment[0] != 0) {
4624       char *p = g_comment;
4625       while (my_isblank(*p))
4626         p++;
4627       fprintf(fout, "  // %s", p);
4628       g_comment[0] = 0;
4629       no_output = 0;
4630     }
4631     if (!no_output)
4632       fprintf(fout, "\n");
4633
4634     // some sanity checking
4635     if (po->flags & OPF_REP) {
4636       if (po->op != OP_STOS && po->op != OP_MOVS
4637           && po->op != OP_CMPS && po->op != OP_SCAS)
4638         ferr(po, "unexpected rep\n");
4639       if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
4640           && (po->op == OP_CMPS || po->op == OP_SCAS))
4641         ferr(po, "cmps/scas with plain rep\n");
4642     }
4643     if ((po->flags & (OPF_REPZ|OPF_REPNZ))
4644         && po->op != OP_CMPS && po->op != OP_SCAS)
4645       ferr(po, "unexpected repz/repnz\n");
4646
4647     if (pfomask != 0)
4648       ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
4649
4650     // see is delayed flag stuff is still valid
4651     if (delayed_flag_op != NULL && delayed_flag_op != po) {
4652       if (is_any_opr_modified(delayed_flag_op, po, 0))
4653         delayed_flag_op = NULL;
4654     }
4655
4656     if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
4657       if (is_opr_modified(last_arith_dst, po))
4658         last_arith_dst = NULL;
4659     }
4660
4661     label_pending = 0;
4662   }
4663
4664   if (g_stack_fsz && !g_stack_frame_used)
4665     fprintf(fout, "  (void)sf;\n");
4666
4667   fprintf(fout, "}\n\n");
4668
4669   // cleanup
4670   for (i = 0; i < opcnt; i++) {
4671     struct label_ref *lr, *lr_del;
4672
4673     lr = g_label_refs[i].next;
4674     while (lr != NULL) {
4675       lr_del = lr;
4676       lr = lr->next;
4677       free(lr_del);
4678     }
4679     g_label_refs[i].i = -1;
4680     g_label_refs[i].next = NULL;
4681
4682     if (ops[i].op == OP_CALL) {
4683       if (ops[i].pp)
4684         proto_release(ops[i].pp);
4685     }
4686   }
4687   g_func_pp = NULL;
4688 }
4689
4690 static void set_label(int i, const char *name)
4691 {
4692   const char *p;
4693   int len;
4694
4695   len = strlen(name);
4696   p = strchr(name, ':');
4697   if (p != NULL)
4698     len = p - name;
4699
4700   if (len > sizeof(g_labels[0]) - 1)
4701     aerr("label '%s' too long: %d\n", name, len);
4702   if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
4703     aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
4704   memcpy(g_labels[i], name, len);
4705   g_labels[i][len] = 0;
4706 }
4707
4708 // '=' needs special treatment..
4709 static char *next_word_s(char *w, size_t wsize, char *s)
4710 {
4711         size_t i;
4712
4713         s = sskip(s);
4714
4715         for (i = 0; i < wsize - 1; i++) {
4716                 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
4717                         break;
4718                 w[i] = s[i];
4719         }
4720         w[i] = 0;
4721
4722         if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
4723                 printf("warning: '%s' truncated\n", w);
4724
4725         return s + i;
4726 }
4727
4728 struct chunk_item {
4729   char *name;
4730   long fptr;
4731   int asmln;
4732 };
4733
4734 static struct chunk_item *func_chunks;
4735 static int func_chunk_cnt;
4736 static int func_chunk_alloc;
4737
4738 static void add_func_chunk(FILE *fasm, const char *name, int line)
4739 {
4740   if (func_chunk_cnt >= func_chunk_alloc) {
4741     func_chunk_alloc *= 2;
4742     func_chunks = realloc(func_chunks,
4743       func_chunk_alloc * sizeof(func_chunks[0]));
4744     my_assert_not(func_chunks, NULL);
4745   }
4746   func_chunks[func_chunk_cnt].fptr = ftell(fasm);
4747   func_chunks[func_chunk_cnt].name = strdup(name);
4748   func_chunks[func_chunk_cnt].asmln = line;
4749   func_chunk_cnt++;
4750 }
4751
4752 static int cmp_chunks(const void *p1, const void *p2)
4753 {
4754   const struct chunk_item *c1 = p1, *c2 = p2;
4755   return strcmp(c1->name, c2->name);
4756 }
4757
4758 static int cmpstringp(const void *p1, const void *p2)
4759 {
4760   return strcmp(*(char * const *)p1, *(char * const *)p2);
4761 }
4762
4763 static void scan_ahead(FILE *fasm)
4764 {
4765   char words[2][256];
4766   char line[256];
4767   long oldpos;
4768   int oldasmln;
4769   int wordc;
4770   char *p;
4771   int i;
4772
4773   oldpos = ftell(fasm);
4774   oldasmln = asmln;
4775
4776   while (fgets(line, sizeof(line), fasm))
4777   {
4778     wordc = 0;
4779     asmln++;
4780
4781     p = sskip(line);
4782     if (*p == 0)
4783       continue;
4784
4785     if (*p == ';')
4786     {
4787       // get rid of random tabs
4788       for (i = 0; line[i] != 0; i++)
4789         if (line[i] == '\t')
4790           line[i] = ' ';
4791
4792       if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4793       {
4794         p += 30;
4795         next_word(words[0], sizeof(words[0]), p);
4796         if (words[0][0] == 0)
4797           aerr("missing name for func chunk?\n");
4798
4799         add_func_chunk(fasm, words[0], asmln);
4800       }
4801       else if (IS_START(p, "; sctend"))
4802         break;
4803
4804       continue;
4805     } // *p == ';'
4806
4807     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4808       words[wordc][0] = 0;
4809       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4810       if (*p == 0 || *p == ';') {
4811         wordc++;
4812         break;
4813       }
4814     }
4815
4816     if (wordc == 2 && IS(words[1], "ends"))
4817       break;
4818   }
4819
4820   fseek(fasm, oldpos, SEEK_SET);
4821   asmln = oldasmln;
4822 }
4823
4824 int main(int argc, char *argv[])
4825 {
4826   FILE *fout, *fasm, *frlist;
4827   struct parsed_data *pd = NULL;
4828   int pd_alloc = 0;
4829   char **rlist = NULL;
4830   int rlist_len = 0;
4831   int rlist_alloc = 0;
4832   int func_chunks_used = 0;
4833   int func_chunks_sorted = 0;
4834   int func_chunk_i = -1;
4835   long func_chunk_ret = 0;
4836   int func_chunk_ret_ln = 0;
4837   int scanned_ahead = 0;
4838   char line[256];
4839   char words[20][256];
4840   enum opr_lenmod lmod;
4841   char *sctproto = NULL;
4842   int in_func = 0;
4843   int pending_endp = 0;
4844   int skip_func = 0;
4845   int skip_warned = 0;
4846   int eq_alloc;
4847   int verbose = 0;
4848   int multi_seg = 0;
4849   int end = 0;
4850   int arg_out;
4851   int arg;
4852   int pi = 0;
4853   int i, j;
4854   int ret, len;
4855   char *p;
4856   int wordc;
4857
4858   for (arg = 1; arg < argc; arg++) {
4859     if (IS(argv[arg], "-v"))
4860       verbose = 1;
4861     else if (IS(argv[arg], "-rf"))
4862       g_allow_regfunc = 1;
4863     else if (IS(argv[arg], "-m"))
4864       multi_seg = 1;
4865     else
4866       break;
4867   }
4868
4869   if (argc < arg + 3) {
4870     printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdrf> [rlist]*\n",
4871       argv[0]);
4872     return 1;
4873   }
4874
4875   arg_out = arg++;
4876
4877   asmfn = argv[arg++];
4878   fasm = fopen(asmfn, "r");
4879   my_assert_not(fasm, NULL);
4880
4881   hdrfn = argv[arg++];
4882   g_fhdr = fopen(hdrfn, "r");
4883   my_assert_not(g_fhdr, NULL);
4884
4885   rlist_alloc = 64;
4886   rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4887   my_assert_not(rlist, NULL);
4888   // needs special handling..
4889   rlist[rlist_len++] = "__alloca_probe";
4890
4891   func_chunk_alloc = 32;
4892   func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4893   my_assert_not(func_chunks, NULL);
4894
4895   memset(words, 0, sizeof(words));
4896
4897   for (; arg < argc; arg++) {
4898     frlist = fopen(argv[arg], "r");
4899     my_assert_not(frlist, NULL);
4900
4901     while (fgets(line, sizeof(line), frlist)) {
4902       p = sskip(line);
4903       if (*p == 0 || *p == ';')
4904         continue;
4905       if (*p == '#') {
4906         if (IS_START(p, "#if 0")
4907          || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
4908         {
4909           skip_func = 1;
4910         }
4911         else if (IS_START(p, "#endif"))
4912           skip_func = 0;
4913         continue;
4914       }
4915       if (skip_func)
4916         continue;
4917
4918       p = next_word(words[0], sizeof(words[0]), p);
4919       if (words[0][0] == 0)
4920         continue;
4921
4922       if (rlist_len >= rlist_alloc) {
4923         rlist_alloc = rlist_alloc * 2 + 64;
4924         rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4925         my_assert_not(rlist, NULL);
4926       }
4927       rlist[rlist_len++] = strdup(words[0]);
4928     }
4929     skip_func = 0;
4930
4931     fclose(frlist);
4932     frlist = NULL;
4933   }
4934
4935   if (rlist_len > 0)
4936     qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4937
4938   fout = fopen(argv[arg_out], "w");
4939   my_assert_not(fout, NULL);
4940
4941   eq_alloc = 128;
4942   g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4943   my_assert_not(g_eqs, NULL);
4944
4945   for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4946     g_label_refs[i].i = -1;
4947     g_label_refs[i].next = NULL;
4948   }
4949
4950   while (fgets(line, sizeof(line), fasm))
4951   {
4952     wordc = 0;
4953     asmln++;
4954
4955     p = sskip(line);
4956     if (*p == 0)
4957       continue;
4958
4959     // get rid of random tabs
4960     for (i = 0; line[i] != 0; i++)
4961       if (line[i] == '\t')
4962         line[i] = ' ';
4963
4964     if (*p == ';')
4965     {
4966       if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4967         goto do_pending_endp; // eww..
4968
4969       if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4970       {
4971         static const char *attrs[] = {
4972           "bp-based frame",
4973           "library function",
4974           "static",
4975           "noreturn",
4976           "thunk",
4977           "fpd=",
4978         };
4979
4980         // parse IDA's attribute-list comment
4981         g_ida_func_attr = 0;
4982         p = sskip(p + 13);
4983
4984         for (; *p != 0; p = sskip(p)) {
4985           for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4986             if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4987               g_ida_func_attr |= 1 << i;
4988               p += strlen(attrs[i]);
4989               break;
4990             }
4991           }
4992           if (i == ARRAY_SIZE(attrs)) {
4993             anote("unparsed IDA attr: %s\n", p);
4994             break;
4995           }
4996           if (IS(attrs[i], "fpd=")) {
4997             p = next_word(words[0], sizeof(words[0]), p);
4998             // ignore for now..
4999           }
5000         }
5001       }
5002       else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
5003       {
5004         p += 30;
5005         next_word(words[0], sizeof(words[0]), p);
5006         if (words[0][0] == 0)
5007           aerr("missing name for func chunk?\n");
5008
5009         if (!scanned_ahead) {
5010           add_func_chunk(fasm, words[0], asmln);
5011           func_chunks_sorted = 0;
5012         }
5013       }
5014       else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
5015       {
5016         if (func_chunk_i >= 0) {
5017           if (func_chunk_i < func_chunk_cnt
5018             && IS(func_chunks[func_chunk_i].name, g_func))
5019           {
5020             // move on to next chunk
5021             ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
5022             if (ret)
5023               aerr("seek failed for '%s' chunk #%d\n",
5024                 g_func, func_chunk_i);
5025             asmln = func_chunks[func_chunk_i].asmln;
5026             func_chunk_i++;
5027           }
5028           else {
5029             if (func_chunk_ret == 0)
5030               aerr("no return from chunk?\n");
5031             fseek(fasm, func_chunk_ret, SEEK_SET);
5032             asmln = func_chunk_ret_ln;
5033             func_chunk_ret = 0;
5034             pending_endp = 1;
5035           }
5036         }
5037       }
5038       else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
5039         func_chunks_used = 1;
5040         p += 20;
5041         if (IS_START(g_func, "sub_")) {
5042           unsigned long addr = strtoul(p, NULL, 16);
5043           unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
5044           if (addr > f_addr && !scanned_ahead) {
5045             anote("scan_ahead caused by '%s', addr %lx\n",
5046               g_func, addr);
5047             scan_ahead(fasm);
5048             scanned_ahead = 1;
5049             func_chunks_sorted = 0;
5050           }
5051         }
5052       }
5053       continue;
5054     } // *p == ';'
5055
5056 parse_words:
5057     for (i = wordc; i < ARRAY_SIZE(words); i++)
5058       words[i][0] = 0;
5059     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
5060       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
5061       if (*p == 0 || *p == ';') {
5062         wordc++;
5063         break;
5064       }
5065     }
5066     if (*p != 0 && *p != ';')
5067       aerr("too many words\n");
5068
5069     // alow asm patches in comments
5070     if (*p == ';') {
5071       if (IS_START(p, "; sctpatch:")) {
5072         p = sskip(p + 11);
5073         if (*p == 0 || *p == ';')
5074           continue;
5075         goto parse_words; // lame
5076       }
5077       if (IS_START(p, "; sctproto:")) {
5078         sctproto = strdup(p + 11);
5079       }
5080       else if (IS_START(p, "; sctend")) {
5081         end = 1;
5082         if (!pending_endp)
5083           break;
5084       }
5085     }
5086
5087     if (wordc == 0) {
5088       // shouldn't happen
5089       awarn("wordc == 0?\n");
5090       continue;
5091     }
5092
5093     // don't care about this:
5094     if (words[0][0] == '.'
5095         || IS(words[0], "include")
5096         || IS(words[0], "assume") || IS(words[1], "segment")
5097         || IS(words[0], "align"))
5098     {
5099       continue;
5100     }
5101
5102 do_pending_endp:
5103     // do delayed endp processing to collect switch jumptables
5104     if (pending_endp) {
5105       if (in_func && !skip_func && !end && wordc >= 2
5106           && ((words[0][0] == 'd' && words[0][2] == 0)
5107               || (words[1][0] == 'd' && words[1][2] == 0)))
5108       {
5109         i = 1;
5110         if (words[1][0] == 'd' && words[1][2] == 0) {
5111           // label
5112           if (g_func_pd_cnt >= pd_alloc) {
5113             pd_alloc = pd_alloc * 2 + 16;
5114             g_func_pd = realloc(g_func_pd,
5115               sizeof(g_func_pd[0]) * pd_alloc);
5116             my_assert_not(g_func_pd, NULL);
5117           }
5118           pd = &g_func_pd[g_func_pd_cnt];
5119           g_func_pd_cnt++;
5120           memset(pd, 0, sizeof(*pd));
5121           strcpy(pd->label, words[0]);
5122           pd->type = OPT_CONST;
5123           pd->lmod = lmod_from_directive(words[1]);
5124           i = 2;
5125         }
5126         else {
5127           if (pd == NULL) {
5128             if (verbose)
5129               anote("skipping alignment byte?\n");
5130             continue;
5131           }
5132           lmod = lmod_from_directive(words[0]);
5133           if (lmod != pd->lmod)
5134             aerr("lmod change? %d->%d\n", pd->lmod, lmod);
5135         }
5136
5137         if (pd->count_alloc < pd->count + wordc) {
5138           pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
5139           pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
5140           my_assert_not(pd->d, NULL);
5141         }
5142         for (; i < wordc; i++) {
5143           if (IS(words[i], "offset")) {
5144             pd->type = OPT_OFFSET;
5145             i++;
5146           }
5147           p = strchr(words[i], ',');
5148           if (p != NULL)
5149             *p = 0;
5150           if (pd->type == OPT_OFFSET)
5151             pd->d[pd->count].u.label = strdup(words[i]);
5152           else
5153             pd->d[pd->count].u.val = parse_number(words[i]);
5154           pd->d[pd->count].bt_i = -1;
5155           pd->count++;
5156         }
5157         continue;
5158       }
5159
5160       if (in_func && !skip_func)
5161         gen_func(fout, g_fhdr, g_func, pi);
5162
5163       pending_endp = 0;
5164       in_func = 0;
5165       g_ida_func_attr = 0;
5166       skip_warned = 0;
5167       skip_func = 0;
5168       g_func[0] = 0;
5169       func_chunks_used = 0;
5170       func_chunk_i = -1;
5171       if (pi != 0) {
5172         memset(&ops, 0, pi * sizeof(ops[0]));
5173         memset(g_labels, 0, pi * sizeof(g_labels[0]));
5174         pi = 0;
5175       }
5176       g_eqcnt = 0;
5177       for (i = 0; i < g_func_pd_cnt; i++) {
5178         pd = &g_func_pd[i];
5179         if (pd->type == OPT_OFFSET) {
5180           for (j = 0; j < pd->count; j++)
5181             free(pd->d[j].u.label);
5182         }
5183         free(pd->d);
5184         pd->d = NULL;
5185       }
5186       g_func_pd_cnt = 0;
5187       pd = NULL;
5188
5189       if (end)
5190         break;
5191       if (wordc == 0)
5192         continue;
5193     }
5194
5195     if (IS(words[1], "proc")) {
5196       if (in_func)
5197         aerr("proc '%s' while in_func '%s'?\n",
5198           words[0], g_func);
5199       p = words[0];
5200       if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
5201         skip_func = 1;
5202       strcpy(g_func, words[0]);
5203       set_label(0, words[0]);
5204       in_func = 1;
5205       continue;
5206     }
5207
5208     if (IS(words[1], "endp"))
5209     {
5210       if (!in_func)
5211         aerr("endp '%s' while not in_func?\n", words[0]);
5212       if (!IS(g_func, words[0]))
5213         aerr("endp '%s' while in_func '%s'?\n",
5214           words[0], g_func);
5215
5216       if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
5217         && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
5218       {
5219         // import jump
5220         skip_func = 1;
5221       }
5222
5223       if (!skip_func && func_chunks_used) {
5224         // start processing chunks
5225         struct chunk_item *ci, key = { g_func, 0 };
5226
5227         func_chunk_ret = ftell(fasm);
5228         func_chunk_ret_ln = asmln;
5229         if (!func_chunks_sorted) {
5230           qsort(func_chunks, func_chunk_cnt,
5231             sizeof(func_chunks[0]), cmp_chunks);
5232           func_chunks_sorted = 1;
5233         }
5234         ci = bsearch(&key, func_chunks, func_chunk_cnt,
5235                sizeof(func_chunks[0]), cmp_chunks);
5236         if (ci == NULL)
5237           aerr("'%s' needs chunks, but none found\n", g_func);
5238         func_chunk_i = ci - func_chunks;
5239         for (; func_chunk_i > 0; func_chunk_i--)
5240           if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
5241             break;
5242
5243         ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
5244         if (ret)
5245           aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
5246         asmln = func_chunks[func_chunk_i].asmln;
5247         func_chunk_i++;
5248         continue;
5249       }
5250       pending_endp = 1;
5251       continue;
5252     }
5253
5254     if (wordc == 2 && IS(words[1], "ends")) {
5255       if (!multi_seg) {
5256         end = 1;
5257         if (pending_endp)
5258           goto do_pending_endp;
5259         break;
5260       }
5261
5262       // scan for next text segment
5263       while (fgets(line, sizeof(line), fasm)) {
5264         asmln++;
5265         p = sskip(line);
5266         if (*p == 0 || *p == ';')
5267           continue;
5268
5269         if (strstr(p, "segment para public 'CODE' use32"))
5270           break;
5271       }
5272
5273       continue;
5274     }
5275
5276     p = strchr(words[0], ':');
5277     if (p != NULL) {
5278       set_label(pi, words[0]);
5279       continue;
5280     }
5281
5282     if (!in_func || skip_func) {
5283       if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
5284         if (verbose)
5285           anote("skipping from '%s'\n", g_labels[pi]);
5286         skip_warned = 1;
5287       }
5288       g_labels[pi][0] = 0;
5289       continue;
5290     }
5291
5292     if (wordc > 1 && IS(words[1], "="))
5293     {
5294       if (wordc != 5)
5295         aerr("unhandled equ, wc=%d\n", wordc);
5296       if (g_eqcnt >= eq_alloc) {
5297         eq_alloc *= 2;
5298         g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
5299         my_assert_not(g_eqs, NULL);
5300       }
5301
5302       len = strlen(words[0]);
5303       if (len > sizeof(g_eqs[0].name) - 1)
5304         aerr("equ name too long: %d\n", len);
5305       strcpy(g_eqs[g_eqcnt].name, words[0]);
5306
5307       if (!IS(words[3], "ptr"))
5308         aerr("unhandled equ\n");
5309       if (IS(words[2], "dword"))
5310         g_eqs[g_eqcnt].lmod = OPLM_DWORD;
5311       else if (IS(words[2], "word"))
5312         g_eqs[g_eqcnt].lmod = OPLM_WORD;
5313       else if (IS(words[2], "byte"))
5314         g_eqs[g_eqcnt].lmod = OPLM_BYTE;
5315       else
5316         aerr("bad lmod: '%s'\n", words[2]);
5317
5318       g_eqs[g_eqcnt].offset = parse_number(words[4]);
5319       g_eqcnt++;
5320       continue;
5321     }
5322
5323     if (pi >= ARRAY_SIZE(ops))
5324       aerr("too many ops\n");
5325
5326     parse_op(&ops[pi], words, wordc);
5327
5328     if (sctproto != NULL) {
5329       if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
5330         ops[pi].datap = sctproto;
5331       sctproto = NULL;
5332     }
5333     pi++;
5334   }
5335
5336   fclose(fout);
5337   fclose(fasm);
5338   fclose(g_fhdr);
5339
5340   return 0;
5341 }
5342
5343 // vim:ts=2:shiftwidth=2:expandtab