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