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