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