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