fixes, something compiles
[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 here, 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", "DWORD",
448     "WPARAM", "LPARAM", "UINT",
449     "HIMC",
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; 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         return ret;
1944       }
1945
1946       if (po->bt_i < 0) {
1947         ferr(po, "dead branch\n");
1948         return -1;
1949       }
1950
1951       if (po->flags & OPF_CC) {
1952         ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1953                  depth, maxdepth, do_flags);
1954         if (ret < 0)
1955           return ret; // dead end
1956       }
1957       else {
1958         i = po->bt_i - 1;
1959       }
1960       continue;
1961     }
1962
1963     if ((po->op == OP_POP || po->op == OP_PUSH)
1964         && po->operand[0].type == OPT_REG
1965         && IS(po->operand[0].name, reg))
1966     {
1967       if (po->op == OP_PUSH && !(po->flags & OPF_FARG)) {
1968         depth++;
1969         if (depth > *maxdepth)
1970           *maxdepth = depth;
1971         if (do_flags)
1972           op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1973       }
1974       else if (po->op == OP_POP) {
1975         if (depth == 0) {
1976           if (do_flags)
1977             op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
1978           return 1;
1979         }
1980         else {
1981           depth--;
1982           if (depth < 0) // should not happen
1983             ferr(po, "fail with depth\n");
1984           if (do_flags)
1985             op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1986         }
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   }
2185
2186   return -1;
2187 }
2188
2189 static int scan_for_reg_clear(int i, int reg)
2190 {
2191   while (i >= 0) {
2192     if (g_labels[i][0] != 0) {
2193       if (g_label_refs[i].next != NULL)
2194         return -1;
2195       if (i > 0 && LAST_OP(i - 1)) {
2196         i = g_label_refs[i].i;
2197         continue;
2198       }
2199       return -1;
2200     }
2201     i--;
2202
2203     if (ops[i].op == OP_XOR
2204      && ops[i].operand[0].lmod == OPLM_DWORD
2205      && ops[i].operand[0].reg == ops[i].operand[1].reg
2206      && ops[i].operand[0].reg == reg)
2207       return i;
2208
2209     if (ops[i].regmask_dst & (1 << reg))
2210       return -1;
2211   }
2212
2213   return -1;
2214 }
2215
2216 // scan for positive, constant esp adjust
2217 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2218 {
2219   const struct parsed_proto *pp;
2220   struct parsed_op *po;
2221   int first_pop = -1;
2222   *adj = 0;
2223
2224   for (; i < opcnt; i++) {
2225     po = &ops[i];
2226
2227     if (g_labels[i][0] != 0)
2228       break;
2229
2230     if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2231       if (po->operand[1].type != OPT_CONST)
2232         ferr(&ops[i], "non-const esp adjust?\n");
2233       *adj += po->operand[1].val;
2234       if (*adj & 3)
2235         ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2236       return i;
2237     }
2238     else if (po->op == OP_PUSH) {
2239       if (first_pop == -1)
2240         first_pop = -2; // none
2241       *adj -= lmod_bytes(po, po->operand[0].lmod);
2242     }
2243     else if (po->op == OP_POP) {
2244       if (first_pop == -1)
2245         first_pop = i;
2246       *adj += lmod_bytes(po, po->operand[0].lmod);
2247     }
2248     else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2249       if (po->op != OP_CALL)
2250         break;
2251       if (po->operand[0].type != OPT_LABEL)
2252         break;
2253       pp = po->datap;
2254       if (pp != NULL && pp->is_stdcall)
2255         break;
2256     }
2257   }
2258
2259   if (*adj == 4 && first_pop >= 0 && ops[first_pop].op == OP_POP
2260     && ops[first_pop].operand[0].type == OPT_REG
2261     && ops[first_pop].operand[0].reg == xCX)
2262   {
2263     // probably 'pop ecx' was used..
2264     return first_pop;
2265   }
2266
2267   return -1;
2268 }
2269
2270 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2271 {
2272   struct parsed_op *po;
2273   int j;
2274
2275   if (i < 0)
2276     ferr(ops, "%s: followed bad branch?\n", __func__);
2277
2278   for (; i < opcnt; i++) {
2279     po = &ops[i];
2280     if (po->cc_scratch == magic)
2281       return;
2282     po->cc_scratch = magic;
2283     po->flags |= flags;
2284
2285     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2286       if (po->btj != NULL) {
2287         // jumptable
2288         for (j = 0; j < po->btj->count; j++)
2289           scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2290         return;
2291       }
2292
2293       scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2294       if (!(po->flags & OPF_CC))
2295         return;
2296     }
2297     if (po->flags & OPF_TAIL)
2298       return;
2299   }
2300 }
2301
2302 static const struct parsed_proto *try_recover_pp(
2303   struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2304 {
2305   const struct parsed_proto *pp = NULL;
2306   char buf[256];
2307   char *p;
2308
2309   // maybe an arg of g_func?
2310   if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2311   {
2312     char ofs_reg[16] = { 0, };
2313     int arg, arg_s, arg_i;
2314     int stack_ra = 0;
2315     int offset = 0;
2316
2317     parse_stack_access(po, opr->name, ofs_reg,
2318       &offset, &stack_ra, NULL);
2319     if (ofs_reg[0] != 0)
2320       ferr(po, "offset reg on arg access?\n");
2321     if (offset <= stack_ra) {
2322       // search who set the stack var instead
2323       if (search_instead != NULL)
2324         *search_instead = 1;
2325       return NULL;
2326     }
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, const 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, NULL);
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   int search_advice = 0;
2442
2443   *multi_src = 0;
2444
2445   switch (ops[i].operand[0].type) {
2446   case OPT_REGMEM:
2447   case OPT_LABEL:
2448   case OPT_OFFSET:
2449     pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
2450     if (!search_advice)
2451       break;
2452     // fallthrough
2453   default:
2454     scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
2455       multi_src);
2456     break;
2457   }
2458
2459   return pp;
2460 }
2461
2462 static int collect_call_args_r(struct parsed_op *po, int i,
2463   struct parsed_proto *pp, int *regmask, int *save_arg_vars, int arg,
2464   int magic, int need_op_saving, int may_reuse)
2465 {
2466   struct parsed_proto *pp_tmp;
2467   struct label_ref *lr;
2468   int need_to_save_current;
2469   int ret = 0;
2470   int j;
2471
2472   if (i < 0) {
2473     ferr(po, "dead label encountered\n");
2474     return -1;
2475   }
2476
2477   for (; arg < pp->argc; arg++)
2478     if (pp->arg[arg].reg == NULL)
2479       break;
2480   magic = (magic & 0xffffff) | (arg << 24);
2481
2482   for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
2483   {
2484     if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2485       if (ops[j].cc_scratch != magic) {
2486         ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2487            pp->name);
2488         return -1;
2489       }
2490       // ok: have already been here
2491       return 0;
2492     }
2493     ops[j].cc_scratch = magic;
2494
2495     if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2496       lr = &g_label_refs[j];
2497       if (lr->next != NULL)
2498         need_op_saving = 1;
2499       for (; lr->next; lr = lr->next) {
2500         if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2501           may_reuse = 1;
2502         ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2503                 arg, magic, need_op_saving, may_reuse);
2504         if (ret < 0)
2505           return ret;
2506       }
2507
2508       if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2509         may_reuse = 1;
2510       if (j > 0 && LAST_OP(j - 1)) {
2511         // follow last branch in reverse
2512         j = lr->i;
2513         continue;
2514       }
2515       need_op_saving = 1;
2516       ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2517                arg, magic, need_op_saving, may_reuse);
2518       if (ret < 0)
2519         return ret;
2520     }
2521     j--;
2522
2523     if (ops[j].op == OP_CALL)
2524     {
2525       if (pp->is_unresolved)
2526         break;
2527
2528       pp_tmp = ops[j].datap;
2529       if (pp_tmp == NULL)
2530         ferr(po, "arg collect hit unparsed call '%s'\n",
2531           ops[j].operand[0].name);
2532       if (may_reuse && pp_tmp->argc_stack > 0)
2533         ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2534           arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2535     }
2536     else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2537       if (pp->is_unresolved)
2538         break;
2539
2540       ferr(po, "arg collect %d/%d hit esp adjust\n",
2541         arg, pp->argc);
2542     }
2543     else if (ops[j].op == OP_POP) {
2544       if (pp->is_unresolved)
2545         break;
2546
2547       ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2548     }
2549     else if ((ops[j].flags & (OPF_JMP|OPF_CC)) == (OPF_JMP|OPF_CC))
2550     {
2551       if (pp->is_unresolved)
2552         break;
2553
2554       may_reuse = 1;
2555     }
2556     else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2557     {
2558       if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
2559         break;
2560
2561       pp->arg[arg].datap = &ops[j];
2562       need_to_save_current = 0;
2563       if (!need_op_saving) {
2564         ret = scan_for_mod(&ops[j], j + 1, i, 1);
2565         need_to_save_current = (ret >= 0);
2566       }
2567       if (need_op_saving || need_to_save_current) {
2568         // mark this push as one that needs operand saving
2569         ops[j].flags &= ~OPF_RMD;
2570         if (ops[j].argnum == 0) {
2571           ops[j].argnum = arg + 1;
2572           *save_arg_vars |= 1 << arg;
2573         }
2574         else if (ops[j].argnum < arg + 1)
2575           ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2576             ops[j].argnum, arg + 1, pp->name);
2577       }
2578       else if (ops[j].argnum == 0)
2579         ops[j].flags |= OPF_RMD;
2580
2581       // some PUSHes are reused by different calls on other branches,
2582       // but that can't happen if we didn't branch, so they
2583       // can be removed from future searches (handles nested calls)
2584       if (!may_reuse)
2585         ops[j].flags |= OPF_FARG;
2586
2587       ops[j].flags &= ~OPF_RSAVE;
2588
2589       arg++;
2590       if (!pp->is_unresolved) {
2591         // next arg
2592         for (; arg < pp->argc; arg++)
2593           if (pp->arg[arg].reg == NULL)
2594             break;
2595       }
2596       magic = (magic & 0xffffff) | (arg << 24);
2597
2598       // tracking reg usage
2599       if (ops[j].operand[0].type == OPT_REG)
2600         *regmask |= 1 << ops[j].operand[0].reg;
2601     }
2602   }
2603
2604   if (arg < pp->argc) {
2605     ferr(po, "arg collect failed for '%s': %d/%d\n",
2606       pp->name, arg, pp->argc);
2607     return -1;
2608   }
2609
2610   return arg;
2611 }
2612
2613 static int collect_call_args(struct parsed_op *po, int i,
2614   struct parsed_proto *pp, int *regmask, int *save_arg_vars,
2615   int magic)
2616 {
2617   int ret;
2618   int a;
2619
2620   ret = collect_call_args_r(po, i, pp, regmask, save_arg_vars,
2621           0, magic, 0, 0);
2622   if (ret < 0)
2623     return ret;
2624
2625   if (pp->is_unresolved) {
2626     pp->argc += ret;
2627     pp->argc_stack += ret;
2628     for (a = 0; a < pp->argc; a++)
2629       if (pp->arg[a].type.name == NULL)
2630         pp->arg[a].type.name = strdup("int");
2631   }
2632
2633   return ret;
2634 }
2635
2636 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
2637 {
2638   int i;
2639
2640   for (i = 0; i < pp->argc; i++)
2641     if (pp->arg[i].reg == NULL)
2642       break;
2643
2644   if (pp->argc_stack)
2645     memmove(&pp->arg[i + 1], &pp->arg[i],
2646       sizeof(pp->arg[0]) * pp->argc_stack);
2647   memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
2648   pp->arg[i].reg = strdup(reg);
2649   pp->arg[i].type.name = strdup("int");
2650   pp->argc++;
2651   pp->argc_reg++;
2652 }
2653
2654 static void add_label_ref(struct label_ref *lr, int op_i)
2655 {
2656   struct label_ref *lr_new;
2657
2658   if (lr->i == -1) {
2659     lr->i = op_i;
2660     return;
2661   }
2662
2663   lr_new = calloc(1, sizeof(*lr_new));
2664   lr_new->i = op_i;
2665   lr_new->next = lr->next;
2666   lr->next = lr_new;
2667 }
2668
2669 static void output_std_flags(FILE *fout, struct parsed_op *po,
2670   int *pfomask, const char *dst_opr_text)
2671 {
2672   if (*pfomask & (1 << PFO_Z)) {
2673     fprintf(fout, "\n  cond_z = (%s%s == 0);",
2674       lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2675     *pfomask &= ~(1 << PFO_Z);
2676   }
2677   if (*pfomask & (1 << PFO_S)) {
2678     fprintf(fout, "\n  cond_s = (%s%s < 0);",
2679       lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2680     *pfomask &= ~(1 << PFO_S);
2681   }
2682 }
2683
2684 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2685 {
2686   struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2687   struct parsed_opr *last_arith_dst = NULL;
2688   char buf1[256], buf2[256], buf3[256], cast[64];
2689   const struct parsed_proto *pp_c;
2690   struct parsed_proto *pp;
2691   struct parsed_data *pd;
2692   const char *tmpname;
2693   enum parsed_flag_op pfo;
2694   int save_arg_vars = 0;
2695   int cmp_result_vars = 0;
2696   int need_mul_var = 0;
2697   int had_decl = 0;
2698   int label_pending = 0;
2699   int regmask_save = 0;
2700   int regmask_arg = 0;
2701   int regmask_now = 0;
2702   int regmask = 0;
2703   int pfomask = 0;
2704   int found = 0;
2705   int depth = 0;
2706   int no_output;
2707   int i, j, l;
2708   int dummy;
2709   int arg;
2710   int reg;
2711   int ret;
2712
2713   g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2714   g_stack_frame_used = 0;
2715
2716   g_func_pp = proto_parse(fhdr, funcn, 0);
2717   if (g_func_pp == NULL)
2718     ferr(ops, "proto_parse failed for '%s'\n", funcn);
2719
2720   fprintf(fout, "%s ", g_func_pp->ret_type.name);
2721   if (g_func_pp->is_stdcall && g_func_pp->argc_reg == 0)
2722     fprintf(fout, "__stdcall ");
2723   if (g_ida_func_attr & IDAFA_NORETURN)
2724     fprintf(fout, "noreturn ");
2725   fprintf(fout, "%s(", funcn);
2726
2727   for (i = 0; i < g_func_pp->argc; i++) {
2728     if (i > 0)
2729       fprintf(fout, ", ");
2730     if (g_func_pp->arg[i].fptr != NULL) {
2731       // func pointer..
2732       pp = g_func_pp->arg[i].fptr;
2733       fprintf(fout, "%s (", pp->ret_type.name);
2734       if (pp->is_stdcall && pp->argc_reg == 0)
2735         fprintf(fout, "__stdcall ");
2736       fprintf(fout, "*a%d)(", i + 1);
2737       for (j = 0; j < pp->argc; j++) {
2738         if (j > 0)
2739           fprintf(fout, ", ");
2740         if (pp->arg[j].fptr)
2741           ferr(ops, "nested fptr\n");
2742         fprintf(fout, "%s", pp->arg[j].type.name);
2743       }
2744       fprintf(fout, ")");
2745     }
2746     else {
2747       fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2748     }
2749     if (g_func_pp->arg[i].reg != NULL) {
2750       reg = char_array_i(regs_r32,
2751               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2752       if (reg < 0)
2753         ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2754       regmask_arg |= 1 << reg;
2755     }
2756   }
2757   if (g_func_pp->is_vararg) {
2758     if (i > 0)
2759       fprintf(fout, ", ");
2760     fprintf(fout, "...");
2761   }
2762
2763   fprintf(fout, ")\n{\n");
2764
2765   // pass1:
2766   // - handle ebp/esp frame, remove ops related to it
2767   if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2768       && ops[1].op == OP_MOV
2769       && IS(opr_name(&ops[1], 0), "ebp")
2770       && IS(opr_name(&ops[1], 1), "esp"))
2771   {
2772     int ecx_push = 0;
2773
2774     g_bp_frame = 1;
2775     ops[0].flags |= OPF_RMD;
2776     ops[1].flags |= OPF_RMD;
2777     i = 2;
2778
2779     if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2780       g_stack_fsz = opr_const(&ops[2], 1);
2781       ops[2].flags |= OPF_RMD;
2782       i++;
2783     }
2784     else {
2785       // another way msvc builds stack frame..
2786       i = 2;
2787       while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2788         g_stack_fsz += 4;
2789         ops[i].flags |= OPF_RMD;
2790         ecx_push++;
2791         i++;
2792       }
2793       // and another way..
2794       if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2795           && ops[i].operand[1].type == OPT_CONST
2796           && ops[i + 1].op == OP_CALL
2797           && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2798       {
2799         g_stack_fsz += ops[i].operand[1].val;
2800         ops[i].flags |= OPF_RMD;
2801         i++;
2802         ops[i].flags |= OPF_RMD;
2803         i++;
2804       }
2805     }
2806
2807     found = 0;
2808     do {
2809       for (; i < opcnt; i++)
2810         if (ops[i].op == OP_RET)
2811           break;
2812       if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2813         break;
2814
2815       if (ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2816         ops[i - 1].flags |= OPF_RMD;
2817       else if (!(g_ida_func_attr & IDAFA_NORETURN))
2818         ferr(&ops[i - 1], "'pop ebp' expected\n");
2819
2820       if (g_stack_fsz != 0) {
2821         if (ops[i - 2].op == OP_MOV
2822             && IS(opr_name(&ops[i - 2], 0), "esp")
2823             && IS(opr_name(&ops[i - 2], 1), "ebp"))
2824         {
2825           ops[i - 2].flags |= OPF_RMD;
2826         }
2827         else if (!(g_ida_func_attr & IDAFA_NORETURN))
2828           ferr(&ops[i - 2], "esp restore expected\n");
2829
2830         if (ecx_push && ops[i - 3].op == OP_POP
2831           && IS(opr_name(&ops[i - 3], 0), "ecx"))
2832         {
2833           ferr(&ops[i - 3], "unexpected ecx pop\n");
2834         }
2835       }
2836
2837       found = 1;
2838       i++;
2839     } while (i < opcnt);
2840   }
2841   else {
2842     for (i = 0; i < opcnt; i++) {
2843       if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2844         break;
2845       if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2846         && ops[i].operand[1].type == OPT_CONST)
2847       {
2848         g_sp_frame = 1;
2849         break;
2850       }
2851     }
2852
2853     if (g_sp_frame)
2854     {
2855       g_stack_fsz = ops[i].operand[1].val;
2856       ops[i].flags |= OPF_RMD;
2857
2858       i++;
2859       do {
2860         for (; i < opcnt; i++)
2861           if (ops[i].op == OP_RET)
2862             break;
2863         if (ops[i - 1].op != OP_ADD
2864             || !IS(opr_name(&ops[i - 1], 0), "esp")
2865             || ops[i - 1].operand[1].type != OPT_CONST
2866             || ops[i - 1].operand[1].val != g_stack_fsz)
2867           ferr(&ops[i - 1], "'add esp' expected\n");
2868         ops[i - 1].flags |= OPF_RMD;
2869
2870         i++;
2871       } while (i < opcnt);
2872     }
2873   }
2874
2875   // pass2:
2876   // - parse calls with labels
2877   // - resolve all branches
2878   for (i = 0; i < opcnt; i++)
2879   {
2880     po = &ops[i];
2881     po->bt_i = -1;
2882     po->btj = NULL;
2883
2884     if (po->flags & OPF_RMD)
2885       continue;
2886
2887     if (po->op == OP_CALL) {
2888       if (po->operand[0].type == OPT_LABEL) {
2889         tmpname = opr_name(po, 0);
2890         if (IS_START(tmpname, "loc_"))
2891           ferr(po, "call to loc_*\n");
2892         pp_c = proto_parse(fhdr, tmpname, 0);
2893         if (pp_c == NULL)
2894           ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2895         if (pp_c->is_fptr)
2896           check_func_pp(po, pp_c, "fptr var call");
2897         if (pp_c->is_noreturn)
2898           po->flags |= OPF_TAIL;
2899
2900         pp = proto_clone(pp_c);
2901         my_assert_not(pp, NULL);
2902         po->datap = pp;
2903       }
2904       continue;
2905     }
2906
2907     if (!(po->flags & OPF_JMP) || po->op == OP_RET)
2908       continue;
2909
2910     if (po->operand[0].type == OPT_REGMEM) {
2911       char *p = strchr(po->operand[0].name, '[');
2912       if (p == NULL)
2913         goto tailcall;
2914       ret = p - po->operand[0].name;
2915       strncpy(buf1, po->operand[0].name, ret);
2916       buf1[ret] = 0;
2917
2918       for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2919         if (IS(g_func_pd[j].label, buf1)) {
2920           pd = &g_func_pd[j];
2921           break;
2922         }
2923       }
2924       if (pd == NULL)
2925         //ferr(po, "label '%s' not parsed?\n", buf1);
2926         goto tailcall;
2927       if (pd->type != OPT_OFFSET)
2928         ferr(po, "label '%s' with non-offset data?\n", buf1);
2929
2930       // find all labels, link
2931       for (j = 0; j < pd->count; j++) {
2932         for (l = 0; l < opcnt; l++) {
2933           if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
2934             add_label_ref(&g_label_refs[l], i);
2935             pd->d[j].bt_i = l;
2936             break;
2937           }
2938         }
2939       }
2940
2941       po->btj = pd;
2942       continue;
2943     }
2944
2945     for (l = 0; l < opcnt; l++) {
2946       if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
2947         add_label_ref(&g_label_refs[l], i);
2948         po->bt_i = l;
2949         break;
2950       }
2951     }
2952
2953     if (po->bt_i != -1)
2954       continue;
2955
2956     if (po->operand[0].type == OPT_LABEL)
2957       // assume tail call
2958       goto tailcall;
2959
2960     ferr(po, "unhandled branch\n");
2961
2962 tailcall:
2963     po->op = OP_CALL;
2964     po->flags |= OPF_TAIL;
2965     i--; // reprocess
2966   }
2967
2968   // pass3:
2969   // - remove dead labels
2970   // - process calls
2971   for (i = 0; i < opcnt; i++)
2972   {
2973     if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
2974       g_labels[i][0] = 0;
2975
2976     po = &ops[i];
2977     if (po->flags & OPF_RMD)
2978       continue;
2979
2980     if (po->op == OP_CALL)
2981     {
2982       tmpname = opr_name(po, 0);
2983       pp = po->datap;
2984       if (pp == NULL)
2985       {
2986         // indirect call
2987         pp_c = resolve_icall(i, opcnt, &l);
2988         if (pp_c != NULL) {
2989           pp = proto_clone(pp_c);
2990           my_assert_not(pp, NULL);
2991           if (l)
2992             // not resolved just to single func
2993             pp->is_fptr = 1;
2994         }
2995         if (pp == NULL) {
2996           pp = calloc(1, sizeof(*pp));
2997           my_assert_not(pp, NULL);
2998           pp->is_fptr = 1;
2999           ret = scan_for_esp_adjust(i + 1, opcnt, &j);
3000           if (ret < 0) {
3001             if (!g_allow_regfunc)
3002               ferr(po, "non-__cdecl indirect call unhandled yet\n");
3003             pp->is_unresolved = 1;
3004             j = 0;
3005           }
3006           j /= 4;
3007           if (j > ARRAY_SIZE(pp->arg))
3008             ferr(po, "esp adjust too large: %d\n", j);
3009           pp->ret_type.name = strdup("int");
3010           pp->argc = pp->argc_stack = j;
3011           for (arg = 0; arg < pp->argc; arg++)
3012             pp->arg[arg].type.name = strdup("int");
3013         }
3014         po->datap = pp;
3015       }
3016
3017       // look for and make use of esp adjust
3018       ret = -1;
3019       if (!pp->is_stdcall && pp->argc_stack > 0)
3020         ret = scan_for_esp_adjust(i + 1, opcnt, &j);
3021       if (ret >= 0) {
3022         if (pp->is_vararg) {
3023           if (j / 4 < pp->argc_stack)
3024             ferr(po, "esp adjust is too small: %x < %x\n",
3025               j, pp->argc_stack * 4);
3026           // modify pp to make it have varargs as normal args
3027           arg = pp->argc;
3028           pp->argc += j / 4 - pp->argc_stack;
3029           for (; arg < pp->argc; arg++) {
3030             pp->arg[arg].type.name = strdup("int");
3031             pp->argc_stack++;
3032           }
3033           if (pp->argc > ARRAY_SIZE(pp->arg))
3034             ferr(po, "too many args for '%s'\n", tmpname);
3035         }
3036         if (pp->argc_stack != j / 4)
3037           ferr(po, "stack tracking failed for '%s': %x %x\n",
3038             tmpname, pp->argc_stack * 4, j);
3039
3040         ops[ret].flags |= OPF_RMD;
3041         // a bit of a hack, but deals with use of
3042         // single adj for multiple calls
3043         ops[ret].operand[1].val -= j;
3044       }
3045       else if (pp->is_vararg)
3046         ferr(po, "missing esp_adjust for vararg func '%s'\n",
3047           pp->name);
3048
3049       for (arg = 0; arg < pp->argc; arg++) {
3050         if (pp->arg[arg].reg != NULL) {
3051           reg = char_array_i(regs_r32,
3052                   ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
3053           if (reg < 0)
3054             ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
3055           regmask |= 1 << reg;
3056         }
3057 #if 0
3058         if (pp->arg[arg].fptr != NULL) {
3059           // can't call functions with non-__cdecl callbacks yet
3060           struct parsed_proto *pp_tmp;
3061           pp_tmp = pp->arg[arg].fptr;
3062           if (pp_tmp->argc_reg != 0)
3063             ferr(po, "'%s' has a callback with reg-args\n", tmpname);
3064         }
3065 #endif
3066       }
3067
3068       if (!pp->is_unresolved) {
3069         // since we know the args, collect them
3070         collect_call_args(po, i, pp, &regmask, &save_arg_vars,
3071           i + opcnt * 2);
3072       }
3073
3074       if (strstr(pp->ret_type.name, "int64"))
3075         need_mul_var = 1;
3076     }
3077   }
3078
3079   // pass4:
3080   // - find POPs for PUSHes, rm both
3081   // - scan for all used registers
3082   // - find flag set ops for their users
3083   // - do unreselved calls
3084   // - declare indirect functions
3085   for (i = 0; i < opcnt; i++) {
3086     po = &ops[i];
3087     if (po->flags & OPF_RMD)
3088       continue;
3089
3090     if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3091       reg = po->operand[0].reg;
3092       if (!(regmask & (1 << reg)))
3093         // not a reg save after all, rerun scan_for_pop
3094         po->flags &= ~OPF_RSAVE;
3095       else
3096         regmask_save |= 1 << reg;
3097     }
3098
3099     if (po->op == OP_PUSH
3100         && po->argnum == 0 && !(po->flags & OPF_RSAVE)
3101         && po->operand[0].type == OPT_REG)
3102     {
3103       reg = po->operand[0].reg;
3104       if (reg < 0)
3105         ferr(po, "reg not set for push?\n");
3106
3107       depth = 0;
3108       ret = scan_for_pop(i + 1, opcnt,
3109               po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3110       if (ret == 1) {
3111         if (depth > 1)
3112           ferr(po, "too much depth: %d\n", depth);
3113
3114         po->flags |= OPF_RMD;
3115         scan_for_pop(i + 1, opcnt, po->operand[0].name,
3116           i + opcnt * 4, 0, &depth, 1);
3117         continue;
3118       }
3119       ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3120       if (ret == 0) {
3121         arg = OPF_RMD;
3122         if (regmask & (1 << reg)) {
3123           if (regmask_save & (1 << reg))
3124             ferr(po, "%s already saved?\n", po->operand[0].name);
3125           arg = OPF_RSAVE;
3126         }
3127         po->flags |= arg;
3128         scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3129         continue;
3130       }
3131     }
3132
3133     regmask_now = po->regmask_src | po->regmask_dst;
3134     if (regmask_now & (1 << xBP)) {
3135       if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3136         if (po->regmask_dst & (1 << xBP))
3137           // compiler decided to drop bp frame and use ebp as scratch
3138           scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
3139         else
3140           regmask_now &= ~(1 << xBP);
3141       }
3142     }
3143
3144     regmask |= regmask_now;
3145
3146     if (po->flags & OPF_CC)
3147     {
3148       int setters[16], cnt = 0, branched = 0;
3149
3150       ret = scan_for_flag_set(i, i + opcnt * 6,
3151               &branched, setters, &cnt);
3152       if (ret < 0 || cnt <= 0)
3153         ferr(po, "unable to trace flag setter(s)\n");
3154       if (cnt > ARRAY_SIZE(setters))
3155         ferr(po, "too many flag setters\n");
3156
3157       pfo = split_cond(po, po->op, &dummy);
3158       for (j = 0; j < cnt; j++)
3159       {
3160         tmp_op = &ops[setters[j]]; // flag setter
3161         pfomask = 0;
3162
3163         // to get nicer code, we try to delay test and cmp;
3164         // if we can't because of operand modification, or if we
3165         // have math op, or branch, make it calculate flags explicitly
3166         if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
3167           if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
3168             pfomask = 1 << pfo;
3169         }
3170         else if (tmp_op->op == OP_CMPS) {
3171           pfomask = 1 << PFO_Z;
3172         }
3173         else {
3174           // see if we'll be able to handle based on op result
3175           if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3176                && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3177               || branched
3178               || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3179             pfomask = 1 << pfo;
3180         }
3181         if (pfomask) {
3182           tmp_op->pfomask |= pfomask;
3183           cmp_result_vars |= pfomask;
3184         }
3185         // note: may overwrite, currently not a problem
3186         po->datap = tmp_op;
3187       }
3188
3189       if (po->op == OP_ADC || po->op == OP_SBB)
3190         cmp_result_vars |= 1 << PFO_C;
3191     }
3192     else if (po->op == OP_MUL
3193       || (po->op == OP_IMUL && po->operand_cnt == 1))
3194     {
3195       need_mul_var = 1;
3196     }
3197     else if (po->op == OP_CALL) {
3198       pp = po->datap;
3199       if (pp == NULL)
3200         ferr(po, "NULL pp\n");
3201
3202       if (pp->is_unresolved) {
3203         int regmask_push = 0;
3204         collect_call_args(po, i, pp, &regmask_push, &save_arg_vars,
3205           i + opcnt * 2);
3206
3207         if (!((regmask_push & (1 << xCX))
3208           && (regmask_push & (1 << xDX))))
3209         {
3210           if (pp->argc_stack != 0
3211            || ((regmask | regmask_arg) & (1 << xCX)))
3212           {
3213             pp_insert_reg_arg(pp, "ecx");
3214             regmask |= 1 << xCX;
3215           }
3216           if (pp->argc_stack != 0
3217            || ((regmask | regmask_arg) & (1 << xDX)))
3218           {
3219             pp_insert_reg_arg(pp, "edx");
3220             regmask |= 1 << xDX;
3221           }
3222         }
3223         regmask |= regmask_push;
3224       }
3225
3226       if (pp->is_fptr) {
3227         fprintf(fout, "  %s (", pp->ret_type.name);
3228         if (pp->is_stdcall && pp->argc_reg == 0)
3229           fprintf(fout, "__stdcall ");
3230         fprintf(fout, "*icall%d)(", i);
3231         for (j = 0; j < pp->argc; j++) {
3232           if (j > 0)
3233             fprintf(fout, ", ");
3234           fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3235         }
3236         fprintf(fout, ");\n");
3237       }
3238     }
3239     else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3240       regmask |= 1 << xAX;
3241   }
3242
3243   // pass4:
3244   // - confirm regmask_save, it might have been reduced
3245   if (regmask_save != 0)
3246   {
3247     regmask_save = 0;
3248     for (i = 0; i < opcnt; i++) {
3249       po = &ops[i];
3250       if (po->flags & OPF_RMD)
3251         continue;
3252
3253       if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
3254         regmask_save |= 1 << po->operand[0].reg;
3255     }
3256   }
3257
3258
3259   // output LUTs/jumptables
3260   for (i = 0; i < g_func_pd_cnt; i++) {
3261     pd = &g_func_pd[i];
3262     fprintf(fout, "  static const ");
3263     if (pd->type == OPT_OFFSET) {
3264       fprintf(fout, "void *jt_%s[] =\n    { ", pd->label);
3265
3266       for (j = 0; j < pd->count; j++) {
3267         if (j > 0)
3268           fprintf(fout, ", ");
3269         fprintf(fout, "&&%s", pd->d[j].u.label);
3270       }
3271     }
3272     else {
3273       fprintf(fout, "%s %s[] =\n    { ",
3274         lmod_type_u(ops, pd->lmod), pd->label);
3275
3276       for (j = 0; j < pd->count; j++) {
3277         if (j > 0)
3278           fprintf(fout, ", ");
3279         fprintf(fout, "%u", pd->d[j].u.val);
3280       }
3281     }
3282     fprintf(fout, " };\n");
3283   }
3284
3285   // declare stack frame, va_arg
3286   if (g_stack_fsz)
3287     fprintf(fout, "  union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3288       (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3289
3290   if (g_func_pp->is_vararg)
3291     fprintf(fout, "  va_list ap;\n");
3292
3293   // declare arg-registers
3294   for (i = 0; i < g_func_pp->argc; i++) {
3295     if (g_func_pp->arg[i].reg != NULL) {
3296       reg = char_array_i(regs_r32,
3297               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3298       if (regmask & (1 << reg)) {
3299         fprintf(fout, "  u32 %s = (u32)a%d;\n",
3300           g_func_pp->arg[i].reg, i + 1);
3301       }
3302       else
3303         fprintf(fout, "  // %s = a%d; // unused\n",
3304           g_func_pp->arg[i].reg, i + 1);
3305       had_decl = 1;
3306     }
3307   }
3308
3309   regmask_now = regmask & ~regmask_arg;
3310   regmask_now &= ~(1 << xSP);
3311   if (regmask_now) {
3312     for (reg = 0; reg < 8; reg++) {
3313       if (regmask_now & (1 << reg)) {
3314         fprintf(fout, "  u32 %s;\n", regs_r32[reg]);
3315         had_decl = 1;
3316       }
3317     }
3318   }
3319
3320   if (regmask_save) {
3321     for (reg = 0; reg < 8; reg++) {
3322       if (regmask_save & (1 << reg)) {
3323         fprintf(fout, "  u32 s_%s;\n", regs_r32[reg]);
3324         had_decl = 1;
3325       }
3326     }
3327   }
3328
3329   if (save_arg_vars) {
3330     for (reg = 0; reg < 32; reg++) {
3331       if (save_arg_vars & (1 << reg)) {
3332         fprintf(fout, "  u32 s_a%d;\n", reg + 1);
3333         had_decl = 1;
3334       }
3335     }
3336   }
3337
3338   if (cmp_result_vars) {
3339     for (i = 0; i < 8; i++) {
3340       if (cmp_result_vars & (1 << i)) {
3341         fprintf(fout, "  u32 cond_%s;\n", parsed_flag_op_names[i]);
3342         had_decl = 1;
3343       }
3344     }
3345   }
3346
3347   if (need_mul_var) {
3348     fprintf(fout, "  u64 mul_tmp;\n");
3349     had_decl = 1;
3350   }
3351
3352   if (had_decl)
3353     fprintf(fout, "\n");
3354
3355   if (g_func_pp->is_vararg) {
3356     if (g_func_pp->argc_stack == 0)
3357       ferr(ops, "vararg func without stack args?\n");
3358     fprintf(fout, "  va_start(ap, a%d);\n", g_func_pp->argc);
3359   }
3360
3361   // output ops
3362   for (i = 0; i < opcnt; i++)
3363   {
3364     if (g_labels[i][0] != 0) {
3365       fprintf(fout, "\n%s:\n", g_labels[i]);
3366       label_pending = 1;
3367
3368       delayed_flag_op = NULL;
3369       last_arith_dst = NULL;
3370     }
3371
3372     po = &ops[i];
3373     if (po->flags & OPF_RMD)
3374       continue;
3375
3376     no_output = 0;
3377
3378     #define assert_operand_cnt(n_) \
3379       if (po->operand_cnt != n_) \
3380         ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3381
3382     // conditional/flag using op?
3383     if (po->flags & OPF_CC)
3384     {
3385       int is_delayed = 0;
3386       int is_inv = 0;
3387
3388       pfo = split_cond(po, po->op, &is_inv);
3389       tmp_op = po->datap;
3390
3391       // we go through all this trouble to avoid using parsed_flag_op,
3392       // which makes generated code much nicer
3393       if (delayed_flag_op != NULL)
3394       {
3395         out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3396         is_delayed = 1;
3397       }
3398       else if (last_arith_dst != NULL
3399         && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3400            || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3401            ))
3402       {
3403         out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3404         out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3405           last_arith_dst->lmod, buf3);
3406         is_delayed = 1;
3407       }
3408       else if (tmp_op != NULL) {
3409         // use preprocessed flag calc results
3410         if (!(tmp_op->pfomask & (1 << pfo)))
3411           ferr(po, "not prepared for pfo %d\n", pfo);
3412
3413         // note: is_inv was not yet applied
3414         snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3415           is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3416       }
3417       else {
3418         ferr(po, "all methods of finding comparison failed\n");
3419       }
3420  
3421       if (po->flags & OPF_JMP) {
3422         fprintf(fout, "  if %s\n", buf1);
3423       }
3424       else if (po->op == OP_ADC || po->op == OP_SBB) {
3425         if (is_delayed)
3426           fprintf(fout, "  cond_%s = %s;\n",
3427             parsed_flag_op_names[pfo], buf1);
3428       }
3429       else if (po->flags & OPF_DATA) { // SETcc
3430         out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3431         fprintf(fout, "  %s = %s;", buf2, buf1);
3432       }
3433       else {
3434         ferr(po, "unhandled conditional op\n");
3435       }
3436     }
3437
3438     pfomask = po->pfomask;
3439
3440     switch (po->op)
3441     {
3442       case OP_MOV:
3443         assert_operand_cnt(2);
3444         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3445         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3446         fprintf(fout, "  %s = %s;", buf1,
3447             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3448               po->operand[0].is_ptr ? "(void *)" : "", 0));
3449         break;
3450
3451       case OP_LEA:
3452         assert_operand_cnt(2);
3453         po->operand[1].lmod = OPLM_DWORD; // always
3454         fprintf(fout, "  %s = %s;",
3455             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3456             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3457               NULL, 1));
3458         break;
3459
3460       case OP_MOVZX:
3461         assert_operand_cnt(2);
3462         fprintf(fout, "  %s = %s;",
3463             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3464             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3465         break;
3466
3467       case OP_MOVSX:
3468         assert_operand_cnt(2);
3469         switch (po->operand[1].lmod) {
3470         case OPLM_BYTE:
3471           strcpy(buf3, "(s8)");
3472           break;
3473         case OPLM_WORD:
3474           strcpy(buf3, "(s16)");
3475           break;
3476         default:
3477           ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3478         }
3479         fprintf(fout, "  %s = %s;",
3480             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3481             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3482               buf3, 0));
3483         break;
3484
3485       case OP_NOT:
3486         assert_operand_cnt(1);
3487         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3488         fprintf(fout, "  %s = ~%s;", buf1, buf1);
3489         break;
3490
3491       case OP_CDQ:
3492         assert_operand_cnt(2);
3493         fprintf(fout, "  %s = (s32)%s >> 31;",
3494             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3495             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3496         strcpy(g_comment, "cdq");
3497         break;
3498
3499       case OP_STOS:
3500         // assumes DF=0
3501         assert_operand_cnt(3);
3502         if (po->flags & OPF_REP) {
3503           fprintf(fout, "  for (; ecx != 0; ecx--, edi += %d)\n",
3504             lmod_bytes(po, po->operand[0].lmod));
3505           fprintf(fout, "    %sedi = eax;",
3506             lmod_cast_u_ptr(po, po->operand[0].lmod));
3507           strcpy(g_comment, "rep stos");
3508         }
3509         else {
3510           fprintf(fout, "    %sedi = eax; edi += %d;",
3511             lmod_cast_u_ptr(po, po->operand[0].lmod),
3512             lmod_bytes(po, po->operand[0].lmod));
3513           strcpy(g_comment, "stos");
3514         }
3515         break;
3516
3517       case OP_MOVS:
3518         // assumes DF=0
3519         assert_operand_cnt(3);
3520         j = lmod_bytes(po, po->operand[0].lmod);
3521         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3522         if (po->flags & OPF_REP) {
3523           fprintf(fout,
3524             "  for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3525             j, j);
3526           fprintf(fout,
3527             "    %sedi = %sesi;", buf1, buf1);
3528           strcpy(g_comment, "rep movs");
3529         }
3530         else {
3531           fprintf(fout, "    %sedi = %sesi; edi += %d; esi += %d;",
3532             buf1, buf1, j, j);
3533           strcpy(g_comment, "movs");
3534         }
3535         break;
3536
3537       case OP_CMPS:
3538         // assumes DF=0
3539         // repe ~ repeat while ZF=1
3540         assert_operand_cnt(3);
3541         j = lmod_bytes(po, po->operand[0].lmod);
3542         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3543         if (po->flags & OPF_REP) {
3544           fprintf(fout,
3545             "  for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3546             j, j);
3547           fprintf(fout,
3548             "    if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3549               buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3550           fprintf(fout,
3551             "      break;");
3552           snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3553             (po->flags & OPF_REPZ) ? "e" : "ne");
3554         }
3555         else {
3556           fprintf(fout,
3557             "    cond_z = (%sedi = %sesi); edi += %d; esi += %d;",
3558             buf1, buf1, j, j);
3559           strcpy(g_comment, "cmps");
3560         }
3561         pfomask &= ~(1 << PFO_Z);
3562         last_arith_dst = NULL;
3563         delayed_flag_op = NULL;
3564         break;
3565
3566       // arithmetic w/flags
3567       case OP_ADD:
3568       case OP_SUB:
3569       case OP_AND:
3570       case OP_OR:
3571         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3572         // fallthrough
3573       dualop_arith:
3574         assert_operand_cnt(2);
3575         fprintf(fout, "  %s %s= %s;",
3576             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3577             op_to_c(po),
3578             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3579         output_std_flags(fout, po, &pfomask, buf1);
3580         last_arith_dst = &po->operand[0];
3581         delayed_flag_op = NULL;
3582         break;
3583
3584       case OP_SHL:
3585       case OP_SHR:
3586         assert_operand_cnt(2);
3587         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3588         if (pfomask & (1 << PFO_C)) {
3589           if (po->operand[1].type == OPT_CONST) {
3590             l = lmod_bytes(po, po->operand[0].lmod) * 8;
3591             j = po->operand[1].val;
3592             j %= l;
3593             if (j != 0) {
3594               if (po->op == OP_SHL)
3595                 j = l - j;
3596               else
3597                 j -= 1;
3598               fprintf(fout, "  cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3599                 buf1, 1 << j);
3600             }
3601             else
3602               ferr(po, "zero shift?\n");
3603           }
3604           else
3605             ferr(po, "TODO\n");
3606           pfomask &= ~(1 << PFO_C);
3607         }
3608         fprintf(fout, "  %s %s= %s;", buf1, op_to_c(po),
3609             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3610         output_std_flags(fout, po, &pfomask, buf1);
3611         last_arith_dst = &po->operand[0];
3612         delayed_flag_op = NULL;
3613         break;
3614
3615       case OP_SAR:
3616         assert_operand_cnt(2);
3617         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3618         fprintf(fout, "  %s = %s%s >> %s;", buf1,
3619           lmod_cast_s(po, po->operand[0].lmod), buf1,
3620           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3621         output_std_flags(fout, po, &pfomask, buf1);
3622         last_arith_dst = &po->operand[0];
3623         delayed_flag_op = NULL;
3624         break;
3625
3626       case OP_ROL:
3627       case OP_ROR:
3628         assert_operand_cnt(2);
3629         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3630         if (po->operand[1].type == OPT_CONST) {
3631           j = po->operand[1].val;
3632           j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3633           fprintf(fout, po->op == OP_ROL ?
3634             "  %s = (%s << %d) | (%s >> %d);" :
3635             "  %s = (%s >> %d) | (%s << %d);",
3636             buf1, buf1, j, buf1,
3637             lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3638         }
3639         else
3640           ferr(po, "TODO\n");
3641         output_std_flags(fout, po, &pfomask, buf1);
3642         last_arith_dst = &po->operand[0];
3643         delayed_flag_op = NULL;
3644         break;
3645
3646       case OP_XOR:
3647         assert_operand_cnt(2);
3648         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3649         if (IS(opr_name(po, 0), opr_name(po, 1))) {
3650           // special case for XOR
3651           fprintf(fout, "  %s = 0;",
3652             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3653           last_arith_dst = &po->operand[0];
3654           delayed_flag_op = NULL;
3655           break;
3656         }
3657         goto dualop_arith;
3658
3659       case OP_ADC:
3660       case OP_SBB:
3661         assert_operand_cnt(2);
3662         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3663         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3664         if (po->op == OP_SBB
3665           && IS(po->operand[0].name, po->operand[1].name))
3666         {
3667           // avoid use of unitialized var
3668           fprintf(fout, "  %s = -cond_c;", buf1);
3669           // carry remains what it was
3670           pfomask &= ~(1 << PFO_C);
3671         }
3672         else {
3673           fprintf(fout, "  %s %s= %s + cond_c;", buf1, op_to_c(po),
3674             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3675         }
3676         output_std_flags(fout, po, &pfomask, buf1);
3677         last_arith_dst = &po->operand[0];
3678         delayed_flag_op = NULL;
3679         break;
3680
3681       case OP_INC:
3682       case OP_DEC:
3683         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3684         if (po->operand[0].type == OPT_REG) {
3685           strcpy(buf2, po->op == OP_INC ? "++" : "--");
3686           fprintf(fout, "  %s%s;", buf1, buf2);
3687         }
3688         else {
3689           strcpy(buf2, po->op == OP_INC ? "+" : "-");
3690           fprintf(fout, "  %s %s= 1;", buf1, buf2);
3691         }
3692         output_std_flags(fout, po, &pfomask, buf1);
3693         last_arith_dst = &po->operand[0];
3694         delayed_flag_op = NULL;
3695         break;
3696
3697       case OP_NEG:
3698         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3699         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3700         fprintf(fout, "  %s = -%s%s;", buf1,
3701           lmod_cast_s(po, po->operand[0].lmod), buf2);
3702         last_arith_dst = &po->operand[0];
3703         delayed_flag_op = NULL;
3704         if (pfomask & (1 << PFO_C)) {
3705           fprintf(fout, "\n  cond_c = (%s != 0);", buf1);
3706           pfomask &= ~(1 << PFO_C);
3707         }
3708         break;
3709
3710       case OP_IMUL:
3711         if (po->operand_cnt == 2) {
3712           propagate_lmod(po, &po->operand[0], &po->operand[1]);
3713           goto dualop_arith;
3714         }
3715         if (po->operand_cnt == 3)
3716           ferr(po, "TODO imul3\n");
3717         // fallthrough
3718       case OP_MUL:
3719         assert_operand_cnt(1);
3720         strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3721         fprintf(fout, "  mul_tmp = %seax * %s%s;\n", buf1, buf1,
3722           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3723         fprintf(fout, "  edx = mul_tmp >> 32;\n");
3724         fprintf(fout, "  eax = mul_tmp;");
3725         last_arith_dst = NULL;
3726         delayed_flag_op = NULL;
3727         break;
3728
3729       case OP_DIV:
3730       case OP_IDIV:
3731         assert_operand_cnt(1);
3732         if (po->operand[0].lmod != OPLM_DWORD)
3733           ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3734
3735         // 32bit division is common, look for it
3736         if (po->op == OP_DIV)
3737           ret = scan_for_reg_clear(i, xDX);
3738         else
3739           ret = scan_for_cdq_edx(i);
3740         if (ret >= 0) {
3741           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3742           strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3743             po->op == OP_IDIV));
3744           fprintf(fout, "  edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3745           fprintf(fout, "  eax = %seax / %s%s;", buf2, buf2, buf1);
3746         }
3747         else
3748           ferr(po, "TODO 64bit divident\n");
3749         last_arith_dst = NULL;
3750         delayed_flag_op = NULL;
3751         break;
3752
3753       case OP_TEST:
3754       case OP_CMP:
3755         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3756         if (pfomask != 0) {
3757           for (j = 0; j < 8; j++) {
3758             if (pfomask & (1 << j)) {
3759               out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3760               fprintf(fout, "  cond_%s = %s;",
3761                 parsed_flag_op_names[j], buf1);
3762             }
3763           }
3764           pfomask = 0;
3765         }
3766         else
3767           no_output = 1;
3768         last_arith_dst = NULL;
3769         delayed_flag_op = po;
3770         break;
3771
3772       // note: we reuse OP_Jcc for SETcc, only flags differ
3773       case OP_JO ... OP_JG:
3774         if (po->flags & OPF_JMP)
3775           fprintf(fout, "    goto %s;", po->operand[0].name);
3776         // else SETcc - should already be handled
3777         break;
3778
3779       case OP_JMP:
3780         assert_operand_cnt(1);
3781         last_arith_dst = NULL;
3782         delayed_flag_op = NULL;
3783
3784         if (po->operand[0].type == OPT_REGMEM) {
3785           ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
3786                   buf1, buf2);
3787           if (ret != 2)
3788             ferr(po, "parse failure for jmp '%s'\n",
3789               po->operand[0].name);
3790           fprintf(fout, "  goto *jt_%s[%s];", buf1, buf2);
3791           break;
3792         }
3793         else if (po->operand[0].type != OPT_LABEL)
3794           ferr(po, "unhandled jmp type\n");
3795
3796         fprintf(fout, "  goto %s;", po->operand[0].name);
3797         break;
3798
3799       case OP_CALL:
3800         assert_operand_cnt(1);
3801         pp = po->datap;
3802         my_assert_not(pp, NULL);
3803
3804         if (pp->is_fptr)
3805           fprintf(fout, "  icall%d = %s;\n", i,
3806             out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
3807               "(void *)", 0));
3808
3809         fprintf(fout, "  ");
3810         if (strstr(pp->ret_type.name, "int64")) {
3811           if (po->flags & OPF_TAIL)
3812             ferr(po, "int64 and tail?\n");
3813           fprintf(fout, "mul_tmp = ");
3814         }
3815         else if (!IS(pp->ret_type.name, "void")) {
3816           if (po->flags & OPF_TAIL) {
3817             if (!IS(g_func_pp->ret_type.name, "void")) {
3818               fprintf(fout, "return ");
3819               if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
3820                 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
3821             }
3822           }
3823           else if (regmask & (1 << xAX)) {
3824             fprintf(fout, "eax = ");
3825             if (pp->ret_type.is_ptr)
3826               fprintf(fout, "(u32)");
3827           }
3828         }
3829
3830         if (pp->is_fptr) {
3831           fprintf(fout, "icall%d(", i);
3832         }
3833         else {
3834           if (pp->name[0] == 0)
3835             ferr(po, "missing pp->name\n");
3836           fprintf(fout, "%s%s(", pp->name,
3837             pp->has_structarg ? "_sa" : "");
3838         }
3839
3840         for (arg = 0; arg < pp->argc; arg++) {
3841           if (arg > 0)
3842             fprintf(fout, ", ");
3843
3844           cast[0] = 0;
3845           if (pp->arg[arg].type.is_ptr)
3846             snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
3847
3848           if (pp->arg[arg].reg != NULL) {
3849             fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
3850             continue;
3851           }
3852
3853           // stack arg
3854           tmp_op = pp->arg[arg].datap;
3855           if (tmp_op == NULL)
3856             ferr(po, "parsed_op missing for arg%d\n", arg);
3857           if (tmp_op->argnum != 0) {
3858             fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
3859           }
3860           else {
3861             fprintf(fout, "%s",
3862               out_src_opr(buf1, sizeof(buf1),
3863                 tmp_op, &tmp_op->operand[0], cast, 0));
3864           }
3865         }
3866         fprintf(fout, ");");
3867
3868         if (strstr(pp->ret_type.name, "int64")) {
3869           fprintf(fout, "\n");
3870           fprintf(fout, "  edx = mul_tmp >> 32;\n");
3871           fprintf(fout, "  eax = mul_tmp;");
3872         }
3873
3874         if (pp->is_unresolved) {
3875           snprintf(buf3, sizeof(buf3), "unresoved %dreg ",
3876             pp->argc_reg);
3877           strcat(g_comment, buf3);
3878         }
3879
3880         if (po->flags & OPF_TAIL) {
3881           ret = 0;
3882           if (i == opcnt - 1)
3883             ret = 0;
3884           else if (IS(pp->ret_type.name, "void"))
3885             ret = 1;
3886           else if (IS(g_func_pp->ret_type.name, "void"))
3887             ret = 1;
3888           // else already handled as 'return f()'
3889
3890           if (ret) {
3891             if (!IS(g_func_pp->ret_type.name, "void")) {
3892               if (!pp->is_noreturn)
3893                 ferr(po, "int func -> void func tailcall?\n");
3894               strcat(g_comment, "tailcall noreturn");
3895             }
3896             else {
3897               fprintf(fout, "\n  return;");
3898               strcat(g_comment, "^ tailcall");
3899             }
3900           }
3901           else
3902             strcat(g_comment, "tailcall");
3903         }
3904         delayed_flag_op = NULL;
3905         last_arith_dst = NULL;
3906         break;
3907
3908       case OP_RET:
3909         if (g_func_pp->is_vararg)
3910           fprintf(fout, "  va_end(ap);\n");
3911  
3912         if (IS(g_func_pp->ret_type.name, "void")) {
3913           if (i != opcnt - 1 || label_pending)
3914             fprintf(fout, "  return;");
3915         }
3916         else if (g_func_pp->ret_type.is_ptr) {
3917           fprintf(fout, "  return (%s)eax;",
3918             g_func_pp->ret_type.name);
3919         }
3920         else
3921           fprintf(fout, "  return eax;");
3922
3923         last_arith_dst = NULL;
3924         delayed_flag_op = NULL;
3925         break;
3926
3927       case OP_PUSH:
3928         if (po->argnum != 0) {
3929           // special case - saved func arg
3930           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3931           fprintf(fout, "  s_a%d = %s;", po->argnum, buf1);
3932           break;
3933         }
3934         else if (po->flags & OPF_RSAVE) {
3935           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3936           fprintf(fout, "  s_%s = %s;", buf1, buf1);
3937           break;
3938         }
3939         if (!(g_ida_func_attr & IDAFA_NORETURN))
3940           ferr(po, "stray push encountered\n");
3941         no_output = 1;
3942         break;
3943
3944       case OP_POP:
3945         if (po->flags & OPF_RSAVE) {
3946           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3947           fprintf(fout, "  %s = s_%s;", buf1, buf1);
3948           break;
3949         }
3950         ferr(po, "stray pop encountered\n");
3951         break;
3952
3953       case OP_NOP:
3954         no_output = 1;
3955         break;
3956
3957       default:
3958         no_output = 1;
3959         ferr(po, "unhandled op type %d, flags %x\n",
3960           po->op, po->flags);
3961         break;
3962     }
3963
3964     if (g_comment[0] != 0) {
3965       fprintf(fout, "  // %s", g_comment);
3966       g_comment[0] = 0;
3967       no_output = 0;
3968     }
3969     if (!no_output)
3970       fprintf(fout, "\n");
3971
3972     // some sanity checking
3973     if ((po->flags & OPF_REP) && po->op != OP_STOS
3974         && po->op != OP_MOVS && po->op != OP_CMPS)
3975       ferr(po, "unexpected rep\n");
3976     if ((po->flags & (OPF_REPZ|OPF_REPNZ)) && po->op != OP_CMPS)
3977       ferr(po, "unexpected repz/repnz\n");
3978
3979     if (pfomask != 0)
3980       ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
3981
3982     // see is delayed flag stuff is still valid
3983     if (delayed_flag_op != NULL && delayed_flag_op != po) {
3984       if (is_any_opr_modified(delayed_flag_op, po, 0))
3985         delayed_flag_op = NULL;
3986     }
3987
3988     if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
3989       if (is_opr_modified(last_arith_dst, po))
3990         last_arith_dst = NULL;
3991     }
3992
3993     label_pending = 0;
3994   }
3995
3996   if (g_stack_fsz && !g_stack_frame_used)
3997     fprintf(fout, "  (void)sf;\n");
3998
3999   fprintf(fout, "}\n\n");
4000
4001   // cleanup
4002   for (i = 0; i < opcnt; i++) {
4003     struct label_ref *lr, *lr_del;
4004
4005     lr = g_label_refs[i].next;
4006     while (lr != NULL) {
4007       lr_del = lr;
4008       lr = lr->next;
4009       free(lr_del);
4010     }
4011     g_label_refs[i].i = -1;
4012     g_label_refs[i].next = NULL;
4013
4014     if (ops[i].op == OP_CALL) {
4015       pp = ops[i].datap;
4016       if (pp)
4017         proto_release(pp);
4018     }
4019   }
4020   g_func_pp = NULL;
4021 }
4022
4023 static void set_label(int i, const char *name)
4024 {
4025   const char *p;
4026   int len;
4027
4028   len = strlen(name);
4029   p = strchr(name, ':');
4030   if (p != NULL)
4031     len = p - name;
4032
4033   if (len > sizeof(g_labels[0]) - 1)
4034     aerr("label '%s' too long: %d\n", name, len);
4035   if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
4036     aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
4037   memcpy(g_labels[i], name, len);
4038   g_labels[i][len] = 0;
4039 }
4040
4041 // '=' needs special treatment..
4042 static char *next_word_s(char *w, size_t wsize, char *s)
4043 {
4044         size_t i;
4045
4046         s = sskip(s);
4047
4048         for (i = 0; i < wsize - 1; i++) {
4049                 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
4050                         break;
4051                 w[i] = s[i];
4052         }
4053         w[i] = 0;
4054
4055         if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
4056                 printf("warning: '%s' truncated\n", w);
4057
4058         return s + i;
4059 }
4060
4061 struct chunk_item {
4062   char *name;
4063   long fptr;
4064   int asmln;
4065 };
4066
4067 static struct chunk_item *func_chunks;
4068 static int func_chunk_cnt;
4069 static int func_chunk_alloc;
4070
4071 static void add_func_chunk(FILE *fasm, const char *name, int line)
4072 {
4073   if (func_chunk_cnt >= func_chunk_alloc) {
4074     func_chunk_alloc *= 2;
4075     func_chunks = realloc(func_chunks,
4076       func_chunk_alloc * sizeof(func_chunks[0]));
4077     my_assert_not(func_chunks, NULL);
4078   }
4079   func_chunks[func_chunk_cnt].fptr = ftell(fasm);
4080   func_chunks[func_chunk_cnt].name = strdup(name);
4081   func_chunks[func_chunk_cnt].asmln = line;
4082   func_chunk_cnt++;
4083 }
4084
4085 static int cmp_chunks(const void *p1, const void *p2)
4086 {
4087   const struct chunk_item *c1 = p1, *c2 = p2;
4088   return strcmp(c1->name, c2->name);
4089 }
4090
4091 static int cmpstringp(const void *p1, const void *p2)
4092 {
4093   return strcmp(*(char * const *)p1, *(char * const *)p2);
4094 }
4095
4096 static void scan_ahead(FILE *fasm)
4097 {
4098   char words[2][256];
4099   char line[256];
4100   long oldpos;
4101   int oldasmln;
4102   int wordc;
4103   char *p;
4104   int i;
4105
4106   oldpos = ftell(fasm);
4107   oldasmln = asmln;
4108
4109   while (fgets(line, sizeof(line), fasm))
4110   {
4111     wordc = 0;
4112     asmln++;
4113
4114     p = sskip(line);
4115     if (*p == 0)
4116       continue;
4117
4118     if (*p == ';')
4119     {
4120       // get rid of random tabs
4121       for (i = 0; line[i] != 0; i++)
4122         if (line[i] == '\t')
4123           line[i] = ' ';
4124
4125       if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4126       {
4127         p += 30;
4128         next_word(words[0], sizeof(words[0]), p);
4129         if (words[0][0] == 0)
4130           aerr("missing name for func chunk?\n");
4131
4132         add_func_chunk(fasm, words[0], asmln);
4133       }
4134       continue;
4135     } // *p == ';'
4136
4137     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4138       words[wordc][0] = 0;
4139       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4140       if (*p == 0 || *p == ';') {
4141         wordc++;
4142         break;
4143       }
4144     }
4145
4146     if (wordc == 2 && IS(words[1], "ends"))
4147       break;
4148   }
4149
4150   fseek(fasm, oldpos, SEEK_SET);
4151   asmln = oldasmln;
4152 }
4153
4154 int main(int argc, char *argv[])
4155 {
4156   FILE *fout, *fasm, *frlist;
4157   struct parsed_data *pd = NULL;
4158   int pd_alloc = 0;
4159   char **rlist = NULL;
4160   int rlist_len = 0;
4161   int rlist_alloc = 0;
4162   int func_chunks_used = 0;
4163   int func_chunks_sorted = 0;
4164   int func_chunk_i = -1;
4165   long func_chunk_ret = 0;
4166   int func_chunk_ret_ln = 0;
4167   int scanned_ahead = 0;
4168   char line[256];
4169   char words[20][256];
4170   enum opr_lenmod lmod;
4171   int in_func = 0;
4172   int pending_endp = 0;
4173   int skip_func = 0;
4174   int skip_warned = 0;
4175   int eq_alloc;
4176   int verbose = 0;
4177   int arg_out;
4178   int arg;
4179   int pi = 0;
4180   int i, j;
4181   int ret, len;
4182   char *p;
4183   int wordc;
4184
4185   for (arg = 1; arg < argc; arg++) {
4186     if (IS(argv[arg], "-v"))
4187       verbose = 1;
4188     else if (IS(argv[arg], "-rf"))
4189       g_allow_regfunc = 1;
4190     else
4191       break;
4192   }
4193
4194   if (argc < arg + 3) {
4195     printf("usage:\n%s [-v] [-rf] <.c> <.asm> <hdrf> [rlist]*\n",
4196       argv[0]);
4197     return 1;
4198   }
4199
4200   arg_out = arg++;
4201
4202   asmfn = argv[arg++];
4203   fasm = fopen(asmfn, "r");
4204   my_assert_not(fasm, NULL);
4205
4206   hdrfn = argv[arg++];
4207   g_fhdr = fopen(hdrfn, "r");
4208   my_assert_not(g_fhdr, NULL);
4209
4210   rlist_alloc = 64;
4211   rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4212   my_assert_not(rlist, NULL);
4213   // needs special handling..
4214   rlist[rlist_len++] = "__alloca_probe";
4215
4216   func_chunk_alloc = 32;
4217   func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4218   my_assert_not(func_chunks, NULL);
4219
4220   memset(words, 0, sizeof(words));
4221
4222   for (; arg < argc; arg++) {
4223     frlist = fopen(argv[arg], "r");
4224     my_assert_not(frlist, NULL);
4225
4226     while (fgets(line, sizeof(line), frlist)) {
4227       p = sskip(line);
4228       if (*p == 0 || *p == ';')
4229         continue;
4230       if (*p == '#') {
4231         if (IS_START(p, "#if 0")
4232          || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
4233         {
4234           skip_func = 1;
4235         }
4236         else if (IS_START(p, "#endif"))
4237           skip_func = 0;
4238         continue;
4239       }
4240       if (skip_func)
4241         continue;
4242
4243       p = next_word(words[0], sizeof(words[0]), p);
4244       if (words[0][0] == 0)
4245         continue;
4246
4247       if (rlist_len >= rlist_alloc) {
4248         rlist_alloc = rlist_alloc * 2 + 64;
4249         rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4250         my_assert_not(rlist, NULL);
4251       }
4252       rlist[rlist_len++] = strdup(words[0]);
4253     }
4254     skip_func = 0;
4255
4256     fclose(frlist);
4257     frlist = NULL;
4258   }
4259
4260   if (rlist_len > 0)
4261     qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4262
4263   fout = fopen(argv[arg_out], "w");
4264   my_assert_not(fout, NULL);
4265
4266   eq_alloc = 128;
4267   g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4268   my_assert_not(g_eqs, NULL);
4269
4270   for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4271     g_label_refs[i].i = -1;
4272     g_label_refs[i].next = NULL;
4273   }
4274
4275   while (fgets(line, sizeof(line), fasm))
4276   {
4277     wordc = 0;
4278     asmln++;
4279
4280     p = sskip(line);
4281     if (*p == 0)
4282       continue;
4283
4284     // get rid of random tabs
4285     for (i = 0; line[i] != 0; i++)
4286       if (line[i] == '\t')
4287         line[i] = ' ';
4288
4289     if (*p == ';')
4290     {
4291       if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4292         goto do_pending_endp; // eww..
4293
4294       if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4295       {
4296         static const char *attrs[] = {
4297           "bp-based frame",
4298           "library function",
4299           "static",
4300           "noreturn",
4301           "thunk",
4302           "fpd=",
4303         };
4304
4305         // parse IDA's attribute-list comment
4306         g_ida_func_attr = 0;
4307         p = sskip(p + 13);
4308
4309         for (; *p != 0; p = sskip(p)) {
4310           for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4311             if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4312               g_ida_func_attr |= 1 << i;
4313               p += strlen(attrs[i]);
4314               break;
4315             }
4316           }
4317           if (i == ARRAY_SIZE(attrs)) {
4318             anote("unparsed IDA attr: %s\n", p);
4319             break;
4320           }
4321           if (IS(attrs[i], "fpd=")) {
4322             p = next_word(words[0], sizeof(words[0]), p);
4323             // ignore for now..
4324           }
4325         }
4326       }
4327       else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4328       {
4329         p += 30;
4330         next_word(words[0], sizeof(words[0]), p);
4331         if (words[0][0] == 0)
4332           aerr("missing name for func chunk?\n");
4333
4334         if (!scanned_ahead) {
4335           add_func_chunk(fasm, words[0], asmln);
4336           func_chunks_sorted = 0;
4337         }
4338       }
4339       else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4340       {
4341         if (func_chunk_i >= 0) {
4342           if (func_chunk_i < func_chunk_cnt
4343             && IS(func_chunks[func_chunk_i].name, g_func))
4344           {
4345             // move on to next chunk
4346             ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4347             if (ret)
4348               aerr("seek failed for '%s' chunk #%d\n",
4349                 g_func, func_chunk_i);
4350             asmln = func_chunks[func_chunk_i].asmln;
4351             func_chunk_i++;
4352           }
4353           else {
4354             if (func_chunk_ret == 0)
4355               aerr("no return from chunk?\n");
4356             fseek(fasm, func_chunk_ret, SEEK_SET);
4357             asmln = func_chunk_ret_ln;
4358             func_chunk_ret = 0;
4359             pending_endp = 1;
4360           }
4361         }
4362       }
4363       else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4364         func_chunks_used = 1;
4365         p += 20;
4366         if (IS_START(g_func, "sub_")) {
4367           unsigned long addr = strtoul(p, NULL, 16);
4368           unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4369           if (addr > f_addr && !scanned_ahead) {
4370             anote("scan_ahead caused by '%s', addr %lx\n",
4371               g_func, addr);
4372             scan_ahead(fasm);
4373             scanned_ahead = 1;
4374             func_chunks_sorted = 0;
4375           }
4376         }
4377       }
4378       continue;
4379     } // *p == ';'
4380
4381 parse_words:
4382     for (i = wordc; i < ARRAY_SIZE(words); i++)
4383       words[i][0] = 0;
4384     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4385       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4386       if (*p == 0 || *p == ';') {
4387         wordc++;
4388         break;
4389       }
4390     }
4391     if (*p != 0 && *p != ';')
4392       aerr("too many words\n");
4393
4394     // alow asm patches in comments
4395     if (*p == ';' && IS_START(p, "; sctpatch:")) {
4396       p = sskip(p + 11);
4397       if (*p == 0 || *p == ';')
4398         continue;
4399       goto parse_words; // lame
4400     }
4401
4402     if (wordc == 0) {
4403       // shouldn't happen
4404       awarn("wordc == 0?\n");
4405       continue;
4406     }
4407
4408     // don't care about this:
4409     if (words[0][0] == '.'
4410         || IS(words[0], "include")
4411         || IS(words[0], "assume") || IS(words[1], "segment")
4412         || IS(words[0], "align"))
4413     {
4414       continue;
4415     }
4416
4417 do_pending_endp:
4418     // do delayed endp processing to collect switch jumptables
4419     if (pending_endp) {
4420       if (in_func && !skip_func && wordc >= 2
4421           && ((words[0][0] == 'd' && words[0][2] == 0)
4422               || (words[1][0] == 'd' && words[1][2] == 0)))
4423       {
4424         i = 1;
4425         if (words[1][0] == 'd' && words[1][2] == 0) {
4426           // label
4427           if (g_func_pd_cnt >= pd_alloc) {
4428             pd_alloc = pd_alloc * 2 + 16;
4429             g_func_pd = realloc(g_func_pd,
4430               sizeof(g_func_pd[0]) * pd_alloc);
4431             my_assert_not(g_func_pd, NULL);
4432           }
4433           pd = &g_func_pd[g_func_pd_cnt];
4434           g_func_pd_cnt++;
4435           memset(pd, 0, sizeof(*pd));
4436           strcpy(pd->label, words[0]);
4437           pd->type = OPT_CONST;
4438           pd->lmod = lmod_from_directive(words[1]);
4439           i = 2;
4440         }
4441         else {
4442           if (pd == NULL) {
4443             if (verbose)
4444               anote("skipping alignment byte?\n");
4445             continue;
4446           }
4447           lmod = lmod_from_directive(words[0]);
4448           if (lmod != pd->lmod)
4449             aerr("lmod change? %d->%d\n", pd->lmod, lmod);
4450         }
4451
4452         if (pd->count_alloc < pd->count + wordc) {
4453           pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
4454           pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
4455           my_assert_not(pd->d, NULL);
4456         }
4457         for (; i < wordc; i++) {
4458           if (IS(words[i], "offset")) {
4459             pd->type = OPT_OFFSET;
4460             i++;
4461           }
4462           p = strchr(words[i], ',');
4463           if (p != NULL)
4464             *p = 0;
4465           if (pd->type == OPT_OFFSET)
4466             pd->d[pd->count].u.label = strdup(words[i]);
4467           else
4468             pd->d[pd->count].u.val = parse_number(words[i]);
4469           pd->d[pd->count].bt_i = -1;
4470           pd->count++;
4471         }
4472         continue;
4473       }
4474
4475       if (in_func && !skip_func)
4476         gen_func(fout, g_fhdr, g_func, pi);
4477
4478       pending_endp = 0;
4479       in_func = 0;
4480       g_ida_func_attr = 0;
4481       skip_warned = 0;
4482       skip_func = 0;
4483       g_func[0] = 0;
4484       func_chunks_used = 0;
4485       func_chunk_i = -1;
4486       if (pi != 0) {
4487         memset(&ops, 0, pi * sizeof(ops[0]));
4488         memset(g_labels, 0, pi * sizeof(g_labels[0]));
4489         pi = 0;
4490       }
4491       g_eqcnt = 0;
4492       for (i = 0; i < g_func_pd_cnt; i++) {
4493         pd = &g_func_pd[i];
4494         if (pd->type == OPT_OFFSET) {
4495           for (j = 0; j < pd->count; j++)
4496             free(pd->d[j].u.label);
4497         }
4498         free(pd->d);
4499         pd->d = NULL;
4500       }
4501       g_func_pd_cnt = 0;
4502       pd = NULL;
4503       if (wordc == 0)
4504         continue;
4505     }
4506
4507     if (IS(words[1], "proc")) {
4508       if (in_func)
4509         aerr("proc '%s' while in_func '%s'?\n",
4510           words[0], g_func);
4511       p = words[0];
4512       if ((g_ida_func_attr & IDAFA_THUNK)
4513        || bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4514         skip_func = 1;
4515       strcpy(g_func, words[0]);
4516       set_label(0, words[0]);
4517       in_func = 1;
4518       continue;
4519     }
4520
4521     if (IS(words[1], "endp"))
4522     {
4523       if (!in_func)
4524         aerr("endp '%s' while not in_func?\n", words[0]);
4525       if (!IS(g_func, words[0]))
4526         aerr("endp '%s' while in_func '%s'?\n",
4527           words[0], g_func);
4528
4529       if (!skip_func && func_chunks_used) {
4530         // start processing chunks
4531         struct chunk_item *ci, key = { g_func, 0 };
4532
4533         func_chunk_ret = ftell(fasm);
4534         func_chunk_ret_ln = asmln;
4535         if (!func_chunks_sorted) {
4536           qsort(func_chunks, func_chunk_cnt,
4537             sizeof(func_chunks[0]), cmp_chunks);
4538           func_chunks_sorted = 1;
4539         }
4540         ci = bsearch(&key, func_chunks, func_chunk_cnt,
4541                sizeof(func_chunks[0]), cmp_chunks);
4542         if (ci == NULL)
4543           aerr("'%s' needs chunks, but none found\n", g_func);
4544         func_chunk_i = ci - func_chunks;
4545         for (; func_chunk_i > 0; func_chunk_i--)
4546           if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4547             break;
4548
4549         ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4550         if (ret)
4551           aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4552         asmln = func_chunks[func_chunk_i].asmln;
4553         func_chunk_i++;
4554         continue;
4555       }
4556       pending_endp = 1;
4557       continue;
4558     }
4559
4560     if (wordc == 2 && IS(words[1], "ends"))
4561       break;
4562
4563     p = strchr(words[0], ':');
4564     if (p != NULL) {
4565       set_label(pi, words[0]);
4566       continue;
4567     }
4568
4569     if (!in_func || skip_func) {
4570       if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4571         if (verbose)
4572           anote("skipping from '%s'\n", g_labels[pi]);
4573         skip_warned = 1;
4574       }
4575       g_labels[pi][0] = 0;
4576       continue;
4577     }
4578
4579     if (wordc > 1 && IS(words[1], "=")) {
4580       if (wordc != 5)
4581         aerr("unhandled equ, wc=%d\n", wordc);
4582       if (g_eqcnt >= eq_alloc) {
4583         eq_alloc *= 2;
4584         g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4585         my_assert_not(g_eqs, NULL);
4586       }
4587
4588       len = strlen(words[0]);
4589       if (len > sizeof(g_eqs[0].name) - 1)
4590         aerr("equ name too long: %d\n", len);
4591       strcpy(g_eqs[g_eqcnt].name, words[0]);
4592
4593       if (!IS(words[3], "ptr"))
4594         aerr("unhandled equ\n");
4595       if (IS(words[2], "dword"))
4596         g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4597       else if (IS(words[2], "word"))
4598         g_eqs[g_eqcnt].lmod = OPLM_WORD;
4599       else if (IS(words[2], "byte"))
4600         g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4601       else
4602         aerr("bad lmod: '%s'\n", words[2]);
4603
4604       g_eqs[g_eqcnt].offset = parse_number(words[4]);
4605       g_eqcnt++;
4606       continue;
4607     }
4608
4609     if (pi >= ARRAY_SIZE(ops))
4610       aerr("too many ops\n");
4611
4612     parse_op(&ops[pi], words, wordc);
4613     pi++;
4614   }
4615
4616   fclose(fout);
4617   fclose(fasm);
4618   fclose(g_fhdr);
4619
4620   return 0;
4621 }
4622
4623 // vim:ts=2:shiftwidth=2:expandtab