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