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