translate: handle more push/pop pair cases
[ia32rtools.git] / tools / translate.c
1 /*
2  * ia32rtools
3  * (C) notaz, 2013-2015
4  *
5  * This work is licensed under the terms of 3-clause BSD license.
6  * See COPYING file in the top-level directory.
7  */
8
9 #define _GNU_SOURCE
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13
14 #include "my_assert.h"
15 #include "my_str.h"
16
17 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
18 #define IS(w, y) !strcmp(w, y)
19 #define IS_START(w, y) !strncmp(w, y, strlen(y))
20
21 #include "protoparse.h"
22
23 static const char *asmfn;
24 static int asmln;
25 static FILE *g_fhdr;
26
27 #define anote(fmt, ...) \
28         printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
29 #define awarn(fmt, ...) \
30         printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
31 #define aerr(fmt, ...) do { \
32         printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
33   fcloseall(); \
34         exit(1); \
35 } while (0)
36
37 #include "masm_tools.h"
38
39 enum op_flags {
40   OPF_RMD    = (1 << 0), /* removed from code generation */
41   OPF_DATA   = (1 << 1), /* data processing - writes to dst opr */
42   OPF_FLAGS  = (1 << 2), /* sets flags */
43   OPF_JMP    = (1 << 3), /* branch, call */
44   OPF_CJMP   = (1 << 4), /* cond. branch (cc or jecxz) */
45   OPF_CC     = (1 << 5), /* uses flags */
46   OPF_TAIL   = (1 << 6), /* ret or tail call */
47   OPF_RSAVE  = (1 << 7), /* push/pop is local reg save/load */
48   OPF_REP    = (1 << 8), /* prefixed by rep */
49   OPF_REPZ   = (1 << 9), /* rep is repe/repz */
50   OPF_REPNZ  = (1 << 10), /* rep is repne/repnz */
51   OPF_FARG   = (1 << 11), /* push collected as func arg */
52   OPF_FARGNR = (1 << 12), /* push collected as func arg (no reuse) */
53   OPF_EBP_S  = (1 << 13), /* ebp used as scratch here, not BP */
54   OPF_DF     = (1 << 14), /* DF flag set */
55   OPF_ATAIL  = (1 << 15), /* tail call with reused arg frame */
56   OPF_32BIT  = (1 << 16), /* 32bit division */
57   OPF_LOCK   = (1 << 17), /* op has lock prefix */
58   OPF_VAPUSH = (1 << 18), /* vararg ptr push (as call arg) */
59   OPF_DONE   = (1 << 19), /* already fully handled by analysis */
60   OPF_PPUSH  = (1 << 20), /* part of complex push-pop graph */
61 };
62
63 enum op_op {
64         OP_INVAL,
65         OP_NOP,
66         OP_PUSH,
67         OP_POP,
68         OP_LEAVE,
69         OP_MOV,
70         OP_LEA,
71         OP_MOVZX,
72         OP_MOVSX,
73         OP_XCHG,
74         OP_NOT,
75         OP_CDQ,
76         OP_LODS,
77         OP_STOS,
78         OP_MOVS,
79         OP_CMPS,
80         OP_SCAS,
81         OP_STD,
82         OP_CLD,
83         OP_RET,
84         OP_ADD,
85         OP_SUB,
86         OP_AND,
87         OP_OR,
88         OP_XOR,
89         OP_SHL,
90         OP_SHR,
91         OP_SAR,
92         OP_SHRD,
93         OP_ROL,
94         OP_ROR,
95         OP_RCL,
96         OP_RCR,
97         OP_ADC,
98         OP_SBB,
99         OP_BSF,
100         OP_INC,
101         OP_DEC,
102         OP_NEG,
103         OP_MUL,
104         OP_IMUL,
105         OP_DIV,
106         OP_IDIV,
107         OP_TEST,
108         OP_CMP,
109         OP_CALL,
110         OP_JMP,
111         OP_JECXZ,
112         OP_JCC,
113         OP_SCC,
114         // x87
115         // mmx
116         OP_EMMS,
117         // undefined
118         OP_UD2,
119 };
120
121 enum opr_type {
122   OPT_UNSPEC,
123   OPT_REG,
124   OPT_REGMEM,
125   OPT_LABEL,
126   OPT_OFFSET,
127   OPT_CONST,
128 };
129
130 // must be sorted (larger len must be further in enum)
131 enum opr_lenmod {
132         OPLM_UNSPEC,
133         OPLM_BYTE,
134         OPLM_WORD,
135         OPLM_DWORD,
136         OPLM_QWORD,
137 };
138
139 #define MAX_OPERANDS 3
140 #define NAMELEN 112
141
142 struct parsed_opr {
143   enum opr_type type;
144   enum opr_lenmod lmod;
145   unsigned int is_ptr:1;   // pointer in C
146   unsigned int is_array:1; // array in C
147   unsigned int type_from_var:1; // .. in header, sometimes wrong
148   unsigned int size_mismatch:1; // type override differs from C
149   unsigned int size_lt:1;  // type override is larger than C
150   unsigned int had_ds:1;   // had ds: prefix
151   const struct parsed_proto *pp; // for OPT_LABEL
152   int reg;
153   unsigned int val;
154   char name[NAMELEN];
155 };
156
157 struct parsed_op {
158   enum op_op op;
159   struct parsed_opr operand[MAX_OPERANDS];
160   unsigned int flags;
161   unsigned char pfo;
162   unsigned char pfo_inv;
163   unsigned char operand_cnt;
164   unsigned char p_argnum; // arg push: altered before call arg #
165   unsigned char p_arggrp; // arg push: arg group # for above
166   unsigned char p_argpass;// arg push: arg of host func
167   short         p_argnext;// arg push: same arg pushed elsewhere or -1
168   int regmask_src;        // all referensed regs
169   int regmask_dst;
170   int pfomask;            // flagop: parsed_flag_op that can't be delayed
171   int cc_scratch;         // scratch storage during analysis
172   int bt_i;               // branch target for branches
173   struct parsed_data *btj;// branch targets for jumptables
174   struct parsed_proto *pp;// parsed_proto for OP_CALL
175   void *datap;
176   int asmln;
177 };
178
179 // datap:
180 // OP_CALL  - parser proto hint (str)
181 // (OPF_CC) - points to one of (OPF_FLAGS) that affects cc op
182 // OP_PUSH  - points to OP_POP in complex push/pop graph
183 // OP_POP   - points to OP_PUSH in simple push/pop pair
184
185 struct parsed_equ {
186   char name[64];
187   enum opr_lenmod lmod;
188   int offset;
189 };
190
191 struct parsed_data {
192   char label[256];
193   enum opr_type type;
194   enum opr_lenmod lmod;
195   int count;
196   int count_alloc;
197   struct {
198     union {
199       char *label;
200       unsigned int val;
201     } u;
202     int bt_i;
203   } *d;
204 };
205
206 struct label_ref {
207   int i;
208   struct label_ref *next;
209 };
210
211 enum ida_func_attr {
212   IDAFA_BP_FRAME = (1 << 0),
213   IDAFA_LIB_FUNC = (1 << 1),
214   IDAFA_STATIC   = (1 << 2),
215   IDAFA_NORETURN = (1 << 3),
216   IDAFA_THUNK    = (1 << 4),
217   IDAFA_FPD      = (1 << 5),
218 };
219
220 // note: limited to 32k due to p_argnext
221 #define MAX_OPS     4096
222 #define MAX_ARG_GRP 2
223
224 static struct parsed_op ops[MAX_OPS];
225 static struct parsed_equ *g_eqs;
226 static int g_eqcnt;
227 static char *g_labels[MAX_OPS];
228 static struct label_ref g_label_refs[MAX_OPS];
229 static const struct parsed_proto *g_func_pp;
230 static struct parsed_data *g_func_pd;
231 static int g_func_pd_cnt;
232 static char g_func[256];
233 static char g_comment[256];
234 static int g_bp_frame;
235 static int g_sp_frame;
236 static int g_stack_frame_used;
237 static int g_stack_fsz;
238 static int g_ida_func_attr;
239 static int g_skip_func;
240 static int g_allow_regfunc;
241 static int g_quiet_pp;
242 static int g_header_mode;
243
244 #define ferr(op_, fmt, ...) do { \
245   printf("%s:%d: error: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
246     dump_op(op_), ##__VA_ARGS__); \
247   fcloseall(); \
248   exit(1); \
249 } while (0)
250 #define fnote(op_, fmt, ...) \
251   printf("%s:%d: note: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
252     dump_op(op_), ##__VA_ARGS__)
253
254 #define ferr_assert(op_, cond) do { \
255   if (!(cond)) ferr(op_, "assertion '%s' failed on ln :%d\n", #cond, \
256                     __LINE__); \
257 } while (0)
258
259 const char *regs_r32[] = {
260   "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp",
261   // not r32, but list here for easy parsing and printing
262   "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
263 };
264 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
265 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
266 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
267
268 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
269
270 // possible basic comparison types (without inversion)
271 enum parsed_flag_op {
272   PFO_O,  // 0 OF=1
273   PFO_C,  // 2 CF=1
274   PFO_Z,  // 4 ZF=1
275   PFO_BE, // 6 CF=1||ZF=1
276   PFO_S,  // 8 SF=1
277   PFO_P,  // a PF=1
278   PFO_L,  // c SF!=OF
279   PFO_LE, // e ZF=1||SF!=OF
280 };
281
282 #define PFOB_O   (1 << PFO_O)
283 #define PFOB_C   (1 << PFO_C)
284 #define PFOB_Z   (1 << PFO_Z)
285 #define PFOB_S   (1 << PFO_S)
286
287 static const char *parsed_flag_op_names[] = {
288   "o", "c", "z", "be", "s", "p", "l", "le"
289 };
290
291 static int char_array_i(const char *array[], size_t len, const char *s)
292 {
293   int i;
294
295   for (i = 0; i < len; i++)
296     if (IS(s, array[i]))
297       return i;
298
299   return -1;
300 }
301
302 static void printf_number(char *buf, size_t buf_size,
303   unsigned long number)
304 {
305   // output in C-friendly form
306   snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
307 }
308
309 static int check_segment_prefix(const char *s)
310 {
311   if (s[0] == 0 || s[1] != 's' || s[2] != ':')
312     return 0;
313
314   switch (s[0]) {
315   case 'c': return 1;
316   case 'd': return 2;
317   case 's': return 3;
318   case 'e': return 4;
319   case 'f': return 5;
320   case 'g': return 6;
321   default:  return 0;
322   }
323 }
324
325 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
326 {
327   int reg;
328
329   reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
330   if (reg >= 8) {
331     *reg_lmod = OPLM_QWORD;
332     return reg;
333   }
334   if (reg >= 0) {
335     *reg_lmod = OPLM_DWORD;
336     return reg;
337   }
338   reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
339   if (reg >= 0) {
340     *reg_lmod = OPLM_WORD;
341     return reg;
342   }
343   reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
344   if (reg >= 0) {
345     *reg_lmod = OPLM_BYTE;
346     return reg;
347   }
348   reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
349   if (reg >= 0) {
350     *reg_lmod = OPLM_BYTE;
351     return reg;
352   }
353
354   return -1;
355 }
356
357 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
358 {
359   enum opr_lenmod lmod;
360   char cvtbuf[256];
361   char *d = cvtbuf;
362   char *s = name;
363   char w[64];
364   long number;
365   int reg;
366   int c = 0;
367
368   *d = 0;
369
370   while (*s != 0) {
371     d += strlen(d);
372     while (my_isblank(*s))
373       s++;
374     for (; my_issep(*s); d++, s++)
375       *d = *s;
376     while (my_isblank(*s))
377       s++;
378     *d = 0;
379
380     // skip '?s:' prefixes
381     if (check_segment_prefix(s))
382       s += 3;
383
384     s = next_idt(w, sizeof(w), s);
385     if (w[0] == 0)
386       break;
387     c++;
388
389     reg = parse_reg(&lmod, w);
390     if (reg >= 0) {
391       *regmask |= 1 << reg;
392       goto pass;
393     }
394
395     if ('0' <= w[0] && w[0] <= '9') {
396       number = parse_number(w);
397       printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
398       continue;
399     }
400
401     // probably some label/identifier - pass
402
403 pass:
404     snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
405   }
406
407   if (need_c_cvt)
408     strcpy(name, cvtbuf);
409
410   return c;
411 }
412
413 static int is_reg_in_str(const char *s)
414 {
415   int i;
416
417   if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
418     return 0;
419
420   for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
421     if (!strncmp(s, regs_r32[i], 3))
422       return 1;
423
424   return 0;
425 }
426
427 static const char *parse_stack_el(const char *name, char *extra_reg,
428   int early_try)
429 {
430   const char *p, *p2, *s;
431   char *endp = NULL;
432   char buf[32];
433   long val;
434   int len;
435
436   if (g_bp_frame || early_try)
437   {
438     p = name;
439     if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
440       p += 4;
441       if (extra_reg != NULL) {
442         strncpy(extra_reg, name, 3);
443         extra_reg[4] = 0;
444       }
445     }
446
447     if (IS_START(p, "ebp+")) {
448       p += 4;
449
450       p2 = strchr(p, '+');
451       if (p2 != NULL && is_reg_in_str(p)) {
452         if (extra_reg != NULL) {
453           strncpy(extra_reg, p, p2 - p);
454           extra_reg[p2 - p] = 0;
455         }
456         p = p2 + 1;
457       }
458
459       if (!('0' <= *p && *p <= '9'))
460         return p;
461
462       return NULL;
463     }
464   }
465
466   if (!IS_START(name, "esp+"))
467     return NULL;
468
469   s = name + 4;
470   p = strchr(s, '+');
471   if (p) {
472     if (is_reg_in_str(s)) {
473       if (extra_reg != NULL) {
474         strncpy(extra_reg, s, p - s);
475         extra_reg[p - s] = 0;
476       }
477       s = p + 1;
478       p = strchr(s, '+');
479       if (p == NULL)
480         aerr("%s IDA stackvar not set?\n", __func__);
481     }
482     if (!('0' <= *s && *s <= '9')) {
483       aerr("%s IDA stackvar offset not set?\n", __func__);
484       return NULL;
485     }
486     if (s[0] == '0' && s[1] == 'x')
487       s += 2;
488     len = p - s;
489     if (len < sizeof(buf) - 1) {
490       strncpy(buf, s, len);
491       buf[len] = 0;
492       val = strtol(buf, &endp, 16);
493       if (val == 0 || *endp != 0) {
494         aerr("%s num parse fail for '%s'\n", __func__, buf);
495         return NULL;
496       }
497     }
498     p++;
499   }
500   else
501     p = name + 4;
502
503   if ('0' <= *p && *p <= '9')
504     return NULL;
505
506   return p;
507 }
508
509 static int guess_lmod_from_name(struct parsed_opr *opr)
510 {
511   if (!strncmp(opr->name, "dword_", 6)) {
512     opr->lmod = OPLM_DWORD;
513     return 1;
514   }
515   if (!strncmp(opr->name, "word_", 5)) {
516     opr->lmod = OPLM_WORD;
517     return 1;
518   }
519   if (!strncmp(opr->name, "byte_", 5)) {
520     opr->lmod = OPLM_BYTE;
521     return 1;
522   }
523   if (!strncmp(opr->name, "qword_", 6)) {
524     opr->lmod = OPLM_QWORD;
525     return 1;
526   }
527   return 0;
528 }
529
530 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
531   const struct parsed_type *c_type)
532 {
533   static const char *dword_types[] = {
534     "uint32_t", "int", "_DWORD", "UINT_PTR", "DWORD",
535     "WPARAM", "LPARAM", "UINT", "__int32",
536     "LONG", "HIMC", "BOOL", "size_t",
537     "float",
538   };
539   static const char *word_types[] = {
540     "uint16_t", "int16_t", "_WORD", "WORD",
541     "unsigned __int16", "__int16",
542   };
543   static const char *byte_types[] = {
544     "uint8_t", "int8_t", "char",
545     "unsigned __int8", "__int8", "BYTE", "_BYTE",
546     "CHAR", "_UNKNOWN",
547     // structures.. deal the same as with _UNKNOWN for now
548     "CRITICAL_SECTION",
549   };
550   const char *n;
551   int i;
552
553   if (c_type->is_ptr) {
554     *lmod = OPLM_DWORD;
555     return 1;
556   }
557
558   n = skip_type_mod(c_type->name);
559
560   for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
561     if (IS(n, dword_types[i])) {
562       *lmod = OPLM_DWORD;
563       return 1;
564     }
565   }
566
567   for (i = 0; i < ARRAY_SIZE(word_types); i++) {
568     if (IS(n, word_types[i])) {
569       *lmod = OPLM_WORD;
570       return 1;
571     }
572   }
573
574   for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
575     if (IS(n, byte_types[i])) {
576       *lmod = OPLM_BYTE;
577       return 1;
578     }
579   }
580
581   return 0;
582 }
583
584 static char *default_cast_to(char *buf, size_t buf_size,
585   struct parsed_opr *opr)
586 {
587   buf[0] = 0;
588
589   if (!opr->is_ptr)
590     return buf;
591   if (opr->pp == NULL || opr->pp->type.name == NULL
592     || opr->pp->is_fptr)
593   {
594     snprintf(buf, buf_size, "%s", "(void *)");
595     return buf;
596   }
597
598   snprintf(buf, buf_size, "(%s)", opr->pp->type.name);
599   return buf;
600 }
601
602 static enum opr_type lmod_from_directive(const char *d)
603 {
604   if (IS(d, "dd"))
605     return OPLM_DWORD;
606   else if (IS(d, "dw"))
607     return OPLM_WORD;
608   else if (IS(d, "db"))
609     return OPLM_BYTE;
610
611   aerr("unhandled directive: '%s'\n", d);
612   return OPLM_UNSPEC;
613 }
614
615 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
616   int *regmask)
617 {
618   opr->type = OPT_REG;
619   opr->reg = reg;
620   opr->lmod = lmod;
621   *regmask |= 1 << reg;
622 }
623
624 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
625   int *extra_offs);
626
627 static int parse_operand(struct parsed_opr *opr,
628   int *regmask, int *regmask_indirect,
629   char words[16][256], int wordc, int w, unsigned int op_flags)
630 {
631   const struct parsed_proto *pp = NULL;
632   enum opr_lenmod tmplmod;
633   unsigned long number;
634   char buf[256];
635   int ret, len;
636   int wordc_in;
637   char *p;
638   int i;
639
640   if (w >= wordc)
641     aerr("parse_operand w %d, wordc %d\n", w, wordc);
642
643   opr->reg = xUNSPEC;
644
645   for (i = w; i < wordc; i++) {
646     len = strlen(words[i]);
647     if (words[i][len - 1] == ',') {
648       words[i][len - 1] = 0;
649       wordc = i + 1;
650       break;
651     }
652   }
653
654   wordc_in = wordc - w;
655
656   if ((op_flags & OPF_JMP) && wordc_in > 0
657       && !('0' <= words[w][0] && words[w][0] <= '9'))
658   {
659     const char *label = NULL;
660
661     if (wordc_in == 3 && !strncmp(words[w], "near", 4)
662      && IS(words[w + 1], "ptr"))
663       label = words[w + 2];
664     else if (wordc_in == 2 && IS(words[w], "short"))
665       label = words[w + 1];
666     else if (wordc_in == 1
667           && strchr(words[w], '[') == NULL
668           && parse_reg(&tmplmod, words[w]) < 0)
669       label = words[w];
670
671     if (label != NULL) {
672       opr->type = OPT_LABEL;
673       ret = check_segment_prefix(label);
674       if (ret != 0) {
675         if (ret >= 5)
676           aerr("fs/gs used\n");
677         opr->had_ds = 1;
678         label += 3;
679       }
680       strcpy(opr->name, label);
681       return wordc;
682     }
683   }
684
685   if (wordc_in >= 3) {
686     if (IS(words[w + 1], "ptr")) {
687       if (IS(words[w], "dword"))
688         opr->lmod = OPLM_DWORD;
689       else if (IS(words[w], "word"))
690         opr->lmod = OPLM_WORD;
691       else if (IS(words[w], "byte"))
692         opr->lmod = OPLM_BYTE;
693       else if (IS(words[w], "qword"))
694         opr->lmod = OPLM_QWORD;
695       else
696         aerr("type parsing failed\n");
697       w += 2;
698       wordc_in = wordc - w;
699     }
700   }
701
702   if (wordc_in == 2) {
703     if (IS(words[w], "offset")) {
704       opr->type = OPT_OFFSET;
705       opr->lmod = OPLM_DWORD;
706       strcpy(opr->name, words[w + 1]);
707       pp = proto_parse(g_fhdr, opr->name, 1);
708       goto do_label;
709     }
710     if (IS(words[w], "(offset")) {
711       p = strchr(words[w + 1], ')');
712       if (p == NULL)
713         aerr("parse of bracketed offset failed\n");
714       *p = 0;
715       opr->type = OPT_OFFSET;
716       strcpy(opr->name, words[w + 1]);
717       return wordc;
718     }
719   }
720
721   if (wordc_in != 1)
722     aerr("parse_operand 1 word expected\n");
723
724   ret = check_segment_prefix(words[w]);
725   if (ret != 0) {
726     if (ret >= 5)
727       aerr("fs/gs used\n");
728     opr->had_ds = 1;
729     memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
730   }
731   strcpy(opr->name, words[w]);
732
733   if (words[w][0] == '[') {
734     opr->type = OPT_REGMEM;
735     ret = sscanf(words[w], "[%[^]]]", opr->name);
736     if (ret != 1)
737       aerr("[] parse failure\n");
738
739     parse_indmode(opr->name, regmask_indirect, 1);
740     if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL, 1))
741     {
742       // might be an equ
743       struct parsed_equ *eq =
744         equ_find(NULL, parse_stack_el(opr->name, NULL, 1), &i);
745       if (eq)
746         opr->lmod = eq->lmod;
747     }
748     return wordc;
749   }
750   else if (strchr(words[w], '[')) {
751     // label[reg] form
752     p = strchr(words[w], '[');
753     opr->type = OPT_REGMEM;
754     parse_indmode(p, regmask_indirect, 0);
755     strncpy(buf, words[w], p - words[w]);
756     buf[p - words[w]] = 0;
757     pp = proto_parse(g_fhdr, buf, 1);
758     goto do_label;
759   }
760   else if (('0' <= words[w][0] && words[w][0] <= '9')
761     || words[w][0] == '-')
762   {
763     number = parse_number(words[w]);
764     opr->type = OPT_CONST;
765     opr->val = number;
766     printf_number(opr->name, sizeof(opr->name), number);
767     return wordc;
768   }
769
770   ret = parse_reg(&tmplmod, opr->name);
771   if (ret >= 0) {
772     setup_reg_opr(opr, ret, tmplmod, regmask);
773     return wordc;
774   }
775
776   // most likely var in data segment
777   opr->type = OPT_LABEL;
778   pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
779
780 do_label:
781   if (pp != NULL) {
782     if (pp->is_fptr || pp->is_func) {
783       opr->lmod = OPLM_DWORD;
784       opr->is_ptr = 1;
785     }
786     else {
787       tmplmod = OPLM_UNSPEC;
788       if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
789         anote("unhandled C type '%s' for '%s'\n",
790           pp->type.name, opr->name);
791       
792       if (opr->lmod == OPLM_UNSPEC) {
793         opr->lmod = tmplmod;
794         opr->type_from_var = 1;
795       }
796       else if (opr->lmod != tmplmod) {
797         opr->size_mismatch = 1;
798         if (tmplmod < opr->lmod)
799           opr->size_lt = 1;
800       }
801       opr->is_ptr = pp->type.is_ptr;
802     }
803     opr->is_array = pp->type.is_array;
804   }
805   opr->pp = pp;
806
807   if (opr->lmod == OPLM_UNSPEC)
808     guess_lmod_from_name(opr);
809   return wordc;
810 }
811
812 static const struct {
813   const char *name;
814   unsigned int flags;
815 } pref_table[] = {
816   { "rep",    OPF_REP },
817   { "repe",   OPF_REP|OPF_REPZ },
818   { "repz",   OPF_REP|OPF_REPZ },
819   { "repne",  OPF_REP|OPF_REPNZ },
820   { "repnz",  OPF_REP|OPF_REPNZ },
821   { "lock",   OPF_LOCK }, // ignored for now..
822 };
823
824 #define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
825
826 static const struct {
827   const char *name;
828   enum op_op op;
829   unsigned short minopr;
830   unsigned short maxopr;
831   unsigned int flags;
832   unsigned char pfo;
833   unsigned char pfo_inv;
834 } op_table[] = {
835   { "nop",  OP_NOP,    0, 0, 0 },
836   { "push", OP_PUSH,   1, 1, 0 },
837   { "pop",  OP_POP,    1, 1, OPF_DATA },
838   { "leave",OP_LEAVE,  0, 0, OPF_DATA },
839   { "mov" , OP_MOV,    2, 2, OPF_DATA },
840   { "lea",  OP_LEA,    2, 2, OPF_DATA },
841   { "movzx",OP_MOVZX,  2, 2, OPF_DATA },
842   { "movsx",OP_MOVSX,  2, 2, OPF_DATA },
843   { "xchg", OP_XCHG,   2, 2, OPF_DATA },
844   { "not",  OP_NOT,    1, 1, OPF_DATA },
845   { "cdq",  OP_CDQ,    0, 0, OPF_DATA },
846   { "lodsb",OP_LODS,   0, 0, OPF_DATA },
847   { "lodsw",OP_LODS,   0, 0, OPF_DATA },
848   { "lodsd",OP_LODS,   0, 0, OPF_DATA },
849   { "stosb",OP_STOS,   0, 0, OPF_DATA },
850   { "stosw",OP_STOS,   0, 0, OPF_DATA },
851   { "stosd",OP_STOS,   0, 0, OPF_DATA },
852   { "movsb",OP_MOVS,   0, 0, OPF_DATA },
853   { "movsw",OP_MOVS,   0, 0, OPF_DATA },
854   { "movsd",OP_MOVS,   0, 0, OPF_DATA },
855   { "cmpsb",OP_CMPS,   0, 0, OPF_DATA|OPF_FLAGS },
856   { "cmpsw",OP_CMPS,   0, 0, OPF_DATA|OPF_FLAGS },
857   { "cmpsd",OP_CMPS,   0, 0, OPF_DATA|OPF_FLAGS },
858   { "scasb",OP_SCAS,   0, 0, OPF_DATA|OPF_FLAGS },
859   { "scasw",OP_SCAS,   0, 0, OPF_DATA|OPF_FLAGS },
860   { "scasd",OP_SCAS,   0, 0, OPF_DATA|OPF_FLAGS },
861   { "std",  OP_STD,    0, 0, OPF_DATA }, // special flag
862   { "cld",  OP_CLD,    0, 0, OPF_DATA },
863   { "add",  OP_ADD,    2, 2, OPF_DATA|OPF_FLAGS },
864   { "sub",  OP_SUB,    2, 2, OPF_DATA|OPF_FLAGS },
865   { "and",  OP_AND,    2, 2, OPF_DATA|OPF_FLAGS },
866   { "or",   OP_OR,     2, 2, OPF_DATA|OPF_FLAGS },
867   { "xor",  OP_XOR,    2, 2, OPF_DATA|OPF_FLAGS },
868   { "shl",  OP_SHL,    2, 2, OPF_DATA|OPF_FLAGS },
869   { "shr",  OP_SHR,    2, 2, OPF_DATA|OPF_FLAGS },
870   { "sal",  OP_SHL,    2, 2, OPF_DATA|OPF_FLAGS },
871   { "sar",  OP_SAR,    2, 2, OPF_DATA|OPF_FLAGS },
872   { "shrd", OP_SHRD,   3, 3, OPF_DATA|OPF_FLAGS },
873   { "rol",  OP_ROL,    2, 2, OPF_DATA|OPF_FLAGS },
874   { "ror",  OP_ROR,    2, 2, OPF_DATA|OPF_FLAGS },
875   { "rcl",  OP_RCL,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
876   { "rcr",  OP_RCR,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
877   { "adc",  OP_ADC,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
878   { "sbb",  OP_SBB,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
879   { "bsf",  OP_BSF,    2, 2, OPF_DATA|OPF_FLAGS },
880   { "inc",  OP_INC,    1, 1, OPF_DATA|OPF_FLAGS },
881   { "dec",  OP_DEC,    1, 1, OPF_DATA|OPF_FLAGS },
882   { "neg",  OP_NEG,    1, 1, OPF_DATA|OPF_FLAGS },
883   { "mul",  OP_MUL,    1, 1, OPF_DATA|OPF_FLAGS },
884   { "imul", OP_IMUL,   1, 3, OPF_DATA|OPF_FLAGS },
885   { "div",  OP_DIV,    1, 1, OPF_DATA|OPF_FLAGS },
886   { "idiv", OP_IDIV,   1, 1, OPF_DATA|OPF_FLAGS },
887   { "test", OP_TEST,   2, 2, OPF_FLAGS },
888   { "cmp",  OP_CMP,    2, 2, OPF_FLAGS },
889   { "retn", OP_RET,    0, 1, OPF_TAIL },
890   { "call", OP_CALL,   1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
891   { "jmp",  OP_JMP,    1, 1, OPF_JMP },
892   { "jecxz",OP_JECXZ,  1, 1, OPF_JMP|OPF_CJMP },
893   { "jo",   OP_JCC,    1, 1, OPF_CJMP_CC, PFO_O,  0 }, // 70 OF=1
894   { "jno",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_O,  1 }, // 71 OF=0
895   { "jc",   OP_JCC,    1, 1, OPF_CJMP_CC, PFO_C,  0 }, // 72 CF=1
896   { "jb",   OP_JCC,    1, 1, OPF_CJMP_CC, PFO_C,  0 }, // 72
897   { "jnc",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_C,  1 }, // 73 CF=0
898   { "jnb",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_C,  1 }, // 73
899   { "jae",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_C,  1 }, // 73
900   { "jz",   OP_JCC,    1, 1, OPF_CJMP_CC, PFO_Z,  0 }, // 74 ZF=1
901   { "je",   OP_JCC,    1, 1, OPF_CJMP_CC, PFO_Z,  0 }, // 74
902   { "jnz",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_Z,  1 }, // 75 ZF=0
903   { "jne",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_Z,  1 }, // 75
904   { "jbe",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76 CF=1||ZF=1
905   { "jna",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76
906   { "ja",   OP_JCC,    1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77 CF=0&&ZF=0
907   { "jnbe", OP_JCC,    1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77
908   { "js",   OP_JCC,    1, 1, OPF_CJMP_CC, PFO_S,  0 }, // 78 SF=1
909   { "jns",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_S,  1 }, // 79 SF=0
910   { "jp",   OP_JCC,    1, 1, OPF_CJMP_CC, PFO_P,  0 }, // 7a PF=1
911   { "jpe",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_P,  0 }, // 7a
912   { "jnp",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_P,  1 }, // 7b PF=0
913   { "jpo",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_P,  1 }, // 7b
914   { "jl",   OP_JCC,    1, 1, OPF_CJMP_CC, PFO_L,  0 }, // 7c SF!=OF
915   { "jnge", OP_JCC,    1, 1, OPF_CJMP_CC, PFO_L,  0 }, // 7c
916   { "jge",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_L,  1 }, // 7d SF=OF
917   { "jnl",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_L,  1 }, // 7d
918   { "jle",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e ZF=1||SF!=OF
919   { "jng",  OP_JCC,    1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e
920   { "jg",   OP_JCC,    1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f ZF=0&&SF=OF
921   { "jnle", OP_JCC,    1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f
922   { "seto",   OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_O,  0 },
923   { "setno",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_O,  1 },
924   { "setc",   OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_C,  0 },
925   { "setb",   OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_C,  0 },
926   { "setnc",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_C,  1 },
927   { "setae",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_C,  1 },
928   { "setnb",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_C,  1 },
929   { "setz",   OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_Z,  0 },
930   { "sete",   OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_Z,  0 },
931   { "setnz",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_Z,  1 },
932   { "setne",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_Z,  1 },
933   { "setbe",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
934   { "setna",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
935   { "seta",   OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
936   { "setnbe", OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
937   { "sets",   OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_S,  0 },
938   { "setns",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_S,  1 },
939   { "setp",   OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_P,  0 },
940   { "setpe",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_P,  0 },
941   { "setnp",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_P,  1 },
942   { "setpo",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_P,  1 },
943   { "setl",   OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_L,  0 },
944   { "setnge", OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_L,  0 },
945   { "setge",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_L,  1 },
946   { "setnl",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_L,  1 },
947   { "setle",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
948   { "setng",  OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
949   { "setg",   OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
950   { "setnle", OP_SCC,  1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
951   // x87
952   // mmx
953   { "emms",   OP_EMMS, 0, 0, OPF_DATA },
954   { "movq",   OP_MOV,  2, 2, OPF_DATA },
955   // must be last
956   { "ud2",    OP_UD2 },
957 };
958
959 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
960 {
961   enum opr_lenmod lmod = OPLM_UNSPEC;
962   int prefix_flags = 0;
963   int regmask_ind;
964   int regmask;
965   int op_w = 0;
966   int opr = 0;
967   int w = 0;
968   int i;
969
970   for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
971     if (IS(words[w], pref_table[i].name)) {
972       prefix_flags = pref_table[i].flags;
973       break;
974     }
975   }
976
977   if (prefix_flags) {
978     if (wordc <= 1)
979       aerr("lone prefix: '%s'\n", words[0]);
980     w++;
981   }
982
983   op_w = w;
984   for (i = 0; i < ARRAY_SIZE(op_table); i++) {
985     if (IS(words[w], op_table[i].name))
986       break;
987   }
988
989   if (i == ARRAY_SIZE(op_table)) {
990     if (!g_skip_func)
991       aerr("unhandled op: '%s'\n", words[0]);
992     i--; // OP_UD2
993   }
994   w++;
995
996   op->op = op_table[i].op;
997   op->flags = op_table[i].flags | prefix_flags;
998   op->pfo = op_table[i].pfo;
999   op->pfo_inv = op_table[i].pfo_inv;
1000   op->regmask_src = op->regmask_dst = 0;
1001   op->asmln = asmln;
1002
1003   if (op->op == OP_UD2)
1004     return;
1005
1006   for (opr = 0; opr < op_table[i].maxopr; opr++) {
1007     if (opr >= op_table[i].minopr && w >= wordc)
1008       break;
1009
1010     regmask = regmask_ind = 0;
1011     w = parse_operand(&op->operand[opr], &regmask, &regmask_ind,
1012       words, wordc, w, op->flags);
1013
1014     if (opr == 0 && (op->flags & OPF_DATA))
1015       op->regmask_dst = regmask;
1016     else
1017       op->regmask_src |= regmask;
1018     op->regmask_src |= regmask_ind;
1019   }
1020
1021   if (w < wordc)
1022     aerr("parse_op %s incomplete: %d/%d\n",
1023       words[0], w, wordc);
1024
1025   // special cases
1026   op->operand_cnt = opr;
1027   if (!strncmp(op_table[i].name, "set", 3))
1028     op->operand[0].lmod = OPLM_BYTE;
1029
1030   switch (op->op) {
1031   // first operand is not dst
1032   case OP_CMP:
1033   case OP_TEST:
1034     op->regmask_src |= op->regmask_dst;
1035     op->regmask_dst = 0;
1036     break;
1037
1038   // first operand is src too
1039   case OP_NOT:
1040   case OP_ADD:
1041   case OP_AND:
1042   case OP_OR:
1043   case OP_RCL:
1044   case OP_RCR:
1045   case OP_ADC:
1046   case OP_INC:
1047   case OP_DEC:
1048   case OP_NEG:
1049   // more below..
1050     op->regmask_src |= op->regmask_dst;
1051     break;
1052
1053   // special
1054   case OP_XCHG:
1055     op->regmask_src |= op->regmask_dst;
1056     op->regmask_dst |= op->regmask_src;
1057     goto check_align;
1058
1059   case OP_SUB:
1060   case OP_SBB:
1061   case OP_XOR:
1062     if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1063      && op->operand[0].lmod == op->operand[1].lmod
1064      && op->operand[0].reg == op->operand[1].reg
1065      && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1066     {
1067       op->regmask_src = 0;
1068     }
1069     else
1070       op->regmask_src |= op->regmask_dst;
1071     break;
1072
1073   // ops with implicit argumets
1074   case OP_CDQ:
1075     op->operand_cnt = 2;
1076     setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
1077     setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
1078     break;
1079
1080   case OP_LODS:
1081   case OP_STOS:
1082   case OP_SCAS:
1083     if (op->operand_cnt != 0)
1084       break;
1085     if      (words[op_w][4] == 'b')
1086       lmod = OPLM_BYTE;
1087     else if (words[op_w][4] == 'w')
1088       lmod = OPLM_WORD;
1089     else if (words[op_w][4] == 'd')
1090       lmod = OPLM_DWORD;
1091     op->operand_cnt = 3;
1092     setup_reg_opr(&op->operand[0], op->op == OP_LODS ? xSI : xDI,
1093       lmod, &op->regmask_src);
1094     setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
1095     op->regmask_dst = op->regmask_src;
1096     setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD,
1097       op->op == OP_LODS ? &op->regmask_dst : &op->regmask_src);
1098     break;
1099
1100   case OP_MOVS:
1101   case OP_CMPS:
1102     if (op->operand_cnt != 0)
1103       break;
1104     if      (words[op_w][4] == 'b')
1105       lmod = OPLM_BYTE;
1106     else if (words[op_w][4] == 'w')
1107       lmod = OPLM_WORD;
1108     else if (words[op_w][4] == 'd')
1109       lmod = OPLM_DWORD;
1110     op->operand_cnt = 3;
1111     setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
1112     setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
1113     setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
1114     op->regmask_dst = op->regmask_src;
1115     break;
1116
1117   case OP_JECXZ:
1118     op->operand_cnt = 1;
1119     op->regmask_src = 1 << xCX;
1120     op->operand[0].type = OPT_REG;
1121     op->operand[0].reg = xCX;
1122     op->operand[0].lmod = OPLM_DWORD;
1123     break;
1124
1125   case OP_IMUL:
1126     if (op->operand_cnt != 1)
1127       break;
1128     // fallthrough
1129   case OP_MUL:
1130     // singleop mul
1131     op->regmask_src |= op->regmask_dst;
1132     op->regmask_dst = (1 << xDX) | (1 << xAX);
1133     if (op->operand[0].lmod == OPLM_UNSPEC)
1134       op->operand[0].lmod = OPLM_DWORD;
1135     break;
1136
1137   case OP_DIV:
1138   case OP_IDIV:
1139     // we could set up operands for edx:eax, but there is no real need to
1140     // (see is_opr_modified())
1141     op->regmask_src |= op->regmask_dst;
1142     op->regmask_dst = (1 << xDX) | (1 << xAX);
1143     if (op->operand[0].lmod == OPLM_UNSPEC)
1144       op->operand[0].lmod = OPLM_DWORD;
1145     break;
1146
1147   case OP_SHL:
1148   case OP_SHR:
1149   case OP_SAR:
1150   case OP_ROL:
1151   case OP_ROR:
1152     op->regmask_src |= op->regmask_dst;
1153     if (op->operand[1].lmod == OPLM_UNSPEC)
1154       op->operand[1].lmod = OPLM_BYTE;
1155     break;
1156
1157   case OP_SHRD:
1158     op->regmask_src |= op->regmask_dst;
1159     if (op->operand[2].lmod == OPLM_UNSPEC)
1160       op->operand[2].lmod = OPLM_BYTE;
1161     break;
1162
1163   case OP_PUSH:
1164     op->regmask_src |= op->regmask_dst;
1165     op->regmask_dst = 0;
1166     if (op->operand[0].lmod == OPLM_UNSPEC
1167         && (op->operand[0].type == OPT_CONST
1168          || op->operand[0].type == OPT_OFFSET
1169          || op->operand[0].type == OPT_LABEL))
1170       op->operand[0].lmod = OPLM_DWORD;
1171     break;
1172
1173   // alignment
1174   case OP_MOV:
1175   check_align:
1176     if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1177      && op->operand[0].lmod == op->operand[1].lmod
1178      && op->operand[0].reg == op->operand[1].reg
1179      && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1180     {
1181       op->flags |= OPF_RMD | OPF_DONE;
1182       op->regmask_src = op->regmask_dst = 0;
1183     }
1184     break;
1185
1186   case OP_LEA:
1187     if (op->operand[0].type == OPT_REG
1188      && op->operand[1].type == OPT_REGMEM)
1189     {
1190       char buf[16];
1191       snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1192       if (IS(buf, op->operand[1].name))
1193         op->flags |= OPF_RMD | OPF_DONE;
1194     }
1195     break;
1196
1197   case OP_CALL:
1198     // trashed regs must be explicitly detected later
1199     op->regmask_dst = 0;
1200     break;
1201
1202   case OP_LEAVE:
1203     op->regmask_dst = (1 << xBP) | (1 << xSP);
1204     op->regmask_src =  1 << xBP;
1205     break;
1206
1207   default:
1208     break;
1209   }
1210 }
1211
1212 static const char *op_name(struct parsed_op *po)
1213 {
1214   static char buf[16];
1215   char *p;
1216   int i;
1217
1218   if (po->op == OP_JCC || po->op == OP_SCC) {
1219     p = buf;
1220     *p++ = (po->op == OP_JCC) ? 'j' : 's';
1221     if (po->pfo_inv)
1222       *p++ = 'n';
1223     strcpy(p, parsed_flag_op_names[po->pfo]);
1224     return buf;
1225   }
1226
1227   for (i = 0; i < ARRAY_SIZE(op_table); i++)
1228     if (op_table[i].op == po->op)
1229       return op_table[i].name;
1230
1231   return "???";
1232 }
1233
1234 // debug
1235 static const char *dump_op(struct parsed_op *po)
1236 {
1237   static char out[128];
1238   char *p = out;
1239   int i;
1240
1241   if (po == NULL)
1242     return "???";
1243
1244   snprintf(out, sizeof(out), "%s", op_name(po));
1245   for (i = 0; i < po->operand_cnt; i++) {
1246     p += strlen(p);
1247     if (i > 0)
1248       *p++ = ',';
1249     snprintf(p, sizeof(out) - (p - out),
1250       po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1251       po->operand[i].name);
1252   }
1253
1254   return out;
1255 }
1256
1257 static const char *lmod_type_u(struct parsed_op *po,
1258   enum opr_lenmod lmod)
1259 {
1260   switch (lmod) {
1261   case OPLM_QWORD:
1262     return "u64";
1263   case OPLM_DWORD:
1264     return "u32";
1265   case OPLM_WORD:
1266     return "u16";
1267   case OPLM_BYTE:
1268     return "u8";
1269   default:
1270     ferr(po, "invalid lmod: %d\n", lmod);
1271     return "(_invalid_)";
1272   }
1273 }
1274
1275 static const char *lmod_cast_u(struct parsed_op *po,
1276   enum opr_lenmod lmod)
1277 {
1278   switch (lmod) {
1279   case OPLM_QWORD:
1280     return "";
1281   case OPLM_DWORD:
1282     return "";
1283   case OPLM_WORD:
1284     return "(u16)";
1285   case OPLM_BYTE:
1286     return "(u8)";
1287   default:
1288     ferr(po, "invalid lmod: %d\n", lmod);
1289     return "(_invalid_)";
1290   }
1291 }
1292
1293 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1294   enum opr_lenmod lmod)
1295 {
1296   switch (lmod) {
1297   case OPLM_QWORD:
1298     return "*(u64 *)";
1299   case OPLM_DWORD:
1300     return "*(u32 *)";
1301   case OPLM_WORD:
1302     return "*(u16 *)";
1303   case OPLM_BYTE:
1304     return "*(u8 *)";
1305   default:
1306     ferr(po, "invalid lmod: %d\n", lmod);
1307     return "(_invalid_)";
1308   }
1309 }
1310
1311 static const char *lmod_cast_s(struct parsed_op *po,
1312   enum opr_lenmod lmod)
1313 {
1314   switch (lmod) {
1315   case OPLM_QWORD:
1316     return "(s64)";
1317   case OPLM_DWORD:
1318     return "(s32)";
1319   case OPLM_WORD:
1320     return "(s16)";
1321   case OPLM_BYTE:
1322     return "(s8)";
1323   default:
1324     ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1325     return "(_invalid_)";
1326   }
1327 }
1328
1329 static const char *lmod_cast(struct parsed_op *po,
1330   enum opr_lenmod lmod, int is_signed)
1331 {
1332   return is_signed ?
1333     lmod_cast_s(po, lmod) :
1334     lmod_cast_u(po, lmod);
1335 }
1336
1337 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1338 {
1339   switch (lmod) {
1340   case OPLM_QWORD:
1341     return 8;
1342   case OPLM_DWORD:
1343     return 4;
1344   case OPLM_WORD:
1345     return 2;
1346   case OPLM_BYTE:
1347     return 1;
1348   default:
1349     ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1350     return 0;
1351   }
1352 }
1353
1354 static const char *opr_name(struct parsed_op *po, int opr_num)
1355 {
1356   if (opr_num >= po->operand_cnt)
1357     ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1358   return po->operand[opr_num].name;
1359 }
1360
1361 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1362 {
1363   if (opr_num >= po->operand_cnt)
1364     ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1365   if (po->operand[opr_num].type != OPT_CONST)
1366     ferr(po, "opr %d: const expected\n", opr_num);
1367   return po->operand[opr_num].val;
1368 }
1369
1370 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1371 {
1372   if ((unsigned int)popr->reg >= ARRAY_SIZE(regs_r32))
1373     ferr(po, "invalid reg: %d\n", popr->reg);
1374   return regs_r32[popr->reg];
1375 }
1376
1377 // cast1 is the "final" cast
1378 static const char *simplify_cast(const char *cast1, const char *cast2)
1379 {
1380   static char buf[256];
1381
1382   if (cast1[0] == 0)
1383     return cast2;
1384   if (cast2[0] == 0)
1385     return cast1;
1386   if (IS(cast1, cast2))
1387     return cast1;
1388   if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1389     return cast1;
1390   if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1391     return cast1;
1392   if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1393     return cast2;
1394   if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1395     return cast2;
1396   if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1397     return cast1;
1398
1399   snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1400   return buf;
1401 }
1402
1403 static const char *simplify_cast_num(const char *cast, unsigned int val)
1404 {
1405   if (IS(cast, "(u8)") && val < 0x100)
1406     return "";
1407   if (IS(cast, "(s8)") && val < 0x80)
1408     return "";
1409   if (IS(cast, "(u16)") && val < 0x10000)
1410     return "";
1411   if (IS(cast, "(s16)") && val < 0x8000)
1412     return "";
1413   if (IS(cast, "(s32)") && val < 0x80000000)
1414     return "";
1415
1416   return cast;
1417 }
1418
1419 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1420   int *extra_offs)
1421 {
1422   const char *p;
1423   char *endp;
1424   int namelen;
1425   int i;
1426
1427   *extra_offs = 0;
1428   namelen = strlen(name);
1429
1430   p = strchr(name, '+');
1431   if (p != NULL) {
1432     namelen = p - name;
1433     if (namelen <= 0)
1434       ferr(po, "equ parse failed for '%s'\n", name);
1435
1436     if (IS_START(p, "0x"))
1437       p += 2;
1438     *extra_offs = strtol(p, &endp, 16);
1439     if (*endp != 0)
1440       ferr(po, "equ parse failed for '%s'\n", name);
1441   }
1442
1443   for (i = 0; i < g_eqcnt; i++)
1444     if (strncmp(g_eqs[i].name, name, namelen) == 0
1445      && g_eqs[i].name[namelen] == 0)
1446       break;
1447   if (i >= g_eqcnt) {
1448     if (po != NULL)
1449       ferr(po, "unresolved equ name: '%s'\n", name);
1450     return NULL;
1451   }
1452
1453   return &g_eqs[i];
1454 }
1455
1456 static int is_stack_access(struct parsed_op *po,
1457   const struct parsed_opr *popr)
1458 {
1459   return (parse_stack_el(popr->name, NULL, 0)
1460     || (g_bp_frame && !(po->flags & OPF_EBP_S)
1461         && IS_START(popr->name, "ebp")));
1462 }
1463
1464 static void parse_stack_access(struct parsed_op *po,
1465   const char *name, char *ofs_reg, int *offset_out,
1466   int *stack_ra_out, const char **bp_arg_out, int is_lea)
1467 {
1468   const char *bp_arg = "";
1469   const char *p = NULL;
1470   struct parsed_equ *eq;
1471   char *endp = NULL;
1472   int stack_ra = 0;
1473   int offset = 0;
1474
1475   ofs_reg[0] = 0;
1476
1477   if (IS_START(name, "ebp-")
1478    || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1479   {
1480     p = name + 4;
1481     if (IS_START(p, "0x"))
1482       p += 2;
1483     offset = strtoul(p, &endp, 16);
1484     if (name[3] == '-')
1485       offset = -offset;
1486     if (*endp != 0)
1487       ferr(po, "ebp- parse of '%s' failed\n", name);
1488   }
1489   else {
1490     bp_arg = parse_stack_el(name, ofs_reg, 0);
1491     snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1492     eq = equ_find(po, bp_arg, &offset);
1493     if (eq == NULL)
1494       ferr(po, "detected but missing eq\n");
1495     offset += eq->offset;
1496   }
1497
1498   if (!strncmp(name, "ebp", 3))
1499     stack_ra = 4;
1500
1501   // yes it sometimes LEAs ra for compares..
1502   if (!is_lea && ofs_reg[0] == 0
1503     && stack_ra <= offset && offset < stack_ra + 4)
1504   {
1505     ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1506   }
1507
1508   *offset_out = offset;
1509   *stack_ra_out = stack_ra;
1510   if (bp_arg_out)
1511     *bp_arg_out = bp_arg;
1512 }
1513
1514 static int stack_frame_access(struct parsed_op *po,
1515   struct parsed_opr *popr, char *buf, size_t buf_size,
1516   const char *name, const char *cast, int is_src, int is_lea)
1517 {
1518   enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1519   const char *prefix = "";
1520   const char *bp_arg = NULL;
1521   char ofs_reg[16] = { 0, };
1522   int i, arg_i, arg_s;
1523   int unaligned = 0;
1524   int stack_ra = 0;
1525   int offset = 0;
1526   int retval = -1;
1527   int sf_ofs;
1528   int lim;
1529
1530   if (po->flags & OPF_EBP_S)
1531     ferr(po, "stack_frame_access while ebp is scratch\n");
1532
1533   parse_stack_access(po, name, ofs_reg, &offset,
1534     &stack_ra, &bp_arg, is_lea);
1535
1536   if (offset > stack_ra)
1537   {
1538     arg_i = (offset - stack_ra - 4) / 4;
1539     if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1540     {
1541       if (g_func_pp->is_vararg
1542           && arg_i == g_func_pp->argc_stack && is_lea)
1543       {
1544         // should be va_list
1545         if (cast[0] == 0)
1546           cast = "(u32)";
1547         snprintf(buf, buf_size, "%sap", cast);
1548         return -1;
1549       }
1550       ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1551         offset, bp_arg, arg_i);
1552     }
1553     if (ofs_reg[0] != 0)
1554       ferr(po, "offset reg on arg access?\n");
1555
1556     for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1557       if (g_func_pp->arg[i].reg != NULL)
1558         continue;
1559       if (arg_s == arg_i)
1560         break;
1561       arg_s++;
1562     }
1563     if (i == g_func_pp->argc)
1564       ferr(po, "arg %d not in prototype?\n", arg_i);
1565
1566     popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1567     retval = i;
1568
1569     switch (popr->lmod)
1570     {
1571     case OPLM_BYTE:
1572       if (is_lea)
1573         ferr(po, "lea/byte to arg?\n");
1574       if (is_src && (offset & 3) == 0)
1575         snprintf(buf, buf_size, "%sa%d",
1576           simplify_cast(cast, "(u8)"), i + 1);
1577       else
1578         snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1579           cast, offset & 3, i + 1);
1580       break;
1581
1582     case OPLM_WORD:
1583       if (is_lea)
1584         ferr(po, "lea/word to arg?\n");
1585       if (offset & 1) {
1586         unaligned = 1;
1587         if (!is_src) {
1588           if (offset & 2)
1589             ferr(po, "problematic arg store\n");
1590           snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1591             simplify_cast(cast, "*(u16 *)"), i + 1);
1592         }
1593         else
1594           ferr(po, "unaligned arg word load\n");
1595       }
1596       else if (is_src && (offset & 2) == 0)
1597         snprintf(buf, buf_size, "%sa%d",
1598           simplify_cast(cast, "(u16)"), i + 1);
1599       else
1600         snprintf(buf, buf_size, "%s%sWORD(a%d)",
1601           cast, (offset & 2) ? "HI" : "LO", i + 1);
1602       break;
1603
1604     case OPLM_DWORD:
1605       if (cast[0])
1606         prefix = cast;
1607       else if (is_src)
1608         prefix = "(u32)";
1609
1610       if (offset & 3) {
1611         unaligned = 1;
1612         if (is_lea)
1613           snprintf(buf, buf_size, "(u32)&a%d + %d",
1614             i + 1, offset & 3);
1615         else if (!is_src)
1616           ferr(po, "unaligned arg store\n");
1617         else {
1618           // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1619           snprintf(buf, buf_size, "%s(a%d >> %d)",
1620             prefix, i + 1, (offset & 3) * 8);
1621         }
1622       }
1623       else {
1624         snprintf(buf, buf_size, "%s%sa%d",
1625           prefix, is_lea ? "&" : "", i + 1);
1626       }
1627       break;
1628
1629     default:
1630       ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1631     }
1632
1633     if (unaligned)
1634       snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1635
1636     // common problem
1637     guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1638     if (tmp_lmod != OPLM_DWORD
1639       && (unaligned || (!is_src && lmod_bytes(po, tmp_lmod)
1640                          < lmod_bytes(po, popr->lmod) + (offset & 3))))
1641     {
1642       ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1643         i + 1, offset, g_func_pp->arg[i].type.name);
1644     }
1645     // can't check this because msvc likes to reuse
1646     // arg space for scratch..
1647     //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1648     //  ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1649   }
1650   else
1651   {
1652     if (g_stack_fsz == 0)
1653       ferr(po, "stack var access without stackframe\n");
1654     g_stack_frame_used = 1;
1655
1656     sf_ofs = g_stack_fsz + offset;
1657     lim = (ofs_reg[0] != 0) ? -4 : 0;
1658     if (offset > 0 || sf_ofs < lim)
1659       ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1660
1661     if (is_lea)
1662       prefix = "(u32)&";
1663     else
1664       prefix = cast;
1665
1666     switch (popr->lmod)
1667     {
1668     case OPLM_BYTE:
1669       snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1670         prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1671       break;
1672
1673     case OPLM_WORD:
1674       if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1675         // known unaligned or possibly unaligned
1676         strcat(g_comment, " unaligned");
1677         if (prefix[0] == 0)
1678           prefix = "*(u16 *)&";
1679         snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1680           prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1681         break;
1682       }
1683       snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1684       break;
1685
1686     case OPLM_DWORD:
1687       if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1688         // known unaligned or possibly unaligned
1689         strcat(g_comment, " unaligned");
1690         if (prefix[0] == 0)
1691           prefix = "*(u32 *)&";
1692         snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1693           prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1694         break;
1695       }
1696       snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1697       break;
1698
1699     default:
1700       ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1701     }
1702   }
1703
1704   return retval;
1705 }
1706
1707 static void check_func_pp(struct parsed_op *po,
1708   const struct parsed_proto *pp, const char *pfx)
1709 {
1710   enum opr_lenmod tmp_lmod;
1711   char buf[256];
1712   int ret, i;
1713
1714   if (pp->argc_reg != 0) {
1715     if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1716       pp_print(buf, sizeof(buf), pp);
1717       ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1718     }
1719     if (pp->argc_stack > 0 && pp->argc_reg != 2)
1720       ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1721         pfx, pp->argc_reg, pp->argc_stack);
1722   }
1723
1724   // fptrs must use 32bit args, callsite might have no information and
1725   // lack a cast to smaller types, which results in incorrectly masked
1726   // args passed (callee may assume masked args, it does on ARM)
1727   if (!pp->is_osinc) {
1728     for (i = 0; i < pp->argc; i++) {
1729       ret = guess_lmod_from_c_type(&tmp_lmod, &pp->arg[i].type);
1730       if (ret && tmp_lmod != OPLM_DWORD)
1731         ferr(po, "reference to %s with arg%d '%s'\n", pp->name,
1732           i + 1, pp->arg[i].type.name);
1733     }
1734   }
1735 }
1736
1737 static const char *check_label_read_ref(struct parsed_op *po,
1738   const char *name)
1739 {
1740   const struct parsed_proto *pp;
1741
1742   pp = proto_parse(g_fhdr, name, 0);
1743   if (pp == NULL)
1744     ferr(po, "proto_parse failed for ref '%s'\n", name);
1745
1746   if (pp->is_func)
1747     check_func_pp(po, pp, "ref");
1748
1749   return pp->name;
1750 }
1751
1752 static char *out_src_opr(char *buf, size_t buf_size,
1753   struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1754   int is_lea)
1755 {
1756   char tmp1[256], tmp2[256];
1757   char expr[256];
1758   const char *name;
1759   char *p;
1760   int ret;
1761
1762   if (cast == NULL)
1763     cast = "";
1764
1765   switch (popr->type) {
1766   case OPT_REG:
1767     if (is_lea)
1768       ferr(po, "lea from reg?\n");
1769
1770     switch (popr->lmod) {
1771     case OPLM_QWORD:
1772       snprintf(buf, buf_size, "%s%s.q", cast, opr_reg_p(po, popr));
1773       break;
1774     case OPLM_DWORD:
1775       snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1776       break;
1777     case OPLM_WORD:
1778       snprintf(buf, buf_size, "%s%s",
1779         simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1780       break;
1781     case OPLM_BYTE:
1782       if (popr->name[1] == 'h') // XXX..
1783         snprintf(buf, buf_size, "%s(%s >> 8)",
1784           simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1785       else
1786         snprintf(buf, buf_size, "%s%s",
1787           simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1788       break;
1789     default:
1790       ferr(po, "invalid src lmod: %d\n", popr->lmod);
1791     }
1792     break;
1793
1794   case OPT_REGMEM:
1795     if (is_stack_access(po, popr)) {
1796       stack_frame_access(po, popr, buf, buf_size,
1797         popr->name, cast, 1, is_lea);
1798       break;
1799     }
1800
1801     strcpy(expr, popr->name);
1802     if (strchr(expr, '[')) {
1803       // special case: '[' can only be left for label[reg] form
1804       ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1805       if (ret != 2)
1806         ferr(po, "parse failure for '%s'\n", expr);
1807       if (tmp1[0] == '(') {
1808         // (off_4FFF50+3)[eax]
1809         p = strchr(tmp1 + 1, ')');
1810         if (p == NULL || p[1] != 0)
1811           ferr(po, "parse failure (2) for '%s'\n", expr);
1812         *p = 0;
1813         memmove(tmp1, tmp1 + 1, strlen(tmp1));
1814       }
1815       snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1816     }
1817
1818     // XXX: do we need more parsing?
1819     if (is_lea) {
1820       snprintf(buf, buf_size, "%s", expr);
1821       break;
1822     }
1823
1824     snprintf(buf, buf_size, "%s(%s)",
1825       simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1826     break;
1827
1828   case OPT_LABEL:
1829     name = check_label_read_ref(po, popr->name);
1830     if (cast[0] == 0 && popr->is_ptr)
1831       cast = "(u32)";
1832
1833     if (is_lea)
1834       snprintf(buf, buf_size, "(u32)&%s", name);
1835     else if (popr->size_lt)
1836       snprintf(buf, buf_size, "%s%s%s%s", cast,
1837         lmod_cast_u_ptr(po, popr->lmod),
1838         popr->is_array ? "" : "&", name);
1839     else
1840       snprintf(buf, buf_size, "%s%s%s", cast, name,
1841         popr->is_array ? "[0]" : "");
1842     break;
1843
1844   case OPT_OFFSET:
1845     name = check_label_read_ref(po, popr->name);
1846     if (cast[0] == 0)
1847       cast = "(u32)";
1848     if (is_lea)
1849       ferr(po, "lea an offset?\n");
1850     snprintf(buf, buf_size, "%s&%s", cast, name);
1851     break;
1852
1853   case OPT_CONST:
1854     if (is_lea)
1855       ferr(po, "lea from const?\n");
1856
1857     printf_number(tmp1, sizeof(tmp1), popr->val);
1858     if (popr->val == 0 && strchr(cast, '*'))
1859       snprintf(buf, buf_size, "NULL");
1860     else
1861       snprintf(buf, buf_size, "%s%s",
1862         simplify_cast_num(cast, popr->val), tmp1);
1863     break;
1864
1865   default:
1866     ferr(po, "invalid src type: %d\n", popr->type);
1867   }
1868
1869   return buf;
1870 }
1871
1872 // note: may set is_ptr (we find that out late for ebp frame..)
1873 static char *out_dst_opr(char *buf, size_t buf_size,
1874         struct parsed_op *po, struct parsed_opr *popr)
1875 {
1876   switch (popr->type) {
1877   case OPT_REG:
1878     switch (popr->lmod) {
1879     case OPLM_QWORD:
1880       snprintf(buf, buf_size, "%s.q", opr_reg_p(po, popr));
1881       break;
1882     case OPLM_DWORD:
1883       snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1884       break;
1885     case OPLM_WORD:
1886       // ugh..
1887       snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1888       break;
1889     case OPLM_BYTE:
1890       // ugh..
1891       if (popr->name[1] == 'h') // XXX..
1892         snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1893       else
1894         snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1895       break;
1896     default:
1897       ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1898     }
1899     break;
1900
1901   case OPT_REGMEM:
1902     if (is_stack_access(po, popr)) {
1903       stack_frame_access(po, popr, buf, buf_size,
1904         popr->name, "", 0, 0);
1905       break;
1906     }
1907
1908     return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1909
1910   case OPT_LABEL:
1911     if (popr->size_mismatch)
1912       snprintf(buf, buf_size, "%s%s%s",
1913         lmod_cast_u_ptr(po, popr->lmod),
1914         popr->is_array ? "" : "&", popr->name);
1915     else
1916       snprintf(buf, buf_size, "%s%s", popr->name,
1917         popr->is_array ? "[0]" : "");
1918     break;
1919
1920   default:
1921     ferr(po, "invalid dst type: %d\n", popr->type);
1922   }
1923
1924   return buf;
1925 }
1926
1927 static char *out_src_opr_u32(char *buf, size_t buf_size,
1928         struct parsed_op *po, struct parsed_opr *popr)
1929 {
1930   return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1931 }
1932
1933 static void out_test_for_cc(char *buf, size_t buf_size,
1934   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1935   enum opr_lenmod lmod, const char *expr)
1936 {
1937   const char *cast, *scast;
1938
1939   cast = lmod_cast_u(po, lmod);
1940   scast = lmod_cast_s(po, lmod);
1941
1942   switch (pfo) {
1943   case PFO_Z:
1944   case PFO_BE: // CF=1||ZF=1; CF=0
1945     snprintf(buf, buf_size, "(%s%s %s 0)",
1946       cast, expr, is_inv ? "!=" : "==");
1947     break;
1948
1949   case PFO_S:
1950   case PFO_L: // SF!=OF; OF=0
1951     snprintf(buf, buf_size, "(%s%s %s 0)",
1952       scast, expr, is_inv ? ">=" : "<");
1953     break;
1954
1955   case PFO_LE: // ZF=1||SF!=OF; OF=0
1956     snprintf(buf, buf_size, "(%s%s %s 0)",
1957       scast, expr, is_inv ? ">" : "<=");
1958     break;
1959
1960   default:
1961     ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1962   }
1963 }
1964
1965 static void out_cmp_for_cc(char *buf, size_t buf_size,
1966   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1967 {
1968   const char *cast, *scast, *cast_use;
1969   char buf1[256], buf2[256];
1970   enum opr_lenmod lmod;
1971
1972   if (po->op != OP_DEC && po->operand[0].lmod != po->operand[1].lmod)
1973     ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1974       po->operand[0].lmod, po->operand[1].lmod);
1975   lmod = po->operand[0].lmod;
1976
1977   cast = lmod_cast_u(po, lmod);
1978   scast = lmod_cast_s(po, lmod);
1979
1980   switch (pfo) {
1981   case PFO_C:
1982   case PFO_Z:
1983   case PFO_BE: // !a
1984     cast_use = cast;
1985     break;
1986
1987   case PFO_S:
1988   case PFO_L: // !ge
1989   case PFO_LE:
1990     cast_use = scast;
1991     break;
1992
1993   default:
1994     ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1995   }
1996
1997   out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1998   if (po->op == OP_DEC)
1999     snprintf(buf2, sizeof(buf2), "1");
2000   else
2001     out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
2002
2003   switch (pfo) {
2004   case PFO_C:
2005     // note: must be unsigned compare
2006     snprintf(buf, buf_size, "(%s %s %s)",
2007       buf1, is_inv ? ">=" : "<", buf2);
2008     break;
2009
2010   case PFO_Z:
2011     snprintf(buf, buf_size, "(%s %s %s)",
2012       buf1, is_inv ? "!=" : "==", buf2);
2013     break;
2014
2015   case PFO_BE: // !a
2016     // note: must be unsigned compare
2017     snprintf(buf, buf_size, "(%s %s %s)",
2018       buf1, is_inv ? ">" : "<=", buf2);
2019
2020     // annoying case
2021     if (is_inv && lmod == OPLM_BYTE
2022       && po->operand[1].type == OPT_CONST
2023       && po->operand[1].val == 0xff)
2024     {
2025       snprintf(g_comment, sizeof(g_comment), "if %s", buf);
2026       snprintf(buf, buf_size, "(0)");
2027     }
2028     break;
2029
2030   // note: must be signed compare
2031   case PFO_S:
2032     snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
2033       scast, buf1, buf2, is_inv ? ">=" : "<");
2034     break;
2035
2036   case PFO_L: // !ge
2037     snprintf(buf, buf_size, "(%s %s %s)",
2038       buf1, is_inv ? ">=" : "<", buf2);
2039     break;
2040
2041   case PFO_LE: // !g
2042     snprintf(buf, buf_size, "(%s %s %s)",
2043       buf1, is_inv ? ">" : "<=", buf2);
2044     break;
2045
2046   default:
2047     break;
2048   }
2049 }
2050
2051 static void out_cmp_test(char *buf, size_t buf_size,
2052   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
2053 {
2054   char buf1[256], buf2[256], buf3[256];
2055
2056   if (po->op == OP_TEST) {
2057     if (IS(opr_name(po, 0), opr_name(po, 1))) {
2058       out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
2059     }
2060     else {
2061       out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
2062       out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
2063       snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
2064     }
2065     out_test_for_cc(buf, buf_size, po, pfo, is_inv,
2066       po->operand[0].lmod, buf3);
2067   }
2068   else if (po->op == OP_CMP) {
2069     out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
2070   }
2071   else
2072     ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
2073 }
2074
2075 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
2076         struct parsed_opr *popr2)
2077 {
2078   if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
2079     ferr(po, "missing lmod for both operands\n");
2080
2081   if (popr1->lmod == OPLM_UNSPEC)
2082     popr1->lmod = popr2->lmod;
2083   else if (popr2->lmod == OPLM_UNSPEC)
2084     popr2->lmod = popr1->lmod;
2085   else if (popr1->lmod != popr2->lmod) {
2086     if (popr1->type_from_var) {
2087       popr1->size_mismatch = 1;
2088       if (popr1->lmod < popr2->lmod)
2089         popr1->size_lt = 1;
2090       popr1->lmod = popr2->lmod;
2091     }
2092     else if (popr2->type_from_var) {
2093       popr2->size_mismatch = 1;
2094       if (popr2->lmod < popr1->lmod)
2095         popr2->size_lt = 1;
2096       popr2->lmod = popr1->lmod;
2097     }
2098     else
2099       ferr(po, "conflicting lmods: %d vs %d\n",
2100         popr1->lmod, popr2->lmod);
2101   }
2102 }
2103
2104 static const char *op_to_c(struct parsed_op *po)
2105 {
2106   switch (po->op)
2107   {
2108     case OP_ADD:
2109     case OP_ADC:
2110       return "+";
2111     case OP_SUB:
2112     case OP_SBB:
2113       return "-";
2114     case OP_AND:
2115       return "&";
2116     case OP_OR:
2117       return "|";
2118     case OP_XOR:
2119       return "^";
2120     case OP_SHL:
2121       return "<<";
2122     case OP_SHR:
2123       return ">>";
2124     case OP_MUL:
2125     case OP_IMUL:
2126       return "*";
2127     default:
2128       ferr(po, "op_to_c was supplied with %d\n", po->op);
2129   }
2130 }
2131
2132 static void op_set_clear_flag(struct parsed_op *po,
2133   enum op_flags flag_set, enum op_flags flag_clear)
2134 {
2135   po->flags |= flag_set;
2136   po->flags &= ~flag_clear;
2137 }
2138
2139 // last op in stream - unconditional branch or ret
2140 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
2141   || ((ops[_i].flags & (OPF_JMP|OPF_CJMP|OPF_RMD)) == OPF_JMP \
2142       && ops[_i].op != OP_CALL))
2143
2144 static int scan_for_pop(int i, int opcnt, const char *reg,
2145   int magic, int depth, int *maxdepth, int do_flags)
2146 {
2147   const struct parsed_proto *pp;
2148   struct parsed_op *po;
2149   int ret = 0;
2150   int j;
2151
2152   for (; i < opcnt; i++) {
2153     po = &ops[i];
2154     if (po->cc_scratch == magic)
2155       break; // already checked
2156     po->cc_scratch = magic;
2157
2158     if (po->flags & OPF_TAIL) {
2159       if (po->op == OP_CALL) {
2160         pp = proto_parse(g_fhdr, po->operand[0].name, g_quiet_pp);
2161         if (pp != NULL && pp->is_noreturn)
2162           // no stack cleanup for noreturn
2163           return ret;
2164       }
2165       return -1; // deadend
2166     }
2167
2168     if ((po->flags & (OPF_RMD|OPF_DONE))
2169         || (po->op == OP_PUSH && po->p_argnum != 0)) // arg push
2170       continue;
2171
2172     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2173       if (po->btj != NULL) {
2174         // jumptable
2175         for (j = 0; j < po->btj->count; j++) {
2176           ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
2177                    depth, maxdepth, do_flags);
2178           if (ret < 0)
2179             return ret; // dead end
2180         }
2181         return ret;
2182       }
2183
2184       if (po->bt_i < 0) {
2185         ferr(po, "dead branch\n");
2186         return -1;
2187       }
2188
2189       if (po->flags & OPF_CJMP) {
2190         ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
2191                  depth, maxdepth, do_flags);
2192         if (ret < 0)
2193           return ret; // dead end
2194       }
2195       else {
2196         i = po->bt_i - 1;
2197       }
2198       continue;
2199     }
2200
2201     if ((po->op == OP_POP || po->op == OP_PUSH)
2202         && po->operand[0].type == OPT_REG
2203         && IS(po->operand[0].name, reg))
2204     {
2205       if (po->op == OP_PUSH && !(po->flags & OPF_FARGNR)) {
2206         depth++;
2207         if (depth > *maxdepth)
2208           *maxdepth = depth;
2209         if (do_flags)
2210           op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2211       }
2212       else if (po->op == OP_POP) {
2213         if (depth == 0) {
2214           if (do_flags)
2215             op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2216           return 1;
2217         }
2218         else {
2219           depth--;
2220           if (depth < 0) // should not happen
2221             ferr(po, "fail with depth\n");
2222           if (do_flags)
2223             op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2224         }
2225       }
2226     }
2227   }
2228
2229   return ret;
2230 }
2231
2232 // scan for pop starting from 'ret' op (all paths)
2233 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2234   int flag_set)
2235 {
2236   int found = 0;
2237   int j;
2238
2239   for (; i < opcnt; i++) {
2240     if (!(ops[i].flags & OPF_TAIL))
2241       continue;
2242
2243     for (j = i - 1; j >= 0; j--) {
2244       if (ops[j].flags & (OPF_RMD|OPF_DONE))
2245         continue;
2246       if (ops[j].flags & OPF_JMP)
2247         return -1;
2248
2249       if (ops[j].op == OP_POP && ops[j].datap == NULL
2250           && ops[j].operand[0].type == OPT_REG
2251           && IS(ops[j].operand[0].name, reg))
2252       {
2253         found = 1;
2254         ops[j].flags |= flag_set;
2255         break;
2256       }
2257
2258       if (g_labels[j] != NULL)
2259         return -1;
2260     }
2261   }
2262
2263   return found ? 0 : -1;
2264 }
2265
2266 static void scan_for_pop_const(int i, int opcnt, int *regmask_pp)
2267 {
2268   struct parsed_op *po;
2269   int is_multipath = 0;
2270   int j;
2271
2272   for (j = i + 1; j < opcnt; j++) {
2273     po = &ops[j];
2274
2275     if (po->op == OP_JMP && po->btj == NULL) {
2276       ferr_assert(po, po->bt_i >= 0);
2277       j = po->bt_i - 1;
2278       continue;
2279     }
2280
2281     if ((po->flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
2282       || po->op == OP_PUSH)
2283     {
2284       break;
2285     }
2286
2287     if (g_labels[j] != NULL)
2288       is_multipath = 1;
2289
2290     if (po->op == OP_POP && !(po->flags & OPF_RMD))
2291     {
2292       is_multipath |= !!(po->flags & OPF_PPUSH);
2293       if (is_multipath) {
2294         ops[i].flags |= OPF_PPUSH | OPF_DONE;
2295         ops[i].datap = po;
2296         po->flags |= OPF_PPUSH | OPF_DONE;
2297         *regmask_pp |= 1 << po->operand[0].reg;
2298       }
2299       else {
2300         ops[i].flags |= OPF_RMD | OPF_DONE;
2301         po->flags |= OPF_DONE;
2302         po->datap = &ops[i];
2303       }
2304       break;
2305     }
2306   }
2307 }
2308
2309 static void scan_propagate_df(int i, int opcnt)
2310 {
2311   struct parsed_op *po = &ops[i];
2312   int j;
2313
2314   for (; i < opcnt; i++) {
2315     po = &ops[i];
2316     if (po->flags & OPF_DF)
2317       return; // already resolved
2318     po->flags |= OPF_DF;
2319
2320     if (po->op == OP_CALL)
2321       ferr(po, "call with DF set?\n");
2322
2323     if (po->flags & OPF_JMP) {
2324       if (po->btj != NULL) {
2325         // jumptable
2326         for (j = 0; j < po->btj->count; j++)
2327           scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2328         return;
2329       }
2330
2331       if (po->bt_i < 0) {
2332         ferr(po, "dead branch\n");
2333         return;
2334       }
2335
2336       if (po->flags & OPF_CJMP)
2337         scan_propagate_df(po->bt_i, opcnt);
2338       else
2339         i = po->bt_i - 1;
2340       continue;
2341     }
2342
2343     if (po->flags & OPF_TAIL)
2344       break;
2345
2346     if (po->op == OP_CLD) {
2347       po->flags |= OPF_RMD | OPF_DONE;
2348       return;
2349     }
2350   }
2351
2352   ferr(po, "missing DF clear?\n");
2353 }
2354
2355 // is operand 'opr' modified by parsed_op 'po'?
2356 static int is_opr_modified(const struct parsed_opr *opr,
2357   const struct parsed_op *po)
2358 {
2359   int mask;
2360
2361   if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2362     return 0;
2363
2364   if (opr->type == OPT_REG) {
2365     if (po->op == OP_CALL) {
2366       mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2367       if ((1 << opr->reg) & mask)
2368         return 1;
2369       else
2370         return 0;
2371     }
2372
2373     if (po->operand[0].type == OPT_REG) {
2374       if (po->regmask_dst & (1 << opr->reg))
2375         return 1;
2376       else
2377         return 0;
2378     }
2379   }
2380
2381   return IS(po->operand[0].name, opr->name);
2382 }
2383
2384 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2385 static int is_any_opr_modified(const struct parsed_op *po_test,
2386   const struct parsed_op *po, int c_mode)
2387 {
2388   int mask;
2389   int i;
2390
2391   if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2392     return 0;
2393
2394   if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2395     return 0;
2396
2397   if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2398     return 1;
2399
2400   // in reality, it can wreck any register, but in decompiled C
2401   // version it can only overwrite eax or edx:eax
2402   mask = (1 << xAX) | (1 << xDX);
2403   if (!c_mode)
2404     mask |= 1 << xCX;
2405
2406   if (po->op == OP_CALL
2407    && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2408     return 1;
2409
2410   for (i = 0; i < po_test->operand_cnt; i++)
2411     if (IS(po_test->operand[i].name, po->operand[0].name))
2412       return 1;
2413
2414   return 0;
2415 }
2416
2417 // scan for any po_test operand modification in range given
2418 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2419   int c_mode)
2420 {
2421   if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2422     return -1;
2423
2424   for (; i < opcnt; i++) {
2425     if (is_any_opr_modified(po_test, &ops[i], c_mode))
2426       return i;
2427   }
2428
2429   return -1;
2430 }
2431
2432 // scan for po_test operand[0] modification in range given
2433 static int scan_for_mod_opr0(struct parsed_op *po_test,
2434   int i, int opcnt)
2435 {
2436   for (; i < opcnt; i++) {
2437     if (is_opr_modified(&po_test->operand[0], &ops[i]))
2438       return i;
2439   }
2440
2441   return -1;
2442 }
2443
2444 #define check_i(po, i) \
2445   if ((i) < 0) \
2446     ferr(po, "bad " #i ": %d\n", i)
2447
2448 static int scan_for_flag_set(int i, int magic, int *branched,
2449   int *setters, int *setter_cnt)
2450 {
2451   struct label_ref *lr;
2452   int ret;
2453
2454   while (i >= 0) {
2455     if (ops[i].cc_scratch == magic) {
2456       ferr(&ops[i], "%s looped\n", __func__);
2457       return -1;
2458     }
2459     ops[i].cc_scratch = magic;
2460
2461     if (g_labels[i] != NULL) {
2462       *branched = 1;
2463
2464       lr = &g_label_refs[i];
2465       for (; lr->next; lr = lr->next) {
2466         check_i(&ops[i], lr->i);
2467         ret = scan_for_flag_set(lr->i, magic,
2468                 branched, setters, setter_cnt);
2469         if (ret < 0)
2470           return ret;
2471       }
2472
2473       check_i(&ops[i], lr->i);
2474       if (i > 0 && LAST_OP(i - 1)) {
2475         i = lr->i;
2476         continue;
2477       }
2478       ret = scan_for_flag_set(lr->i, magic,
2479               branched, setters, setter_cnt);
2480       if (ret < 0)
2481         return ret;
2482     }
2483     i--;
2484
2485     if (ops[i].flags & OPF_FLAGS) {
2486       setters[*setter_cnt] = i;
2487       (*setter_cnt)++;
2488       return 0;
2489     }
2490
2491     if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2492       return -1;
2493   }
2494
2495   return -1;
2496 }
2497
2498 // scan back for cdq, if anything modifies edx, fail
2499 static int scan_for_cdq_edx(int i)
2500 {
2501   while (i >= 0) {
2502     if (g_labels[i] != NULL) {
2503       if (g_label_refs[i].next != NULL)
2504         return -1;
2505       if (i > 0 && LAST_OP(i - 1)) {
2506         i = g_label_refs[i].i;
2507         continue;
2508       }
2509       return -1;
2510     }
2511     i--;
2512
2513     if (ops[i].op == OP_CDQ)
2514       return i;
2515
2516     if (ops[i].regmask_dst & (1 << xDX))
2517       return -1;
2518   }
2519
2520   return -1;
2521 }
2522
2523 static int scan_for_reg_clear(int i, int reg)
2524 {
2525   while (i >= 0) {
2526     if (g_labels[i] != NULL) {
2527       if (g_label_refs[i].next != NULL)
2528         return -1;
2529       if (i > 0 && LAST_OP(i - 1)) {
2530         i = g_label_refs[i].i;
2531         continue;
2532       }
2533       return -1;
2534     }
2535     i--;
2536
2537     if (ops[i].op == OP_XOR
2538      && ops[i].operand[0].lmod == OPLM_DWORD
2539      && ops[i].operand[0].reg == ops[i].operand[1].reg
2540      && ops[i].operand[0].reg == reg)
2541       return i;
2542
2543     if (ops[i].regmask_dst & (1 << reg))
2544       return -1;
2545   }
2546
2547   return -1;
2548 }
2549
2550 static void patch_esp_adjust(struct parsed_op *po, int adj)
2551 {
2552   ferr_assert(po, po->op == OP_ADD);
2553   ferr_assert(po, IS(opr_name(po, 0), "esp"));
2554   ferr_assert(po, po->operand[1].type == OPT_CONST);
2555
2556   // this is a bit of a hack, but deals with use of
2557   // single adj for multiple calls
2558   po->operand[1].val -= adj;
2559   po->flags |= OPF_RMD;
2560   if (po->operand[1].val == 0)
2561     po->flags |= OPF_DONE;
2562   ferr_assert(po, (int)po->operand[1].val >= 0);
2563 }
2564
2565 // scan for positive, constant esp adjust
2566 // multipath case is preliminary
2567 static int scan_for_esp_adjust(int i, int opcnt,
2568   int adj_expect, int *adj, int *is_multipath, int do_update)
2569 {
2570   struct parsed_op *po;
2571   int first_pop = -1;
2572
2573   *adj = *is_multipath = 0;
2574
2575   for (; i < opcnt && *adj < adj_expect; i++) {
2576     if (g_labels[i] != NULL)
2577       *is_multipath = 1;
2578
2579     po = &ops[i];
2580     if (po->flags & OPF_DONE)
2581       continue;
2582
2583     if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2584       if (po->operand[1].type != OPT_CONST)
2585         ferr(&ops[i], "non-const esp adjust?\n");
2586       *adj += po->operand[1].val;
2587       if (*adj & 3)
2588         ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2589       if (do_update) {
2590         if (!*is_multipath)
2591           patch_esp_adjust(po, adj_expect);
2592         else
2593           po->flags |= OPF_RMD;
2594       }
2595       return i;
2596     }
2597     else if (po->op == OP_PUSH) {
2598       //if (first_pop == -1)
2599       //  first_pop = -2; // none
2600       *adj -= lmod_bytes(po, po->operand[0].lmod);
2601     }
2602     else if (po->op == OP_POP) {
2603       if (!(po->flags & OPF_DONE)) {
2604         // seems like msvc only uses 'pop ecx' for stack realignment..
2605         if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2606           break;
2607         if (first_pop == -1 && *adj >= 0)
2608           first_pop = i;
2609       }
2610       if (do_update && *adj >= 0) {
2611         po->flags |= OPF_RMD;
2612         if (!*is_multipath)
2613           po->flags |= OPF_DONE;
2614       }
2615
2616       *adj += lmod_bytes(po, po->operand[0].lmod);
2617     }
2618     else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2619       if (po->op == OP_JMP && po->btj == NULL) {
2620         if (po->bt_i <= i)
2621           break;
2622         i = po->bt_i - 1;
2623         continue;
2624       }
2625       if (po->op != OP_CALL)
2626         break;
2627       if (po->operand[0].type != OPT_LABEL)
2628         break;
2629       if (po->pp != NULL && po->pp->is_stdcall)
2630         break;
2631       // assume it's another cdecl call
2632     }
2633   }
2634
2635   if (first_pop >= 0) {
2636     // probably 'pop ecx' was used..
2637     return first_pop;
2638   }
2639
2640   return -1;
2641 }
2642
2643 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2644 {
2645   struct parsed_op *po;
2646   int j;
2647
2648   if (i < 0)
2649     ferr(ops, "%s: followed bad branch?\n", __func__);
2650
2651   for (; i < opcnt; i++) {
2652     po = &ops[i];
2653     if (po->cc_scratch == magic)
2654       return;
2655     po->cc_scratch = magic;
2656     po->flags |= flags;
2657
2658     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2659       if (po->btj != NULL) {
2660         // jumptable
2661         for (j = 0; j < po->btj->count; j++)
2662           scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2663         return;
2664       }
2665
2666       scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2667       if (!(po->flags & OPF_CJMP))
2668         return;
2669     }
2670     if (po->flags & OPF_TAIL)
2671       return;
2672   }
2673 }
2674
2675 static const struct parsed_proto *try_recover_pp(
2676   struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2677 {
2678   const struct parsed_proto *pp = NULL;
2679   char buf[256];
2680   char *p;
2681
2682   // maybe an arg of g_func?
2683   if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2684   {
2685     char ofs_reg[16] = { 0, };
2686     int arg, arg_s, arg_i;
2687     int stack_ra = 0;
2688     int offset = 0;
2689
2690     if (g_header_mode)
2691       return NULL;
2692
2693     parse_stack_access(po, opr->name, ofs_reg,
2694       &offset, &stack_ra, NULL, 0);
2695     if (ofs_reg[0] != 0)
2696       ferr(po, "offset reg on arg access?\n");
2697     if (offset <= stack_ra) {
2698       // search who set the stack var instead
2699       if (search_instead != NULL)
2700         *search_instead = 1;
2701       return NULL;
2702     }
2703
2704     arg_i = (offset - stack_ra - 4) / 4;
2705     for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2706       if (g_func_pp->arg[arg].reg != NULL)
2707         continue;
2708       if (arg_s == arg_i)
2709         break;
2710       arg_s++;
2711     }
2712     if (arg == g_func_pp->argc)
2713       ferr(po, "stack arg %d not in prototype?\n", arg_i);
2714
2715     pp = g_func_pp->arg[arg].fptr;
2716     if (pp == NULL)
2717       ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2718     check_func_pp(po, pp, "icall arg");
2719   }
2720   else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2721     // label[index]
2722     p = strchr(opr->name + 1, '[');
2723     memcpy(buf, opr->name, p - opr->name);
2724     buf[p - opr->name] = 0;
2725     pp = proto_parse(g_fhdr, buf, g_quiet_pp);
2726   }
2727   else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2728     pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
2729     if (pp == NULL) {
2730       if (!g_header_mode)
2731         ferr(po, "proto_parse failed for icall to '%s'\n", opr->name);
2732     }
2733     else
2734       check_func_pp(po, pp, "reg-fptr ref");
2735   }
2736
2737   return pp;
2738 }
2739
2740 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2741   int magic, const struct parsed_proto **pp_found, int *multi)
2742 {
2743   const struct parsed_proto *pp = NULL;
2744   struct parsed_op *po;
2745   struct label_ref *lr;
2746
2747   ops[i].cc_scratch = magic;
2748
2749   while (1) {
2750     if (g_labels[i] != NULL) {
2751       lr = &g_label_refs[i];
2752       for (; lr != NULL; lr = lr->next) {
2753         check_i(&ops[i], lr->i);
2754         scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2755       }
2756       if (i > 0 && LAST_OP(i - 1))
2757         return;
2758     }
2759
2760     i--;
2761     if (i < 0)
2762       break;
2763
2764     if (ops[i].cc_scratch == magic)
2765       return;
2766     ops[i].cc_scratch = magic;
2767
2768     if (!(ops[i].flags & OPF_DATA))
2769       continue;
2770     if (!is_opr_modified(opr, &ops[i]))
2771       continue;
2772     if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2773       // most probably trashed by some processing
2774       *pp_found = NULL;
2775       return;
2776     }
2777
2778     opr = &ops[i].operand[1];
2779     if (opr->type != OPT_REG)
2780       break;
2781   }
2782
2783   po = (i >= 0) ? &ops[i] : ops;
2784
2785   if (i < 0) {
2786     // reached the top - can only be an arg-reg
2787     if (opr->type != OPT_REG)
2788       return;
2789
2790     for (i = 0; i < g_func_pp->argc; i++) {
2791       if (g_func_pp->arg[i].reg == NULL)
2792         continue;
2793       if (IS(opr->name, g_func_pp->arg[i].reg))
2794         break;
2795     }
2796     if (i == g_func_pp->argc)
2797       return;
2798     pp = g_func_pp->arg[i].fptr;
2799     if (pp == NULL)
2800       ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2801         i + 1, g_func_pp->arg[i].reg);
2802     check_func_pp(po, pp, "icall reg-arg");
2803   }
2804   else
2805     pp = try_recover_pp(po, opr, NULL);
2806
2807   if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2808     if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2809       || (*pp_found)->is_stdcall != pp->is_stdcall
2810       || (*pp_found)->is_fptr != pp->is_fptr
2811       || (*pp_found)->argc != pp->argc
2812       || (*pp_found)->argc_reg != pp->argc_reg
2813       || (*pp_found)->argc_stack != pp->argc_stack)
2814     {
2815       ferr(po, "icall: parsed_proto mismatch\n");
2816     }
2817     *multi = 1;
2818   }
2819   if (pp != NULL)
2820     *pp_found = pp;
2821 }
2822
2823 // early check for tail call or branch back
2824 static int is_like_tailjmp(int j)
2825 {
2826   if (!(ops[j].flags & OPF_JMP))
2827     return 0;
2828
2829   if (ops[j].op == OP_JMP && !ops[j].operand[0].had_ds)
2830     // probably local branch back..
2831     return 1;
2832   if (ops[j].op == OP_CALL)
2833     // probably noreturn call..
2834     return 1;
2835
2836   return 0;
2837 }
2838
2839 static void scan_prologue_epilogue(int opcnt)
2840 {
2841   int ecx_push = 0, esp_sub = 0;
2842   int found;
2843   int i, j, l;
2844
2845   if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2846       && ops[1].op == OP_MOV
2847       && IS(opr_name(&ops[1], 0), "ebp")
2848       && IS(opr_name(&ops[1], 1), "esp"))
2849   {
2850     g_bp_frame = 1;
2851     ops[0].flags |= OPF_RMD | OPF_DONE;
2852     ops[1].flags |= OPF_RMD | OPF_DONE;
2853     i = 2;
2854
2855     if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2856       g_stack_fsz = opr_const(&ops[2], 1);
2857       ops[2].flags |= OPF_RMD | OPF_DONE;
2858       i++;
2859     }
2860     else {
2861       // another way msvc builds stack frame..
2862       i = 2;
2863       while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2864         g_stack_fsz += 4;
2865         ops[i].flags |= OPF_RMD | OPF_DONE;
2866         ecx_push++;
2867         i++;
2868       }
2869       // and another way..
2870       if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2871           && ops[i].operand[1].type == OPT_CONST
2872           && ops[i + 1].op == OP_CALL
2873           && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2874       {
2875         g_stack_fsz += ops[i].operand[1].val;
2876         ops[i].flags |= OPF_RMD | OPF_DONE;
2877         i++;
2878         ops[i].flags |= OPF_RMD | OPF_DONE;
2879         i++;
2880       }
2881     }
2882
2883     found = 0;
2884     do {
2885       for (; i < opcnt; i++)
2886         if (ops[i].op == OP_RET)
2887           break;
2888       j = i - 1;
2889       if (i == opcnt && (ops[j].flags & OPF_JMP)) {
2890         if (found && is_like_tailjmp(j))
2891             break;
2892         j--;
2893       }
2894
2895       if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
2896           || ops[j].op == OP_LEAVE)
2897       {
2898         ops[j].flags |= OPF_RMD | OPF_DONE;
2899       }
2900       else if (!(g_ida_func_attr & IDAFA_NORETURN))
2901         ferr(&ops[j], "'pop ebp' expected\n");
2902
2903       if (g_stack_fsz != 0) {
2904         if (ops[j - 1].op == OP_MOV
2905             && IS(opr_name(&ops[j - 1], 0), "esp")
2906             && IS(opr_name(&ops[j - 1], 1), "ebp"))
2907         {
2908           ops[j - 1].flags |= OPF_RMD | OPF_DONE;
2909         }
2910         else if (ops[j].op != OP_LEAVE
2911           && !(g_ida_func_attr & IDAFA_NORETURN))
2912         {
2913           ferr(&ops[j - 1], "esp restore expected\n");
2914         }
2915
2916         if (ecx_push && ops[j - 2].op == OP_POP
2917           && IS(opr_name(&ops[j - 2], 0), "ecx"))
2918         {
2919           ferr(&ops[j - 2], "unexpected ecx pop\n");
2920         }
2921       }
2922
2923       found = 1;
2924       i++;
2925     } while (i < opcnt);
2926
2927     return;
2928   }
2929
2930   // non-bp frame
2931   i = 0;
2932   while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2933     ops[i].flags |= OPF_RMD | OPF_DONE;
2934     g_stack_fsz += 4;
2935     ecx_push++;
2936     i++;
2937   }
2938
2939   for (; i < opcnt; i++) {
2940     if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2941       break;
2942     if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2943       && ops[i].operand[1].type == OPT_CONST)
2944     {
2945       g_stack_fsz = ops[i].operand[1].val;
2946       ops[i].flags |= OPF_RMD | OPF_DONE;
2947       esp_sub = 1;
2948       break;
2949     }
2950   }
2951
2952   if (ecx_push && !esp_sub) {
2953     // could actually be args for a call..
2954     for (; i < opcnt; i++)
2955       if (ops[i].op != OP_PUSH)
2956         break;
2957
2958     if (ops[i].op == OP_CALL && ops[i].operand[0].type == OPT_LABEL) {
2959       const struct parsed_proto *pp;
2960       pp = proto_parse(g_fhdr, opr_name(&ops[i], 0), 1);
2961       j = pp ? pp->argc_stack : 0;
2962       while (i > 0 && j > 0) {
2963         i--;
2964         if (ops[i].op == OP_PUSH) {
2965           ops[i].flags &= ~(OPF_RMD | OPF_DONE);
2966           j--;
2967         }
2968       }
2969       if (j != 0)
2970         ferr(&ops[i], "unhandled prologue\n");
2971
2972       // recheck
2973       i = g_stack_fsz = ecx_push = 0;
2974       while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2975         if (!(ops[i].flags & OPF_RMD))
2976           break;
2977         g_stack_fsz += 4;
2978         ecx_push++;
2979         i++;
2980       }
2981     }
2982   }
2983
2984   found = 0;
2985   if (ecx_push || esp_sub)
2986   {
2987     g_sp_frame = 1;
2988
2989     i++;
2990     do {
2991       for (; i < opcnt; i++)
2992         if (ops[i].op == OP_RET)
2993           break;
2994       j = i - 1;
2995       if (i == opcnt && (ops[j].flags & OPF_JMP)) {
2996         if (found && is_like_tailjmp(j))
2997             break;
2998         j--;
2999       }
3000
3001       if (ecx_push > 0) {
3002         for (l = 0; l < ecx_push; l++) {
3003           if (ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ecx"))
3004             /* pop ecx */;
3005           else if (ops[j].op == OP_ADD
3006                    && IS(opr_name(&ops[j], 0), "esp")
3007                    && ops[j].operand[1].type == OPT_CONST)
3008           {
3009             /* add esp, N */
3010             l += ops[j].operand[1].val / 4 - 1;
3011           }
3012           else
3013             ferr(&ops[j], "'pop ecx' expected\n");
3014
3015           ops[j].flags |= OPF_RMD | OPF_DONE;
3016           j--;
3017         }
3018         if (l != ecx_push)
3019           ferr(&ops[j], "epilogue scan failed\n");
3020
3021         found = 1;
3022       }
3023
3024       if (esp_sub) {
3025         if (ops[j].op != OP_ADD
3026             || !IS(opr_name(&ops[j], 0), "esp")
3027             || ops[j].operand[1].type != OPT_CONST
3028             || ops[j].operand[1].val != g_stack_fsz)
3029           ferr(&ops[j], "'add esp' expected\n");
3030
3031         ops[j].flags |= OPF_RMD | OPF_DONE;
3032         ops[j].operand[1].val = 0; // hack for stack arg scanner
3033         found = 1;
3034       }
3035
3036       i++;
3037     } while (i < opcnt);
3038   }
3039 }
3040
3041 static const struct parsed_proto *resolve_icall(int i, int opcnt,
3042   int *multi_src)
3043 {
3044   const struct parsed_proto *pp = NULL;
3045   int search_advice = 0;
3046
3047   *multi_src = 0;
3048
3049   switch (ops[i].operand[0].type) {
3050   case OPT_REGMEM:
3051   case OPT_LABEL:
3052   case OPT_OFFSET:
3053     pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
3054     if (!search_advice)
3055       break;
3056     // fallthrough
3057   default:
3058     scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
3059       multi_src);
3060     break;
3061   }
3062
3063   return pp;
3064 }
3065
3066 // find an instruction that changed opr before i op
3067 // *op_i must be set to -1 by caller
3068 // *entry is set to 1 if one source is determined to be the caller
3069 // returns 1 if found, *op_i is then set to origin
3070 static int resolve_origin(int i, const struct parsed_opr *opr,
3071   int magic, int *op_i, int *is_caller)
3072 {
3073   struct label_ref *lr;
3074   int ret = 0;
3075
3076   if (ops[i].cc_scratch == magic)
3077     return 0;
3078   ops[i].cc_scratch = magic;
3079
3080   while (1) {
3081     if (g_labels[i] != NULL) {
3082       lr = &g_label_refs[i];
3083       for (; lr != NULL; lr = lr->next) {
3084         check_i(&ops[i], lr->i);
3085         ret |= resolve_origin(lr->i, opr, magic, op_i, is_caller);
3086       }
3087       if (i > 0 && LAST_OP(i - 1))
3088         return ret;
3089     }
3090
3091     i--;
3092     if (i < 0) {
3093       if (is_caller != NULL)
3094         *is_caller = 1;
3095       return -1;
3096     }
3097
3098     if (ops[i].cc_scratch == magic)
3099       return 0;
3100     ops[i].cc_scratch = magic;
3101
3102     if (!(ops[i].flags & OPF_DATA))
3103       continue;
3104     if (!is_opr_modified(opr, &ops[i]))
3105       continue;
3106
3107     if (*op_i >= 0) {
3108       if (*op_i == i)
3109         return 1;
3110       // XXX: could check if the other op does the same
3111       return -1;
3112     }
3113
3114     *op_i = i;
3115     return 1;
3116   }
3117 }
3118
3119 static int try_resolve_const(int i, const struct parsed_opr *opr,
3120   int magic, unsigned int *val)
3121 {
3122   int s_i = -1;
3123   int ret;
3124
3125   ret = resolve_origin(i, opr, magic, &s_i, NULL);
3126   if (ret == 1) {
3127     i = s_i;
3128     if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
3129       return -1;
3130
3131     *val = ops[i].operand[1].val;
3132     return 1;
3133   }
3134
3135   return -1;
3136 }
3137
3138 static struct parsed_proto *process_call_early(int i, int opcnt,
3139   int *adj_i)
3140 {
3141   struct parsed_op *po = &ops[i];
3142   struct parsed_proto *pp;
3143   int multipath = 0;
3144   int adj = 0;
3145   int ret;
3146
3147   pp = po->pp;
3148   if (pp == NULL || pp->is_vararg || pp->argc_reg != 0)
3149     // leave for later
3150     return NULL;
3151
3152   // look for and make use of esp adjust
3153   *adj_i = ret = -1;
3154   if (!pp->is_stdcall && pp->argc_stack > 0)
3155     ret = scan_for_esp_adjust(i + 1, opcnt,
3156             pp->argc_stack * 4, &adj, &multipath, 0);
3157   if (ret >= 0) {
3158     if (pp->argc_stack > adj / 4)
3159       return NULL;
3160     if (multipath)
3161       return NULL;
3162     if (ops[ret].op == OP_POP && adj != 4)
3163       return NULL;
3164   }
3165
3166   *adj_i = ret;
3167   return pp;
3168 }
3169
3170 static struct parsed_proto *process_call(int i, int opcnt)
3171 {
3172   struct parsed_op *po = &ops[i];
3173   const struct parsed_proto *pp_c;
3174   struct parsed_proto *pp;
3175   const char *tmpname;
3176   int adj = 0, multipath = 0;
3177   int ret, arg;
3178
3179   tmpname = opr_name(po, 0);
3180   pp = po->pp;
3181   if (pp == NULL)
3182   {
3183     // indirect call
3184     pp_c = resolve_icall(i, opcnt, &multipath);
3185     if (pp_c != NULL) {
3186       if (!pp_c->is_func && !pp_c->is_fptr)
3187         ferr(po, "call to non-func: %s\n", pp_c->name);
3188       pp = proto_clone(pp_c);
3189       my_assert_not(pp, NULL);
3190       if (multipath)
3191         // not resolved just to single func
3192         pp->is_fptr = 1;
3193
3194       switch (po->operand[0].type) {
3195       case OPT_REG:
3196         // we resolved this call and no longer need the register
3197         po->regmask_src &= ~(1 << po->operand[0].reg);
3198         break;
3199       case OPT_REGMEM:
3200         pp->is_fptr = 1;
3201         break;
3202       default:
3203         break;
3204       }
3205     }
3206     if (pp == NULL) {
3207       pp = calloc(1, sizeof(*pp));
3208       my_assert_not(pp, NULL);
3209
3210       pp->is_fptr = 1;
3211       ret = scan_for_esp_adjust(i + 1, opcnt,
3212               32*4, &adj, &multipath, 0);
3213       if (ret < 0 || adj < 0) {
3214         if (!g_allow_regfunc)
3215           ferr(po, "non-__cdecl indirect call unhandled yet\n");
3216         pp->is_unresolved = 1;
3217         adj = 0;
3218       }
3219       adj /= 4;
3220       if (adj > ARRAY_SIZE(pp->arg))
3221         ferr(po, "esp adjust too large: %d\n", adj);
3222       pp->ret_type.name = strdup("int");
3223       pp->argc = pp->argc_stack = adj;
3224       for (arg = 0; arg < pp->argc; arg++)
3225         pp->arg[arg].type.name = strdup("int");
3226     }
3227     po->pp = pp;
3228   }
3229
3230   // look for and make use of esp adjust
3231   multipath = 0;
3232   ret = -1;
3233   if (!pp->is_stdcall && pp->argc_stack > 0)
3234     ret = scan_for_esp_adjust(i + 1, opcnt,
3235             pp->argc_stack * 4, &adj, &multipath, 0);
3236   if (ret >= 0) {
3237     if (pp->is_vararg) {
3238       if (adj / 4 < pp->argc_stack) {
3239         fnote(po, "(this call)\n");
3240         ferr(&ops[ret], "esp adjust is too small: %x < %x\n",
3241           adj, pp->argc_stack * 4);
3242       }
3243       // modify pp to make it have varargs as normal args
3244       arg = pp->argc;
3245       pp->argc += adj / 4 - pp->argc_stack;
3246       for (; arg < pp->argc; arg++) {
3247         pp->arg[arg].type.name = strdup("int");
3248         pp->argc_stack++;
3249       }
3250       if (pp->argc > ARRAY_SIZE(pp->arg))
3251         ferr(po, "too many args for '%s'\n", tmpname);
3252     }
3253     if (pp->argc_stack > adj / 4) {
3254       fnote(po, "(this call)\n");
3255       ferr(&ops[ret], "stack tracking failed for '%s': %x %x\n",
3256         tmpname, pp->argc_stack * 4, adj);
3257     }
3258
3259     scan_for_esp_adjust(i + 1, opcnt,
3260       pp->argc_stack * 4, &adj, &multipath, 1);
3261   }
3262   else if (pp->is_vararg)
3263     ferr(po, "missing esp_adjust for vararg func '%s'\n",
3264       pp->name);
3265
3266   return pp;
3267 }
3268
3269 static int collect_call_args_early(struct parsed_op *po, int i,
3270   struct parsed_proto *pp, int *regmask)
3271 {
3272   int arg, ret;
3273   int j;
3274
3275   for (arg = 0; arg < pp->argc; arg++)
3276     if (pp->arg[arg].reg == NULL)
3277       break;
3278
3279   // first see if it can be easily done
3280   for (j = i; j > 0 && arg < pp->argc; )
3281   {
3282     if (g_labels[j] != NULL)
3283       return -1;
3284     j--;
3285
3286     if (ops[j].op == OP_CALL)
3287       return -1;
3288     else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP)
3289       return -1;
3290     else if (ops[j].op == OP_POP)
3291       return -1;
3292     else if (ops[j].flags & OPF_CJMP)
3293       return -1;
3294     else if (ops[j].op == OP_PUSH) {
3295       if (ops[j].flags & (OPF_FARG|OPF_FARGNR))
3296         return -1;
3297       ret = scan_for_mod(&ops[j], j + 1, i, 1);
3298       if (ret >= 0)
3299         return -1;
3300
3301       if (pp->arg[arg].type.is_va_list)
3302         return -1;
3303
3304       // next arg
3305       for (arg++; arg < pp->argc; arg++)
3306         if (pp->arg[arg].reg == NULL)
3307           break;
3308     }
3309   }
3310
3311   if (arg < pp->argc)
3312     return -1;
3313
3314   // now do it
3315   for (arg = 0; arg < pp->argc; arg++)
3316     if (pp->arg[arg].reg == NULL)
3317       break;
3318
3319   for (j = i; j > 0 && arg < pp->argc; )
3320   {
3321     j--;
3322
3323     if (ops[j].op == OP_PUSH)
3324     {
3325       ops[j].p_argnext = -1;
3326       ferr_assert(&ops[j], pp->arg[arg].datap == NULL);
3327       pp->arg[arg].datap = &ops[j];
3328
3329       if (ops[j].operand[0].type == OPT_REG)
3330         *regmask |= 1 << ops[j].operand[0].reg;
3331
3332       ops[j].flags |= OPF_RMD | OPF_DONE | OPF_FARGNR | OPF_FARG;
3333       ops[j].flags &= ~OPF_RSAVE;
3334
3335       // next arg
3336       for (arg++; arg < pp->argc; arg++)
3337         if (pp->arg[arg].reg == NULL)
3338           break;
3339     }
3340   }
3341
3342   return 0;
3343 }
3344
3345 static int collect_call_args_r(struct parsed_op *po, int i,
3346   struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3347   int *arg_grp, int arg, int magic, int need_op_saving, int may_reuse)
3348 {
3349   struct parsed_proto *pp_tmp;
3350   struct parsed_op *po_tmp;
3351   struct label_ref *lr;
3352   int need_to_save_current;
3353   int arg_grp_current = 0;
3354   int save_args_seen = 0;
3355   int save_args;
3356   int ret = 0;
3357   int reg;
3358   char buf[32];
3359   int j, k;
3360
3361   if (i < 0) {
3362     ferr(po, "dead label encountered\n");
3363     return -1;
3364   }
3365
3366   for (; arg < pp->argc; arg++)
3367     if (pp->arg[arg].reg == NULL)
3368       break;
3369   magic = (magic & 0xffffff) | (arg << 24);
3370
3371   for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
3372   {
3373     if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
3374       if (ops[j].cc_scratch != magic) {
3375         ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
3376            pp->name);
3377         return -1;
3378       }
3379       // ok: have already been here
3380       return 0;
3381     }
3382     ops[j].cc_scratch = magic;
3383
3384     if (g_labels[j] != NULL && g_label_refs[j].i != -1) {
3385       lr = &g_label_refs[j];
3386       if (lr->next != NULL)
3387         need_op_saving = 1;
3388       for (; lr->next; lr = lr->next) {
3389         check_i(&ops[j], lr->i);
3390         if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
3391           may_reuse = 1;
3392         ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3393                 arg_grp, arg, magic, need_op_saving, may_reuse);
3394         if (ret < 0)
3395           return ret;
3396       }
3397
3398       check_i(&ops[j], lr->i);
3399       if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
3400         may_reuse = 1;
3401       if (j > 0 && LAST_OP(j - 1)) {
3402         // follow last branch in reverse
3403         j = lr->i;
3404         continue;
3405       }
3406       need_op_saving = 1;
3407       ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3408                arg_grp, arg, magic, need_op_saving, may_reuse);
3409       if (ret < 0)
3410         return ret;
3411     }
3412     j--;
3413
3414     if (ops[j].op == OP_CALL)
3415     {
3416       if (pp->is_unresolved)
3417         break;
3418
3419       pp_tmp = ops[j].pp;
3420       if (pp_tmp == NULL)
3421         ferr(po, "arg collect hit unparsed call '%s'\n",
3422           ops[j].operand[0].name);
3423       if (may_reuse && pp_tmp->argc_stack > 0)
3424         ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
3425           arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
3426     }
3427     // esp adjust of 0 means we collected it before
3428     else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP
3429       && (ops[j].operand[1].type != OPT_CONST
3430           || ops[j].operand[1].val != 0))
3431     {
3432       if (pp->is_unresolved)
3433         break;
3434
3435       ferr(po, "arg collect %d/%d hit esp adjust of %d\n",
3436         arg, pp->argc, ops[j].operand[1].val);
3437     }
3438     else if (ops[j].op == OP_POP && !(ops[j].flags & OPF_DONE))
3439     {
3440       if (pp->is_unresolved)
3441         break;
3442
3443       ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
3444     }
3445     else if (ops[j].flags & OPF_CJMP)
3446     {
3447       if (pp->is_unresolved)
3448         break;
3449
3450       may_reuse = 1;
3451     }
3452     else if (ops[j].op == OP_PUSH
3453       && !(ops[j].flags & (OPF_FARGNR|OPF_DONE)))
3454     {
3455       if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
3456         break;
3457
3458       ops[j].p_argnext = -1;
3459       po_tmp = pp->arg[arg].datap;
3460       if (po_tmp != NULL)
3461         ops[j].p_argnext = po_tmp - ops;
3462       pp->arg[arg].datap = &ops[j];
3463
3464       need_to_save_current = 0;
3465       save_args = 0;
3466       reg = -1;
3467       if (ops[j].operand[0].type == OPT_REG)
3468         reg = ops[j].operand[0].reg;
3469
3470       if (!need_op_saving) {
3471         ret = scan_for_mod(&ops[j], j + 1, i, 1);
3472         need_to_save_current = (ret >= 0);
3473       }
3474       if (need_op_saving || need_to_save_current) {
3475         // mark this push as one that needs operand saving
3476         ops[j].flags &= ~OPF_RMD;
3477         if (ops[j].p_argnum == 0) {
3478           ops[j].p_argnum = arg + 1;
3479           save_args |= 1 << arg;
3480         }
3481         else if (ops[j].p_argnum < arg + 1) {
3482           // XXX: might kill valid var..
3483           //*save_arg_vars &= ~(1 << (ops[j].p_argnum - 1));
3484           ops[j].p_argnum = arg + 1;
3485           save_args |= 1 << arg;
3486         }
3487
3488         if (save_args_seen & (1 << (ops[j].p_argnum - 1))) {
3489           save_args_seen = 0;
3490           arg_grp_current++;
3491           if (arg_grp_current >= MAX_ARG_GRP)
3492             ferr(&ops[j], "out of arg groups (arg%d), f %s\n",
3493               ops[j].p_argnum, pp->name);
3494         }
3495       }
3496       else if (ops[j].p_argnum == 0)
3497         ops[j].flags |= OPF_RMD;
3498
3499       // some PUSHes are reused by different calls on other branches,
3500       // but that can't happen if we didn't branch, so they
3501       // can be removed from future searches (handles nested calls)
3502       if (!may_reuse)
3503         ops[j].flags |= OPF_FARGNR;
3504
3505       ops[j].flags |= OPF_FARG;
3506       ops[j].flags &= ~OPF_RSAVE;
3507
3508       // check for __VALIST
3509       if (!pp->is_unresolved && pp->arg[arg].type.is_va_list) {
3510         k = -1;
3511         ret = resolve_origin(j, &ops[j].operand[0],
3512                 magic + 1, &k, NULL);
3513         if (ret == 1 && k >= 0)
3514         {
3515           if (ops[k].op == OP_LEA) {
3516             snprintf(buf, sizeof(buf), "arg_%X",
3517               g_func_pp->argc_stack * 4);
3518             if (!g_func_pp->is_vararg
3519               || strstr(ops[k].operand[1].name, buf))
3520             {
3521               ops[k].flags |= OPF_RMD | OPF_DONE;
3522               ops[j].flags |= OPF_RMD | OPF_VAPUSH;
3523               save_args &= ~(1 << arg);
3524               reg = -1;
3525             }
3526             else
3527               ferr(&ops[j], "lea va_list used, but no vararg?\n");
3528           }
3529           // check for va_list from g_func_pp arg too
3530           else if (ops[k].op == OP_MOV
3531             && is_stack_access(&ops[k], &ops[k].operand[1]))
3532           {
3533             ret = stack_frame_access(&ops[k], &ops[k].operand[1],
3534               buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
3535             if (ret >= 0) {
3536               ops[k].flags |= OPF_RMD | OPF_DONE;
3537               ops[j].flags |= OPF_RMD;
3538               ops[j].p_argpass = ret + 1;
3539               save_args &= ~(1 << arg);
3540               reg = -1;
3541             }
3542           }
3543         }
3544       }
3545
3546       *save_arg_vars |= save_args;
3547
3548       // tracking reg usage
3549       if (reg >= 0)
3550         *regmask |= 1 << reg;
3551
3552       arg++;
3553       if (!pp->is_unresolved) {
3554         // next arg
3555         for (; arg < pp->argc; arg++)
3556           if (pp->arg[arg].reg == NULL)
3557             break;
3558       }
3559       magic = (magic & 0xffffff) | (arg << 24);
3560     }
3561
3562     if (ops[j].p_arggrp > arg_grp_current) {
3563       save_args_seen = 0;
3564       arg_grp_current = ops[j].p_arggrp;
3565     }
3566     if (ops[j].p_argnum > 0)
3567       save_args_seen |= 1 << (ops[j].p_argnum - 1);
3568   }
3569
3570   if (arg < pp->argc) {
3571     ferr(po, "arg collect failed for '%s': %d/%d\n",
3572       pp->name, arg, pp->argc);
3573     return -1;
3574   }
3575
3576   if (arg_grp_current > *arg_grp)
3577     *arg_grp = arg_grp_current;
3578
3579   return arg;
3580 }
3581
3582 static int collect_call_args(struct parsed_op *po, int i,
3583   struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3584   int magic)
3585 {
3586   // arg group is for cases when pushes for
3587   // multiple funcs are going on
3588   struct parsed_op *po_tmp;
3589   int save_arg_vars_current = 0;
3590   int arg_grp = 0;
3591   int ret;
3592   int a;
3593
3594   ret = collect_call_args_r(po, i, pp, regmask,
3595           &save_arg_vars_current, &arg_grp, 0, magic, 0, 0);
3596   if (ret < 0)
3597     return ret;
3598
3599   if (arg_grp != 0) {
3600     // propagate arg_grp
3601     for (a = 0; a < pp->argc; a++) {
3602       if (pp->arg[a].reg != NULL)
3603         continue;
3604
3605       po_tmp = pp->arg[a].datap;
3606       while (po_tmp != NULL) {
3607         po_tmp->p_arggrp = arg_grp;
3608         if (po_tmp->p_argnext > 0)
3609           po_tmp = &ops[po_tmp->p_argnext];
3610         else
3611           po_tmp = NULL;
3612       }
3613     }
3614   }
3615   save_arg_vars[arg_grp] |= save_arg_vars_current;
3616
3617   if (pp->is_unresolved) {
3618     pp->argc += ret;
3619     pp->argc_stack += ret;
3620     for (a = 0; a < pp->argc; a++)
3621       if (pp->arg[a].type.name == NULL)
3622         pp->arg[a].type.name = strdup("int");
3623   }
3624
3625   return ret;
3626 }
3627
3628 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
3629 {
3630   int i;
3631
3632   for (i = 0; i < pp->argc; i++)
3633     if (pp->arg[i].reg == NULL)
3634       break;
3635
3636   if (pp->argc_stack)
3637     memmove(&pp->arg[i + 1], &pp->arg[i],
3638       sizeof(pp->arg[0]) * pp->argc_stack);
3639   memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
3640   pp->arg[i].reg = strdup(reg);
3641   pp->arg[i].type.name = strdup("int");
3642   pp->argc++;
3643   pp->argc_reg++;
3644 }
3645
3646 static void add_label_ref(struct label_ref *lr, int op_i)
3647 {
3648   struct label_ref *lr_new;
3649
3650   if (lr->i == -1) {
3651     lr->i = op_i;
3652     return;
3653   }
3654
3655   lr_new = calloc(1, sizeof(*lr_new));
3656   lr_new->i = op_i;
3657   lr_new->next = lr->next;
3658   lr->next = lr_new;
3659 }
3660
3661 static struct parsed_data *try_resolve_jumptab(int i, int opcnt)
3662 {
3663   struct parsed_op *po = &ops[i];
3664   struct parsed_data *pd;
3665   char label[NAMELEN], *p;
3666   int len, j, l;
3667
3668   p = strchr(po->operand[0].name, '[');
3669   if (p == NULL)
3670     return NULL;
3671
3672   len = p - po->operand[0].name;
3673   strncpy(label, po->operand[0].name, len);
3674   label[len] = 0;
3675
3676   for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3677     if (IS(g_func_pd[j].label, label)) {
3678       pd = &g_func_pd[j];
3679       break;
3680     }
3681   }
3682   if (pd == NULL)
3683     //ferr(po, "label '%s' not parsed?\n", label);
3684     return NULL;
3685
3686   if (pd->type != OPT_OFFSET)
3687     ferr(po, "label '%s' with non-offset data?\n", label);
3688
3689   // find all labels, link
3690   for (j = 0; j < pd->count; j++) {
3691     for (l = 0; l < opcnt; l++) {
3692       if (g_labels[l] != NULL && IS(g_labels[l], pd->d[j].u.label)) {
3693         add_label_ref(&g_label_refs[l], i);
3694         pd->d[j].bt_i = l;
3695         break;
3696       }
3697     }
3698   }
3699
3700   return pd;
3701 }
3702
3703 static void clear_labels(int count)
3704 {
3705   int i;
3706
3707   for (i = 0; i < count; i++) {
3708     if (g_labels[i] != NULL) {
3709       free(g_labels[i]);
3710       g_labels[i] = NULL;
3711     }
3712   }
3713 }
3714
3715 static void output_std_flags(FILE *fout, struct parsed_op *po,
3716   int *pfomask, const char *dst_opr_text)
3717 {
3718   if (*pfomask & (1 << PFO_Z)) {
3719     fprintf(fout, "\n  cond_z = (%s%s == 0);",
3720       lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
3721     *pfomask &= ~(1 << PFO_Z);
3722   }
3723   if (*pfomask & (1 << PFO_S)) {
3724     fprintf(fout, "\n  cond_s = (%s%s < 0);",
3725       lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
3726     *pfomask &= ~(1 << PFO_S);
3727   }
3728 }
3729
3730 enum {
3731   OPP_FORCE_NORETURN = (1 << 0),
3732   OPP_SIMPLE_ARGS    = (1 << 1),
3733   OPP_ALIGN          = (1 << 2),
3734 };
3735
3736 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
3737   int flags)
3738 {
3739   const char *cconv = "";
3740
3741   if (pp->is_fastcall)
3742     cconv = "__fastcall ";
3743   else if (pp->is_stdcall && pp->argc_reg == 0)
3744     cconv = "__stdcall ";
3745
3746   fprintf(fout, (flags & OPP_ALIGN) ? "%-16s" : "%s", cconv);
3747
3748   if (pp->is_noreturn || (flags & OPP_FORCE_NORETURN))
3749     fprintf(fout, "noreturn ");
3750 }
3751
3752 static void output_pp(FILE *fout, const struct parsed_proto *pp,
3753   int flags)
3754 {
3755   int i;
3756
3757   fprintf(fout, (flags & OPP_ALIGN) ? "%-5s" : "%s ",
3758     pp->ret_type.name);
3759   if (pp->is_fptr)
3760     fprintf(fout, "(");
3761   output_pp_attrs(fout, pp, flags);
3762   if (pp->is_fptr)
3763     fprintf(fout, "*");
3764   fprintf(fout, "%s", pp->name);
3765   if (pp->is_fptr)
3766     fprintf(fout, ")");
3767
3768   fprintf(fout, "(");
3769   for (i = 0; i < pp->argc; i++) {
3770     if (i > 0)
3771       fprintf(fout, ", ");
3772     if (pp->arg[i].fptr != NULL && !(flags & OPP_SIMPLE_ARGS)) {
3773       // func pointer
3774       output_pp(fout, pp->arg[i].fptr, 0);
3775     }
3776     else if (pp->arg[i].type.is_retreg) {
3777       fprintf(fout, "u32 *r_%s", pp->arg[i].reg);
3778     }
3779     else {
3780       fprintf(fout, "%s", pp->arg[i].type.name);
3781       if (!pp->is_fptr)
3782         fprintf(fout, " a%d", i + 1);
3783     }
3784   }
3785   if (pp->is_vararg) {
3786     if (i > 0)
3787       fprintf(fout, ", ");
3788     fprintf(fout, "...");
3789   }
3790   fprintf(fout, ")");
3791 }
3792
3793 static int get_pp_arg_regmask(const struct parsed_proto *pp)
3794 {
3795   int regmask = 0;
3796   int i, reg;
3797
3798   for (i = 0; i < pp->argc; i++) {
3799     if (pp->arg[i].reg != NULL) {
3800       reg = char_array_i(regs_r32,
3801               ARRAY_SIZE(regs_r32), pp->arg[i].reg);
3802       if (reg < 0)
3803         ferr(ops, "arg '%s' of func '%s' is not a reg?\n",
3804           pp->arg[i].reg, pp->name);
3805       regmask |= 1 << reg;
3806     }
3807   }
3808
3809   return regmask;
3810 }
3811
3812 static char *saved_arg_name(char *buf, size_t buf_size, int grp, int num)
3813 {
3814   char buf1[16];
3815
3816   buf1[0] = 0;
3817   if (grp > 0)
3818     snprintf(buf1, sizeof(buf1), "%d", grp);
3819   snprintf(buf, buf_size, "s%s_a%d", buf1, num);
3820
3821   return buf;
3822 }
3823
3824 static void gen_x_cleanup(int opcnt);
3825
3826 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
3827 {
3828   struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
3829   struct parsed_opr *last_arith_dst = NULL;
3830   char buf1[256], buf2[256], buf3[256], cast[64];
3831   const struct parsed_proto *pp_c;
3832   struct parsed_proto *pp, *pp_tmp;
3833   struct parsed_data *pd;
3834   const char *tmpname;
3835   unsigned int uval;
3836   int save_arg_vars[MAX_ARG_GRP] = { 0, };
3837   int cond_vars = 0;
3838   int need_tmp_var = 0;
3839   int need_tmp64 = 0;
3840   int had_decl = 0;
3841   int label_pending = 0;
3842   int regmask_save = 0; // regs saved/restored in this func
3843   int regmask_arg = 0;  // regs carrying function args (fastcall, etc)
3844   int regmask_now;      // temp
3845   int regmask_init = 0; // regs that need zero initialization
3846   int regmask_pp = 0;   // regs used in complex push-pop graph
3847   int regmask = 0;      // used regs
3848   int pfomask = 0;
3849   int found = 0;
3850   int depth = 0;
3851   int no_output;
3852   int i, j, l;
3853   int arg;
3854   int reg;
3855   int ret;
3856
3857   g_bp_frame = g_sp_frame = g_stack_fsz = 0;
3858   g_stack_frame_used = 0;
3859
3860   g_func_pp = proto_parse(fhdr, funcn, 0);
3861   if (g_func_pp == NULL)
3862     ferr(ops, "proto_parse failed for '%s'\n", funcn);
3863
3864   regmask_arg = get_pp_arg_regmask(g_func_pp);
3865
3866   // pass1:
3867   // - handle ebp/esp frame, remove ops related to it
3868   scan_prologue_epilogue(opcnt);
3869
3870   // pass2:
3871   // - parse calls with labels
3872   // - resolve all branches
3873   for (i = 0; i < opcnt; i++)
3874   {
3875     po = &ops[i];
3876     po->bt_i = -1;
3877     po->btj = NULL;
3878
3879     if (po->flags & (OPF_RMD|OPF_DONE))
3880       continue;
3881
3882     if (po->op == OP_CALL) {
3883       pp = NULL;
3884
3885       if (po->operand[0].type == OPT_LABEL) {
3886         tmpname = opr_name(po, 0);
3887         if (IS_START(tmpname, "loc_"))
3888           ferr(po, "call to loc_*\n");
3889         pp_c = proto_parse(fhdr, tmpname, 0);
3890         if (pp_c == NULL)
3891           ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3892
3893         pp = proto_clone(pp_c);
3894         my_assert_not(pp, NULL);
3895       }
3896       else if (po->datap != NULL) {
3897         pp = calloc(1, sizeof(*pp));
3898         my_assert_not(pp, NULL);
3899
3900         ret = parse_protostr(po->datap, pp);
3901         if (ret < 0)
3902           ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3903         free(po->datap);
3904         po->datap = NULL;
3905       }
3906
3907       if (pp != NULL) {
3908         if (pp->is_fptr)
3909           check_func_pp(po, pp, "fptr var call");
3910         if (pp->is_noreturn)
3911           po->flags |= OPF_TAIL;
3912       }
3913       po->pp = pp;
3914       continue;
3915     }
3916
3917     if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3918       continue;
3919
3920     if (po->operand[0].type == OPT_REGMEM) {
3921       pd = try_resolve_jumptab(i, opcnt);
3922       if (pd == NULL)
3923         goto tailcall;
3924
3925       po->btj = pd;
3926       continue;
3927     }
3928
3929     for (l = 0; l < opcnt; l++) {
3930       if (g_labels[l] != NULL
3931           && IS(po->operand[0].name, g_labels[l]))
3932       {
3933         if (l == i + 1 && po->op == OP_JMP) {
3934           // yet another alignment type..
3935           po->flags |= OPF_RMD|OPF_DONE;
3936           break;
3937         }
3938         add_label_ref(&g_label_refs[l], i);
3939         po->bt_i = l;
3940         break;
3941       }
3942     }
3943
3944     if (po->bt_i != -1 || (po->flags & OPF_RMD))
3945       continue;
3946
3947     if (po->operand[0].type == OPT_LABEL)
3948       // assume tail call
3949       goto tailcall;
3950
3951     ferr(po, "unhandled branch\n");
3952
3953 tailcall:
3954     po->op = OP_CALL;
3955     po->flags |= OPF_TAIL;
3956     if (i > 0 && ops[i - 1].op == OP_POP)
3957       po->flags |= OPF_ATAIL;
3958     i--; // reprocess
3959   }
3960
3961   // pass3:
3962   // - remove dead labels
3963   // - process trivial calls
3964   for (i = 0; i < opcnt; i++)
3965   {
3966     if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
3967       free(g_labels[i]);
3968       g_labels[i] = NULL;
3969     }
3970
3971     po = &ops[i];
3972     if (po->flags & (OPF_RMD|OPF_DONE))
3973       continue;
3974
3975     if (po->op == OP_CALL)
3976     {
3977       pp = process_call_early(i, opcnt, &j);
3978       if (pp != NULL) {
3979         if (!(po->flags & OPF_ATAIL))
3980           // since we know the args, try to collect them
3981           if (collect_call_args_early(po, i, pp, &regmask) != 0)
3982             pp = NULL;
3983       }
3984
3985       if (pp != NULL) {
3986         if (j >= 0) {
3987           // commit esp adjust
3988           ops[j].flags |= OPF_RMD;
3989           if (ops[j].op != OP_POP)
3990             patch_esp_adjust(&ops[j], pp->argc_stack * 4);
3991           else
3992             ops[j].flags |= OPF_DONE;
3993         }
3994
3995         if (strstr(pp->ret_type.name, "int64"))
3996           need_tmp64 = 1;
3997
3998         po->flags |= OPF_DONE;
3999       }
4000     }
4001   }
4002
4003   // pass4:
4004   // - process calls
4005   // - handle push <const>/pop pairs
4006   for (i = 0; i < opcnt; i++)
4007   {
4008     po = &ops[i];
4009     if (po->flags & (OPF_RMD|OPF_DONE))
4010       continue;
4011
4012     if (po->op == OP_CALL && !(po->flags & OPF_DONE))
4013     {
4014       pp = process_call(i, opcnt);
4015
4016       if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
4017         // since we know the args, collect them
4018         collect_call_args(po, i, pp, &regmask, save_arg_vars,
4019           i + opcnt * 2);
4020       }
4021
4022       if (strstr(pp->ret_type.name, "int64"))
4023         need_tmp64 = 1;
4024     }
4025     else if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4026       && !(po->flags & OPF_RSAVE) && po->operand[0].type == OPT_CONST)
4027         scan_for_pop_const(i, opcnt, &regmask_pp);
4028   }
4029
4030   // pass5:
4031   // - find POPs for PUSHes, rm both
4032   // - scan for STD/CLD, propagate DF
4033   // - scan for all used registers
4034   // - find flag set ops for their users
4035   // - do unreselved calls
4036   // - declare indirect functions
4037   for (i = 0; i < opcnt; i++)
4038   {
4039     po = &ops[i];
4040     if (po->flags & (OPF_RMD|OPF_DONE))
4041       continue;
4042
4043     if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
4044       reg = po->operand[0].reg;
4045       if (!(regmask & (1 << reg)))
4046         // not a reg save after all, rerun scan_for_pop
4047         po->flags &= ~OPF_RSAVE;
4048       else
4049         regmask_save |= 1 << reg;
4050     }
4051
4052     if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4053       && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
4054     {
4055       if (po->operand[0].type == OPT_REG)
4056       {
4057         reg = po->operand[0].reg;
4058         if (reg < 0)
4059           ferr(po, "reg not set for push?\n");
4060
4061         depth = 0;
4062         ret = scan_for_pop(i + 1, opcnt,
4063                 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
4064         if (ret == 1) {
4065           if (depth > 1)
4066             ferr(po, "too much depth: %d\n", depth);
4067
4068           po->flags |= OPF_RMD;
4069           scan_for_pop(i + 1, opcnt, po->operand[0].name,
4070             i + opcnt * 4, 0, &depth, 1);
4071           continue;
4072         }
4073         ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
4074         if (ret == 0) {
4075           arg = OPF_RMD;
4076           if (regmask & (1 << reg)) {
4077             if (regmask_save & (1 << reg))
4078               ferr(po, "%s already saved?\n", po->operand[0].name);
4079             arg = OPF_RSAVE;
4080           }
4081           po->flags |= arg;
4082           scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
4083           continue;
4084         }
4085       }
4086     }
4087
4088     if (po->op == OP_STD) {
4089       po->flags |= OPF_DF | OPF_RMD | OPF_DONE;
4090       scan_propagate_df(i + 1, opcnt);
4091     }
4092
4093     regmask_now = po->regmask_src | po->regmask_dst;
4094     if (regmask_now & (1 << xBP)) {
4095       if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
4096         if (po->regmask_dst & (1 << xBP))
4097           // compiler decided to drop bp frame and use ebp as scratch
4098           scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
4099         else
4100           regmask_now &= ~(1 << xBP);
4101       }
4102     }
4103
4104     regmask |= regmask_now;
4105
4106     if (po->flags & OPF_CC)
4107     {
4108       int setters[16], cnt = 0, branched = 0;
4109
4110       ret = scan_for_flag_set(i, i + opcnt * 6,
4111               &branched, setters, &cnt);
4112       if (ret < 0 || cnt <= 0)
4113         ferr(po, "unable to trace flag setter(s)\n");
4114       if (cnt > ARRAY_SIZE(setters))
4115         ferr(po, "too many flag setters\n");
4116
4117       for (j = 0; j < cnt; j++)
4118       {
4119         tmp_op = &ops[setters[j]]; // flag setter
4120         pfomask = 0;
4121
4122         // to get nicer code, we try to delay test and cmp;
4123         // if we can't because of operand modification, or if we
4124         // have arith op, or branch, make it calculate flags explicitly
4125         if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
4126         {
4127           if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
4128             pfomask = 1 << po->pfo;
4129         }
4130         else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
4131           pfomask = 1 << po->pfo;
4132         }
4133         else {
4134           // see if we'll be able to handle based on op result
4135           if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
4136                && po->pfo != PFO_Z && po->pfo != PFO_S
4137                && po->pfo != PFO_P)
4138               || branched
4139               || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
4140           {
4141             pfomask = 1 << po->pfo;
4142           }
4143
4144           if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
4145             propagate_lmod(tmp_op, &tmp_op->operand[0],
4146               &tmp_op->operand[1]);
4147             if (tmp_op->operand[0].lmod == OPLM_DWORD)
4148               need_tmp64 = 1;
4149           }
4150         }
4151         if (pfomask) {
4152           tmp_op->pfomask |= pfomask;
4153           cond_vars |= pfomask;
4154         }
4155         // note: may overwrite, currently not a problem
4156         po->datap = tmp_op;
4157       }
4158
4159       if (po->op == OP_RCL || po->op == OP_RCR
4160        || po->op == OP_ADC || po->op == OP_SBB)
4161         cond_vars |= 1 << PFO_C;
4162     }
4163
4164     if (po->op == OP_CMPS || po->op == OP_SCAS) {
4165       cond_vars |= 1 << PFO_Z;
4166     }
4167     else if (po->op == OP_MUL
4168       || (po->op == OP_IMUL && po->operand_cnt == 1))
4169     {
4170       if (po->operand[0].lmod == OPLM_DWORD)
4171         need_tmp64 = 1;
4172     }
4173     else if (po->op == OP_CALL) {
4174       // note: resolved non-reg calls are OPF_DONE already
4175       pp = po->pp;
4176       if (pp == NULL)
4177         ferr(po, "NULL pp\n");
4178
4179       if (pp->is_unresolved) {
4180         int regmask_stack = 0;
4181         collect_call_args(po, i, pp, &regmask, save_arg_vars,
4182           i + opcnt * 2);
4183
4184         // this is pretty rough guess:
4185         // see ecx and edx were pushed (and not their saved versions)
4186         for (arg = 0; arg < pp->argc; arg++) {
4187           if (pp->arg[arg].reg != NULL)
4188             continue;
4189
4190           tmp_op = pp->arg[arg].datap;
4191           if (tmp_op == NULL)
4192             ferr(po, "parsed_op missing for arg%d\n", arg);
4193           if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
4194             regmask_stack |= 1 << tmp_op->operand[0].reg;
4195         }
4196
4197         if (!((regmask_stack & (1 << xCX))
4198           && (regmask_stack & (1 << xDX))))
4199         {
4200           if (pp->argc_stack != 0
4201            || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
4202           {
4203             pp_insert_reg_arg(pp, "ecx");
4204             pp->is_fastcall = 1;
4205             regmask_init |= 1 << xCX;
4206             regmask |= 1 << xCX;
4207           }
4208           if (pp->argc_stack != 0
4209            || ((regmask | regmask_arg) & (1 << xDX)))
4210           {
4211             pp_insert_reg_arg(pp, "edx");
4212             regmask_init |= 1 << xDX;
4213             regmask |= 1 << xDX;
4214           }
4215         }
4216
4217         // note: __cdecl doesn't fall into is_unresolved category
4218         if (pp->argc_stack > 0)
4219           pp->is_stdcall = 1;
4220       }
4221
4222       for (arg = 0; arg < pp->argc; arg++) {
4223         if (pp->arg[arg].reg != NULL) {
4224           reg = char_array_i(regs_r32,
4225                   ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
4226           if (reg < 0)
4227             ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
4228           if (!(regmask & (1 << reg))) {
4229             regmask_init |= 1 << reg;
4230             regmask |= 1 << reg;
4231           }
4232         }
4233       }
4234     }
4235     else if (po->op == OP_MOV && po->operand[0].pp != NULL
4236       && po->operand[1].pp != NULL)
4237     {
4238       // <var> = offset <something>
4239       if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
4240         && !IS_START(po->operand[1].name, "off_"))
4241       {
4242         if (!po->operand[0].pp->is_fptr)
4243           ferr(po, "%s not declared as fptr when it should be\n",
4244             po->operand[0].name);
4245         if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
4246           pp_print(buf1, sizeof(buf1), po->operand[0].pp);
4247           pp_print(buf2, sizeof(buf2), po->operand[1].pp);
4248           fnote(po, "var:  %s\n", buf1);
4249           fnote(po, "func: %s\n", buf2);
4250           ferr(po, "^ mismatch\n");
4251         }
4252       }
4253     }
4254     else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
4255       regmask |= 1 << xAX;
4256     else if (po->op == OP_DIV || po->op == OP_IDIV) {
4257       // 32bit division is common, look for it
4258       if (po->op == OP_DIV)
4259         ret = scan_for_reg_clear(i, xDX);
4260       else
4261         ret = scan_for_cdq_edx(i);
4262       if (ret >= 0)
4263         po->flags |= OPF_32BIT;
4264       else
4265         need_tmp64 = 1;
4266     }
4267     else if (po->op == OP_CLD)
4268       po->flags |= OPF_RMD | OPF_DONE;
4269
4270     if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
4271       need_tmp_var = 1;
4272     }
4273   }
4274
4275   // pass6:
4276   // - confirm regmask_save, it might have been reduced
4277   if (regmask_save != 0)
4278   {
4279     regmask_save = 0;
4280     for (i = 0; i < opcnt; i++) {
4281       po = &ops[i];
4282       if (po->flags & OPF_RMD)
4283         continue;
4284
4285       if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
4286         regmask_save |= 1 << po->operand[0].reg;
4287     }
4288   }
4289
4290   // output starts here
4291
4292   // define userstack size
4293   if (g_func_pp->is_userstack) {
4294     fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
4295     fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
4296     fprintf(fout, "#endif\n");
4297   }
4298
4299   // the function itself
4300   ferr_assert(ops, !g_func_pp->is_fptr);
4301   output_pp(fout, g_func_pp,
4302     (g_ida_func_attr & IDAFA_NORETURN) ? OPP_FORCE_NORETURN : 0);
4303   fprintf(fout, "\n{\n");
4304
4305   // declare indirect functions
4306   for (i = 0; i < opcnt; i++) {
4307     po = &ops[i];
4308     if (po->flags & OPF_RMD)
4309       continue;
4310
4311     if (po->op == OP_CALL) {
4312       pp = po->pp;
4313       if (pp == NULL)
4314         ferr(po, "NULL pp\n");
4315
4316       if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
4317         if (pp->name[0] != 0) {
4318           memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
4319           memcpy(pp->name, "i_", 2);
4320
4321           // might be declared already
4322           found = 0;
4323           for (j = 0; j < i; j++) {
4324             if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
4325               if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
4326                 found = 1;
4327                 break;
4328               }
4329             }
4330           }
4331           if (found)
4332             continue;
4333         }
4334         else
4335           snprintf(pp->name, sizeof(pp->name), "icall%d", i);
4336
4337         fprintf(fout, "  ");
4338         output_pp(fout, pp, OPP_SIMPLE_ARGS);
4339         fprintf(fout, ";\n");
4340       }
4341     }
4342   }
4343
4344   // output LUTs/jumptables
4345   for (i = 0; i < g_func_pd_cnt; i++) {
4346     pd = &g_func_pd[i];
4347     fprintf(fout, "  static const ");
4348     if (pd->type == OPT_OFFSET) {
4349       fprintf(fout, "void *jt_%s[] =\n    { ", pd->label);
4350
4351       for (j = 0; j < pd->count; j++) {
4352         if (j > 0)
4353           fprintf(fout, ", ");
4354         fprintf(fout, "&&%s", pd->d[j].u.label);
4355       }
4356     }
4357     else {
4358       fprintf(fout, "%s %s[] =\n    { ",
4359         lmod_type_u(ops, pd->lmod), pd->label);
4360
4361       for (j = 0; j < pd->count; j++) {
4362         if (j > 0)
4363           fprintf(fout, ", ");
4364         fprintf(fout, "%u", pd->d[j].u.val);
4365       }
4366     }
4367     fprintf(fout, " };\n");
4368     had_decl = 1;
4369   }
4370
4371   // declare stack frame, va_arg
4372   if (g_stack_fsz) {
4373     fprintf(fout, "  union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
4374       (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
4375     had_decl = 1;
4376   }
4377
4378   if (g_func_pp->is_userstack) {
4379     fprintf(fout, "  u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
4380     fprintf(fout, "  u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
4381     had_decl = 1;
4382   }
4383
4384   if (g_func_pp->is_vararg) {
4385     fprintf(fout, "  va_list ap;\n");
4386     had_decl = 1;
4387   }
4388
4389   // declare arg-registers
4390   for (i = 0; i < g_func_pp->argc; i++) {
4391     if (g_func_pp->arg[i].reg != NULL) {
4392       reg = char_array_i(regs_r32,
4393               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
4394       if (regmask & (1 << reg)) {
4395         if (g_func_pp->arg[i].type.is_retreg)
4396           fprintf(fout, "  u32 %s = *r_%s;\n",
4397             g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
4398         else
4399           fprintf(fout, "  u32 %s = (u32)a%d;\n",
4400             g_func_pp->arg[i].reg, i + 1);
4401       }
4402       else {
4403         if (g_func_pp->arg[i].type.is_retreg)
4404           ferr(ops, "retreg '%s' is unused?\n",
4405             g_func_pp->arg[i].reg);
4406         fprintf(fout, "  // %s = a%d; // unused\n",
4407           g_func_pp->arg[i].reg, i + 1);
4408       }
4409       had_decl = 1;
4410     }
4411   }
4412
4413   // declare normal registers
4414   regmask_now = regmask & ~regmask_arg;
4415   regmask_now &= ~(1 << xSP);
4416   if (regmask_now & 0x00ff) {
4417     for (reg = 0; reg < 8; reg++) {
4418       if (regmask_now & (1 << reg)) {
4419         fprintf(fout, "  u32 %s", regs_r32[reg]);
4420         if (regmask_init & (1 << reg))
4421           fprintf(fout, " = 0");
4422         fprintf(fout, ";\n");
4423         had_decl = 1;
4424       }
4425     }
4426   }
4427   if (regmask_now & 0xff00) {
4428     for (reg = 8; reg < 16; reg++) {
4429       if (regmask_now & (1 << reg)) {
4430         fprintf(fout, "  mmxr %s", regs_r32[reg]);
4431         if (regmask_init & (1 << reg))
4432           fprintf(fout, " = { 0, }");
4433         fprintf(fout, ";\n");
4434         had_decl = 1;
4435       }
4436     }
4437   }
4438
4439   if (regmask_save) {
4440     for (reg = 0; reg < 8; reg++) {
4441       if (regmask_save & (1 << reg)) {
4442         fprintf(fout, "  u32 s_%s;\n", regs_r32[reg]);
4443         had_decl = 1;
4444       }
4445     }
4446   }
4447
4448   for (i = 0; i < ARRAY_SIZE(save_arg_vars); i++) {
4449     if (save_arg_vars[i] == 0)
4450       continue;
4451     for (reg = 0; reg < 32; reg++) {
4452       if (save_arg_vars[i] & (1 << reg)) {
4453         fprintf(fout, "  u32 %s;\n",
4454           saved_arg_name(buf1, sizeof(buf1), i, reg + 1));
4455         had_decl = 1;
4456       }
4457     }
4458   }
4459
4460   // declare push-pop temporaries
4461   if (regmask_pp) {
4462     for (reg = 0; reg < 8; reg++) {
4463       if (regmask_pp & (1 << reg)) {
4464         fprintf(fout, "  u32 pp_%s;\n", regs_r32[reg]);
4465         had_decl = 1;
4466       }
4467     }
4468   }
4469
4470   if (cond_vars) {
4471     for (i = 0; i < 8; i++) {
4472       if (cond_vars & (1 << i)) {
4473         fprintf(fout, "  u32 cond_%s;\n", parsed_flag_op_names[i]);
4474         had_decl = 1;
4475       }
4476     }
4477   }
4478
4479   if (need_tmp_var) {
4480     fprintf(fout, "  u32 tmp;\n");
4481     had_decl = 1;
4482   }
4483
4484   if (need_tmp64) {
4485     fprintf(fout, "  u64 tmp64;\n");
4486     had_decl = 1;
4487   }
4488
4489   if (had_decl)
4490     fprintf(fout, "\n");
4491
4492   if (g_func_pp->is_vararg) {
4493     if (g_func_pp->argc_stack == 0)
4494       ferr(ops, "vararg func without stack args?\n");
4495     fprintf(fout, "  va_start(ap, a%d);\n", g_func_pp->argc);
4496   }
4497
4498   // output ops
4499   for (i = 0; i < opcnt; i++)
4500   {
4501     if (g_labels[i] != NULL) {
4502       fprintf(fout, "\n%s:\n", g_labels[i]);
4503       label_pending = 1;
4504
4505       delayed_flag_op = NULL;
4506       last_arith_dst = NULL;
4507     }
4508
4509     po = &ops[i];
4510     if (po->flags & OPF_RMD)
4511       continue;
4512
4513     no_output = 0;
4514
4515     #define assert_operand_cnt(n_) \
4516       if (po->operand_cnt != n_) \
4517         ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
4518
4519     // conditional/flag using op?
4520     if (po->flags & OPF_CC)
4521     {
4522       int is_delayed = 0;
4523
4524       tmp_op = po->datap;
4525
4526       // we go through all this trouble to avoid using parsed_flag_op,
4527       // which makes generated code much nicer
4528       if (delayed_flag_op != NULL)
4529       {
4530         out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
4531           po->pfo, po->pfo_inv);
4532         is_delayed = 1;
4533       }
4534       else if (last_arith_dst != NULL
4535         && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
4536            || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
4537            ))
4538       {
4539         out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4540         out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
4541           last_arith_dst->lmod, buf3);
4542         is_delayed = 1;
4543       }
4544       else if (tmp_op != NULL) {
4545         // use preprocessed flag calc results
4546         if (!(tmp_op->pfomask & (1 << po->pfo)))
4547           ferr(po, "not prepared for pfo %d\n", po->pfo);
4548
4549         // note: pfo_inv was not yet applied
4550         snprintf(buf1, sizeof(buf1), "(%scond_%s)",
4551           po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
4552       }
4553       else {
4554         ferr(po, "all methods of finding comparison failed\n");
4555       }
4556  
4557       if (po->flags & OPF_JMP) {
4558         fprintf(fout, "  if %s", buf1);
4559       }
4560       else if (po->op == OP_RCL || po->op == OP_RCR
4561                || po->op == OP_ADC || po->op == OP_SBB)
4562       {
4563         if (is_delayed)
4564           fprintf(fout, "  cond_%s = %s;\n",
4565             parsed_flag_op_names[po->pfo], buf1);
4566       }
4567       else if (po->flags & OPF_DATA) { // SETcc
4568         out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
4569         fprintf(fout, "  %s = %s;", buf2, buf1);
4570       }
4571       else {
4572         ferr(po, "unhandled conditional op\n");
4573       }
4574     }
4575
4576     pfomask = po->pfomask;
4577
4578     if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
4579       struct parsed_opr opr = {0,};
4580       opr.type = OPT_REG;
4581       opr.reg = xCX;
4582       opr.lmod = OPLM_DWORD;
4583       ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
4584
4585       if (ret != 1 || uval == 0) {
4586         // we need initial flags for ecx=0 case..
4587         if (i > 0 && ops[i - 1].op == OP_XOR
4588           && IS(ops[i - 1].operand[0].name,
4589                 ops[i - 1].operand[1].name))
4590         {
4591           fprintf(fout, "  cond_z = ");
4592           if (pfomask & (1 << PFO_C))
4593             fprintf(fout, "cond_c = ");
4594           fprintf(fout, "0;\n");
4595         }
4596         else if (last_arith_dst != NULL) {
4597           out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4598           out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
4599             last_arith_dst->lmod, buf3);
4600           fprintf(fout, "  cond_z = %s;\n", buf1);
4601         }
4602         else
4603           ferr(po, "missing initial ZF\n");
4604       }
4605     }
4606
4607     switch (po->op)
4608     {
4609       case OP_MOV:
4610         assert_operand_cnt(2);
4611         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4612         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4613         default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
4614         fprintf(fout, "  %s = %s;", buf1,
4615             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4616               buf3, 0));
4617         break;
4618
4619       case OP_LEA:
4620         assert_operand_cnt(2);
4621         po->operand[1].lmod = OPLM_DWORD; // always
4622         fprintf(fout, "  %s = %s;",
4623             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4624             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4625               NULL, 1));
4626         break;
4627
4628       case OP_MOVZX:
4629         assert_operand_cnt(2);
4630         fprintf(fout, "  %s = %s;",
4631             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4632             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4633         break;
4634
4635       case OP_MOVSX:
4636         assert_operand_cnt(2);
4637         switch (po->operand[1].lmod) {
4638         case OPLM_BYTE:
4639           strcpy(buf3, "(s8)");
4640           break;
4641         case OPLM_WORD:
4642           strcpy(buf3, "(s16)");
4643           break;
4644         default:
4645           ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
4646         }
4647         fprintf(fout, "  %s = %s;",
4648             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4649             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4650               buf3, 0));
4651         break;
4652
4653       case OP_XCHG:
4654         assert_operand_cnt(2);
4655         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4656         fprintf(fout, "  tmp = %s;",
4657           out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
4658         fprintf(fout, " %s = %s;",
4659           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4660           out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4661             default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4662         fprintf(fout, " %s = %stmp;",
4663           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
4664           default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
4665         snprintf(g_comment, sizeof(g_comment), "xchg");
4666         break;
4667
4668       case OP_NOT:
4669         assert_operand_cnt(1);
4670         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4671         fprintf(fout, "  %s = ~%s;", buf1, buf1);
4672         break;
4673
4674       case OP_CDQ:
4675         assert_operand_cnt(2);
4676         fprintf(fout, "  %s = (s32)%s >> 31;",
4677             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4678             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4679         strcpy(g_comment, "cdq");
4680         break;
4681
4682       case OP_LODS:
4683         assert_operand_cnt(3);
4684         if (po->flags & OPF_REP) {
4685           // hmh..
4686           ferr(po, "TODO\n");
4687         }
4688         else {
4689           fprintf(fout, "  eax = %sesi; esi %c= %d;",
4690             lmod_cast_u_ptr(po, po->operand[0].lmod),
4691             (po->flags & OPF_DF) ? '-' : '+',
4692             lmod_bytes(po, po->operand[0].lmod));
4693           strcpy(g_comment, "lods");
4694         }
4695         break;
4696
4697       case OP_STOS:
4698         assert_operand_cnt(3);
4699         if (po->flags & OPF_REP) {
4700           fprintf(fout, "  for (; ecx != 0; ecx--, edi %c= %d)\n",
4701             (po->flags & OPF_DF) ? '-' : '+',
4702             lmod_bytes(po, po->operand[0].lmod));
4703           fprintf(fout, "    %sedi = eax;",
4704             lmod_cast_u_ptr(po, po->operand[0].lmod));
4705           strcpy(g_comment, "rep stos");
4706         }
4707         else {
4708           fprintf(fout, "  %sedi = eax; edi %c= %d;",
4709             lmod_cast_u_ptr(po, po->operand[0].lmod),
4710             (po->flags & OPF_DF) ? '-' : '+',
4711             lmod_bytes(po, po->operand[0].lmod));
4712           strcpy(g_comment, "stos");
4713         }
4714         break;
4715
4716       case OP_MOVS:
4717         assert_operand_cnt(3);
4718         j = lmod_bytes(po, po->operand[0].lmod);
4719         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4720         l = (po->flags & OPF_DF) ? '-' : '+';
4721         if (po->flags & OPF_REP) {
4722           fprintf(fout,
4723             "  for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
4724             l, j, l, j);
4725           fprintf(fout,
4726             "    %sedi = %sesi;", buf1, buf1);
4727           strcpy(g_comment, "rep movs");
4728         }
4729         else {
4730           fprintf(fout, "  %sedi = %sesi; edi %c= %d; esi %c= %d;",
4731             buf1, buf1, l, j, l, j);
4732           strcpy(g_comment, "movs");
4733         }
4734         break;
4735
4736       case OP_CMPS:
4737         // repe ~ repeat while ZF=1
4738         assert_operand_cnt(3);
4739         j = lmod_bytes(po, po->operand[0].lmod);
4740         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4741         l = (po->flags & OPF_DF) ? '-' : '+';
4742         if (po->flags & OPF_REP) {
4743           fprintf(fout,
4744             "  for (; ecx != 0; ecx--) {\n");
4745           if (pfomask & (1 << PFO_C)) {
4746             // ugh..
4747             fprintf(fout,
4748             "    cond_c = %sesi < %sedi;\n", buf1, buf1);
4749             pfomask &= ~(1 << PFO_C);
4750           }
4751           fprintf(fout,
4752             "    cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
4753               buf1, buf1, l, j, l, j);
4754           fprintf(fout,
4755             "    if (cond_z %s 0) break;\n",
4756               (po->flags & OPF_REPZ) ? "==" : "!=");
4757           fprintf(fout,
4758             "  }");
4759           snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
4760             (po->flags & OPF_REPZ) ? "e" : "ne");
4761         }
4762         else {
4763           fprintf(fout,
4764             "  cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
4765             buf1, buf1, l, j, l, j);
4766           strcpy(g_comment, "cmps");
4767         }
4768         pfomask &= ~(1 << PFO_Z);
4769         last_arith_dst = NULL;
4770         delayed_flag_op = NULL;
4771         break;
4772
4773       case OP_SCAS:
4774         // only does ZF (for now)
4775         // repe ~ repeat while ZF=1
4776         assert_operand_cnt(3);
4777         j = lmod_bytes(po, po->operand[0].lmod);
4778         l = (po->flags & OPF_DF) ? '-' : '+';
4779         if (po->flags & OPF_REP) {
4780           fprintf(fout,
4781             "  for (; ecx != 0; ecx--) {\n");
4782           fprintf(fout,
4783             "    cond_z = (%seax == %sedi); edi %c= %d;\n",
4784               lmod_cast_u(po, po->operand[0].lmod),
4785               lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4786           fprintf(fout,
4787             "    if (cond_z %s 0) break;\n",
4788               (po->flags & OPF_REPZ) ? "==" : "!=");
4789           fprintf(fout,
4790             "  }");
4791           snprintf(g_comment, sizeof(g_comment), "rep%s scas",
4792             (po->flags & OPF_REPZ) ? "e" : "ne");
4793         }
4794         else {
4795           fprintf(fout, "  cond_z = (%seax == %sedi); edi %c= %d;",
4796               lmod_cast_u(po, po->operand[0].lmod),
4797               lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4798           strcpy(g_comment, "scas");
4799         }
4800         pfomask &= ~(1 << PFO_Z);
4801         last_arith_dst = NULL;
4802         delayed_flag_op = NULL;
4803         break;
4804
4805       // arithmetic w/flags
4806       case OP_AND:
4807       case OP_OR:
4808         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4809         // fallthrough
4810       dualop_arith:
4811         assert_operand_cnt(2);
4812         fprintf(fout, "  %s %s= %s;",
4813             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4814             op_to_c(po),
4815             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4816         output_std_flags(fout, po, &pfomask, buf1);
4817         last_arith_dst = &po->operand[0];
4818         delayed_flag_op = NULL;
4819         break;
4820
4821       case OP_SHL:
4822       case OP_SHR:
4823         assert_operand_cnt(2);
4824         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4825         if (pfomask & (1 << PFO_C)) {
4826           if (po->operand[1].type == OPT_CONST) {
4827             l = lmod_bytes(po, po->operand[0].lmod) * 8;
4828             j = po->operand[1].val;
4829             j %= l;
4830             if (j != 0) {
4831               if (po->op == OP_SHL)
4832                 j = l - j;
4833               else
4834                 j -= 1;
4835               fprintf(fout, "  cond_c = (%s >> %d) & 1;\n",
4836                 buf1, j);
4837             }
4838             else
4839               ferr(po, "zero shift?\n");
4840           }
4841           else
4842             ferr(po, "TODO\n");
4843           pfomask &= ~(1 << PFO_C);
4844         }
4845         fprintf(fout, "  %s %s= %s;", buf1, op_to_c(po),
4846             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4847         output_std_flags(fout, po, &pfomask, buf1);
4848         last_arith_dst = &po->operand[0];
4849         delayed_flag_op = NULL;
4850         break;
4851
4852       case OP_SAR:
4853         assert_operand_cnt(2);
4854         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4855         fprintf(fout, "  %s = %s%s >> %s;", buf1,
4856           lmod_cast_s(po, po->operand[0].lmod), buf1,
4857           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4858         output_std_flags(fout, po, &pfomask, buf1);
4859         last_arith_dst = &po->operand[0];
4860         delayed_flag_op = NULL;
4861         break;
4862
4863       case OP_SHRD:
4864         assert_operand_cnt(3);
4865         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4866         l = lmod_bytes(po, po->operand[0].lmod) * 8;
4867         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4868         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4869         out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[2]);
4870         fprintf(fout, "  %s >>= %s; %s |= %s << (%d - %s);",
4871           buf1, buf3, buf1, buf2, l, buf3);
4872         strcpy(g_comment, "shrd");
4873         output_std_flags(fout, po, &pfomask, buf1);
4874         last_arith_dst = &po->operand[0];
4875         delayed_flag_op = NULL;
4876         break;
4877
4878       case OP_ROL:
4879       case OP_ROR:
4880         assert_operand_cnt(2);
4881         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4882         if (po->operand[1].type == OPT_CONST) {
4883           j = po->operand[1].val;
4884           j %= lmod_bytes(po, po->operand[0].lmod) * 8;
4885           fprintf(fout, po->op == OP_ROL ?
4886             "  %s = (%s << %d) | (%s >> %d);" :
4887             "  %s = (%s >> %d) | (%s << %d);",
4888             buf1, buf1, j, buf1,
4889             lmod_bytes(po, po->operand[0].lmod) * 8 - j);
4890         }
4891         else
4892           ferr(po, "TODO\n");
4893         output_std_flags(fout, po, &pfomask, buf1);
4894         last_arith_dst = &po->operand[0];
4895         delayed_flag_op = NULL;
4896         break;
4897
4898       case OP_RCL:
4899       case OP_RCR:
4900         assert_operand_cnt(2);
4901         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4902         l = lmod_bytes(po, po->operand[0].lmod) * 8;
4903         if (po->operand[1].type == OPT_CONST) {
4904           j = po->operand[1].val % l;
4905           if (j == 0)
4906             ferr(po, "zero rotate\n");
4907           fprintf(fout, "  tmp = (%s >> %d) & 1;\n",
4908             buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
4909           if (po->op == OP_RCL) {
4910             fprintf(fout,
4911               "  %s = (%s << %d) | (cond_c << %d)",
4912               buf1, buf1, j, j - 1);
4913             if (j != 1)
4914               fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
4915           }
4916           else {
4917             fprintf(fout,
4918               "  %s = (%s >> %d) | (cond_c << %d)",
4919               buf1, buf1, j, l - j);
4920             if (j != 1)
4921               fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
4922           }
4923           fprintf(fout, ";\n");
4924           fprintf(fout, "  cond_c = tmp;");
4925         }
4926         else
4927           ferr(po, "TODO\n");
4928         strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
4929         output_std_flags(fout, po, &pfomask, buf1);
4930         last_arith_dst = &po->operand[0];
4931         delayed_flag_op = NULL;
4932         break;
4933
4934       case OP_XOR:
4935         assert_operand_cnt(2);
4936         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4937         if (IS(opr_name(po, 0), opr_name(po, 1))) {
4938           // special case for XOR
4939           if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
4940             fprintf(fout, "  cond_be = 1;\n");
4941             pfomask &= ~(1 << PFO_BE);
4942           }
4943           fprintf(fout, "  %s = 0;",
4944             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4945           last_arith_dst = &po->operand[0];
4946           delayed_flag_op = NULL;
4947           break;
4948         }
4949         goto dualop_arith;
4950
4951       case OP_ADD:
4952         assert_operand_cnt(2);
4953         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4954         if (pfomask & (1 << PFO_C)) {
4955           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4956           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4957           if (po->operand[0].lmod == OPLM_DWORD) {
4958             fprintf(fout, "  tmp64 = (u64)%s + %s;\n", buf1, buf2);
4959             fprintf(fout, "  cond_c = tmp64 >> 32;\n");
4960             fprintf(fout, "  %s = (u32)tmp64;",
4961               out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4962             strcat(g_comment, "add64");
4963           }
4964           else {
4965             fprintf(fout, "  cond_c = ((u32)%s + %s) >> %d;\n",
4966               buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
4967             fprintf(fout, "  %s += %s;",
4968               out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4969               buf2);
4970           }
4971           pfomask &= ~(1 << PFO_C);
4972           output_std_flags(fout, po, &pfomask, buf1);
4973           last_arith_dst = &po->operand[0];
4974           delayed_flag_op = NULL;
4975           break;
4976         }
4977         goto dualop_arith;
4978
4979       case OP_SUB:
4980         assert_operand_cnt(2);
4981         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4982         if (pfomask & ~((1 << PFO_Z) | (1 << PFO_S))) {
4983           for (j = 0; j <= PFO_LE; j++) {
4984             if (!(pfomask & (1 << j)))
4985               continue;
4986             if (j == PFO_Z || j == PFO_S)
4987               continue;
4988
4989             out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
4990             fprintf(fout, "  cond_%s = %s;\n",
4991               parsed_flag_op_names[j], buf1);
4992             pfomask &= ~(1 << j);
4993           }
4994         }
4995         goto dualop_arith;
4996
4997       case OP_ADC:
4998       case OP_SBB:
4999         assert_operand_cnt(2);
5000         propagate_lmod(po, &po->operand[0], &po->operand[1]);
5001         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5002         if (po->op == OP_SBB
5003           && IS(po->operand[0].name, po->operand[1].name))
5004         {
5005           // avoid use of unitialized var
5006           fprintf(fout, "  %s = -cond_c;", buf1);
5007           // carry remains what it was
5008           pfomask &= ~(1 << PFO_C);
5009         }
5010         else {
5011           fprintf(fout, "  %s %s= %s + cond_c;", buf1, op_to_c(po),
5012             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5013         }
5014         output_std_flags(fout, po, &pfomask, buf1);
5015         last_arith_dst = &po->operand[0];
5016         delayed_flag_op = NULL;
5017         break;
5018
5019       case OP_BSF:
5020         assert_operand_cnt(2);
5021         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5022         fprintf(fout, "  %s = %s ? __builtin_ffs(%s) - 1 : 0;",
5023           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5024           buf2, buf2);
5025         output_std_flags(fout, po, &pfomask, buf1);
5026         last_arith_dst = &po->operand[0];
5027         delayed_flag_op = NULL;
5028         strcat(g_comment, "bsf");
5029         break;
5030
5031       case OP_DEC:
5032         if (pfomask & ~(PFOB_S | PFOB_S | PFOB_C)) {
5033           for (j = 0; j <= PFO_LE; j++) {
5034             if (!(pfomask & (1 << j)))
5035               continue;
5036             if (j == PFO_Z || j == PFO_S || j == PFO_C)
5037               continue;
5038
5039             out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5040             fprintf(fout, "  cond_%s = %s;\n",
5041               parsed_flag_op_names[j], buf1);
5042             pfomask &= ~(1 << j);
5043           }
5044         }
5045         // fallthrough
5046
5047       case OP_INC:
5048         if (pfomask & (1 << PFO_C))
5049           // carry is unaffected by inc/dec.. wtf?
5050           ferr(po, "carry propagation needed\n");
5051
5052         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5053         if (po->operand[0].type == OPT_REG) {
5054           strcpy(buf2, po->op == OP_INC ? "++" : "--");
5055           fprintf(fout, "  %s%s;", buf1, buf2);
5056         }
5057         else {
5058           strcpy(buf2, po->op == OP_INC ? "+" : "-");
5059           fprintf(fout, "  %s %s= 1;", buf1, buf2);
5060         }
5061         output_std_flags(fout, po, &pfomask, buf1);
5062         last_arith_dst = &po->operand[0];
5063         delayed_flag_op = NULL;
5064         break;
5065
5066       case OP_NEG:
5067         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5068         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
5069         fprintf(fout, "  %s = -%s%s;", buf1,
5070           lmod_cast_s(po, po->operand[0].lmod), buf2);
5071         last_arith_dst = &po->operand[0];
5072         delayed_flag_op = NULL;
5073         if (pfomask & (1 << PFO_C)) {
5074           fprintf(fout, "\n  cond_c = (%s != 0);", buf1);
5075           pfomask &= ~(1 << PFO_C);
5076         }
5077         break;
5078
5079       case OP_IMUL:
5080         if (po->operand_cnt == 2) {
5081           propagate_lmod(po, &po->operand[0], &po->operand[1]);
5082           goto dualop_arith;
5083         }
5084         if (po->operand_cnt == 3)
5085           ferr(po, "TODO imul3\n");
5086         // fallthrough
5087       case OP_MUL:
5088         assert_operand_cnt(1);
5089         switch (po->operand[0].lmod) {
5090         case OPLM_DWORD:
5091           strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
5092           fprintf(fout, "  tmp64 = %seax * %s%s;\n", buf1, buf1,
5093             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
5094           fprintf(fout, "  edx = tmp64 >> 32;\n");
5095           fprintf(fout, "  eax = tmp64;");
5096           break;
5097         case OPLM_BYTE:
5098           strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
5099           fprintf(fout, "  LOWORD(eax) = %seax * %s;", buf1,
5100             out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
5101               buf1, 0));
5102           break;
5103         default:
5104           ferr(po, "TODO: unhandled mul type\n");
5105           break;
5106         }
5107         last_arith_dst = NULL;
5108         delayed_flag_op = NULL;
5109         break;
5110
5111       case OP_DIV:
5112       case OP_IDIV:
5113         assert_operand_cnt(1);
5114         if (po->operand[0].lmod != OPLM_DWORD)
5115           ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
5116
5117         out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5118         strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
5119           po->op == OP_IDIV));
5120         switch (po->operand[0].lmod) {
5121         case OPLM_DWORD:
5122           if (po->flags & OPF_32BIT)
5123             snprintf(buf3, sizeof(buf3), "%seax", buf2);
5124           else {
5125             fprintf(fout, "  tmp64 = ((u64)edx << 32) | eax;\n");
5126             snprintf(buf3, sizeof(buf3), "%stmp64",
5127               (po->op == OP_IDIV) ? "(s64)" : "");
5128           }
5129           if (po->operand[0].type == OPT_REG
5130             && po->operand[0].reg == xDX)
5131           {
5132             fprintf(fout, "  eax = %s / %s%s;", buf3, buf2, buf1);
5133             fprintf(fout, "  edx = %s %% %s%s;\n", buf3, buf2, buf1);
5134           }
5135           else {
5136             fprintf(fout, "  edx = %s %% %s%s;\n", buf3, buf2, buf1);
5137             fprintf(fout, "  eax = %s / %s%s;", buf3, buf2, buf1);
5138           }
5139           break;
5140         default:
5141           ferr(po, "unhandled division type\n");
5142         }
5143         last_arith_dst = NULL;
5144         delayed_flag_op = NULL;
5145         break;
5146
5147       case OP_TEST:
5148       case OP_CMP:
5149         propagate_lmod(po, &po->operand[0], &po->operand[1]);
5150         if (pfomask != 0) {
5151           for (j = 0; j < 8; j++) {
5152             if (pfomask & (1 << j)) {
5153               out_cmp_test(buf1, sizeof(buf1), po, j, 0);
5154               fprintf(fout, "  cond_%s = %s;",
5155                 parsed_flag_op_names[j], buf1);
5156             }
5157           }
5158           pfomask = 0;
5159         }
5160         else
5161           no_output = 1;
5162         last_arith_dst = NULL;
5163         delayed_flag_op = po;
5164         break;
5165
5166       case OP_SCC:
5167         // SETcc - should already be handled
5168         break;
5169
5170       // note: we reuse OP_Jcc for SETcc, only flags differ
5171       case OP_JCC:
5172         fprintf(fout, "\n    goto %s;", po->operand[0].name);
5173         break;
5174
5175       case OP_JECXZ:
5176         fprintf(fout, "  if (ecx == 0)\n");
5177         fprintf(fout, "    goto %s;", po->operand[0].name);
5178         strcat(g_comment, "jecxz");
5179         break;
5180
5181       case OP_JMP:
5182         assert_operand_cnt(1);
5183         last_arith_dst = NULL;
5184         delayed_flag_op = NULL;
5185
5186         if (po->operand[0].type == OPT_REGMEM) {
5187           ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
5188                   buf1, buf2);
5189           if (ret != 2)
5190             ferr(po, "parse failure for jmp '%s'\n",
5191               po->operand[0].name);
5192           fprintf(fout, "  goto *jt_%s[%s];", buf1, buf2);
5193           break;
5194         }
5195         else if (po->operand[0].type != OPT_LABEL)
5196           ferr(po, "unhandled jmp type\n");
5197
5198         fprintf(fout, "  goto %s;", po->operand[0].name);
5199         break;
5200
5201       case OP_CALL:
5202         assert_operand_cnt(1);
5203         pp = po->pp;
5204         my_assert_not(pp, NULL);
5205
5206         strcpy(buf3, "  ");
5207         if (po->flags & OPF_CC) {
5208           // we treat conditional branch to another func
5209           // (yes such code exists..) as conditional tailcall
5210           strcat(buf3, "  ");
5211           fprintf(fout, " {\n");
5212         }
5213
5214         if (pp->is_fptr && !pp->is_arg) {
5215           fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
5216             out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
5217               "(void *)", 0));
5218           if (pp->is_unresolved)
5219             fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
5220               buf3, asmfn, po->asmln, pp->name);
5221         }
5222
5223         fprintf(fout, "%s", buf3);
5224         if (strstr(pp->ret_type.name, "int64")) {
5225           if (po->flags & OPF_TAIL)
5226             ferr(po, "int64 and tail?\n");
5227           fprintf(fout, "tmp64 = ");
5228         }
5229         else if (!IS(pp->ret_type.name, "void")) {
5230           if (po->flags & OPF_TAIL) {
5231             if (!IS(g_func_pp->ret_type.name, "void")) {
5232               fprintf(fout, "return ");
5233               if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
5234                 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
5235             }
5236           }
5237           else if (regmask & (1 << xAX)) {
5238             fprintf(fout, "eax = ");
5239             if (pp->ret_type.is_ptr)
5240               fprintf(fout, "(u32)");
5241           }
5242         }
5243
5244         if (pp->name[0] == 0)
5245           ferr(po, "missing pp->name\n");
5246         fprintf(fout, "%s%s(", pp->name,
5247           pp->has_structarg ? "_sa" : "");
5248
5249         if (po->flags & OPF_ATAIL) {
5250           if (pp->argc_stack != g_func_pp->argc_stack
5251             || (pp->argc_stack > 0
5252                 && pp->is_stdcall != g_func_pp->is_stdcall))
5253             ferr(po, "incompatible tailcall\n");
5254           if (g_func_pp->has_retreg)
5255             ferr(po, "TODO: retreg+tailcall\n");
5256
5257           for (arg = j = 0; arg < pp->argc; arg++) {
5258             if (arg > 0)
5259               fprintf(fout, ", ");
5260
5261             cast[0] = 0;
5262             if (pp->arg[arg].type.is_ptr)
5263               snprintf(cast, sizeof(cast), "(%s)",
5264                 pp->arg[arg].type.name);
5265
5266             if (pp->arg[arg].reg != NULL) {
5267               fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5268               continue;
5269             }
5270             // stack arg
5271             for (; j < g_func_pp->argc; j++)
5272               if (g_func_pp->arg[j].reg == NULL)
5273                 break;
5274             fprintf(fout, "%sa%d", cast, j + 1);
5275             j++;
5276           }
5277         }
5278         else {
5279           for (arg = 0; arg < pp->argc; arg++) {
5280             if (arg > 0)
5281               fprintf(fout, ", ");
5282
5283             cast[0] = 0;
5284             if (pp->arg[arg].type.is_ptr)
5285               snprintf(cast, sizeof(cast), "(%s)",
5286                 pp->arg[arg].type.name);
5287
5288             if (pp->arg[arg].reg != NULL) {
5289               if (pp->arg[arg].type.is_retreg)
5290                 fprintf(fout, "&%s", pp->arg[arg].reg);
5291               else
5292                 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5293               continue;
5294             }
5295
5296             // stack arg
5297             tmp_op = pp->arg[arg].datap;
5298             if (tmp_op == NULL)
5299               ferr(po, "parsed_op missing for arg%d\n", arg);
5300
5301             if (tmp_op->flags & OPF_VAPUSH) {
5302               fprintf(fout, "ap");
5303             }
5304             else if (tmp_op->p_argpass != 0) {
5305               fprintf(fout, "a%d", tmp_op->p_argpass);
5306             }
5307             else if (tmp_op->p_argnum != 0) {
5308               fprintf(fout, "%s%s", cast,
5309                 saved_arg_name(buf1, sizeof(buf1),
5310                   tmp_op->p_arggrp, tmp_op->p_argnum));
5311             }
5312             else {
5313               fprintf(fout, "%s",
5314                 out_src_opr(buf1, sizeof(buf1),
5315                   tmp_op, &tmp_op->operand[0], cast, 0));
5316             }
5317           }
5318         }
5319         fprintf(fout, ");");
5320
5321         if (strstr(pp->ret_type.name, "int64")) {
5322           fprintf(fout, "\n");
5323           fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
5324           fprintf(fout, "%seax = tmp64;", buf3);
5325         }
5326
5327         if (pp->is_unresolved) {
5328           snprintf(buf2, sizeof(buf2), " unresolved %dreg",
5329             pp->argc_reg);
5330           strcat(g_comment, buf2);
5331         }
5332
5333         if (po->flags & OPF_TAIL) {
5334           ret = 0;
5335           if (i == opcnt - 1 || pp->is_noreturn)
5336             ret = 0;
5337           else if (IS(pp->ret_type.name, "void"))
5338             ret = 1;
5339           else if (IS(g_func_pp->ret_type.name, "void"))
5340             ret = 1;
5341           // else already handled as 'return f()'
5342
5343           if (ret) {
5344             if (!IS(g_func_pp->ret_type.name, "void")) {
5345               ferr(po, "int func -> void func tailcall?\n");
5346             }
5347             else {
5348               fprintf(fout, "\n%sreturn;", buf3);
5349               strcat(g_comment, " ^ tailcall");
5350             }
5351           }
5352           else
5353             strcat(g_comment, " tailcall");
5354         }
5355         if (pp->is_noreturn)
5356           strcat(g_comment, " noreturn");
5357         if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
5358           strcat(g_comment, " argframe");
5359         if (po->flags & OPF_CC)
5360           strcat(g_comment, " cond");
5361
5362         if (po->flags & OPF_CC)
5363           fprintf(fout, "\n  }");
5364
5365         delayed_flag_op = NULL;
5366         last_arith_dst = NULL;
5367         break;
5368
5369       case OP_RET:
5370         if (g_func_pp->is_vararg)
5371           fprintf(fout, "  va_end(ap);\n");
5372         if (g_func_pp->has_retreg) {
5373           for (arg = 0; arg < g_func_pp->argc; arg++)
5374             if (g_func_pp->arg[arg].type.is_retreg)
5375               fprintf(fout, "  *r_%s = %s;\n",
5376                 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
5377         }
5378  
5379         if (IS(g_func_pp->ret_type.name, "void")) {
5380           if (i != opcnt - 1 || label_pending)
5381             fprintf(fout, "  return;");
5382         }
5383         else if (g_func_pp->ret_type.is_ptr) {
5384           fprintf(fout, "  return (%s)eax;",
5385             g_func_pp->ret_type.name);
5386         }
5387         else if (IS(g_func_pp->ret_type.name, "__int64"))
5388           fprintf(fout, "  return ((u64)edx << 32) | eax;");
5389         else
5390           fprintf(fout, "  return eax;");
5391
5392         last_arith_dst = NULL;
5393         delayed_flag_op = NULL;
5394         break;
5395
5396       case OP_PUSH:
5397         out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5398         if (po->p_argnum != 0) {
5399           // special case - saved func arg
5400           fprintf(fout, "  %s = %s;",
5401             saved_arg_name(buf2, sizeof(buf2),
5402               po->p_arggrp, po->p_argnum), buf1);
5403           break;
5404         }
5405         else if (po->flags & OPF_RSAVE) {
5406           fprintf(fout, "  s_%s = %s;", buf1, buf1);
5407           break;
5408         }
5409         else if (po->flags & OPF_PPUSH) {
5410           tmp_op = po->datap;
5411           ferr_assert(po, tmp_op != NULL);
5412           out_dst_opr(buf2, sizeof(buf2), po, &tmp_op->operand[0]);
5413           fprintf(fout, "  pp_%s = %s;", buf2, buf1);
5414           break;
5415         }
5416         else if (g_func_pp->is_userstack) {
5417           fprintf(fout, "  *(--esp) = %s;", buf1);
5418           break;
5419         }
5420         if (!(g_ida_func_attr & IDAFA_NORETURN))
5421           ferr(po, "stray push encountered\n");
5422         no_output = 1;
5423         break;
5424
5425       case OP_POP:
5426         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5427         if (po->flags & OPF_RSAVE) {
5428           fprintf(fout, "  %s = s_%s;", buf1, buf1);
5429           break;
5430         }
5431         else if (po->flags & OPF_PPUSH) {
5432           // push/pop graph
5433           ferr_assert(po, po->datap == NULL);
5434           fprintf(fout, "  %s = pp_%s;", buf1, buf1);
5435           break;
5436         }
5437         else if (po->datap != NULL) {
5438           // push/pop pair
5439           tmp_op = po->datap;
5440           fprintf(fout, "  %s = %s;", buf1,
5441             out_src_opr(buf2, sizeof(buf2),
5442               tmp_op, &tmp_op->operand[0],
5443               default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5444           break;
5445         }
5446         else if (g_func_pp->is_userstack) {
5447           fprintf(fout, "  %s = *esp++;", buf1);
5448           break;
5449         }
5450         else
5451           ferr(po, "stray pop encountered\n");
5452         break;
5453
5454       case OP_NOP:
5455         no_output = 1;
5456         break;
5457
5458       // mmx
5459       case OP_EMMS:
5460         strcpy(g_comment, "(emms)");
5461         break;
5462
5463       default:
5464         no_output = 1;
5465         ferr(po, "unhandled op type %d, flags %x\n",
5466           po->op, po->flags);
5467         break;
5468     }
5469
5470     if (g_comment[0] != 0) {
5471       char *p = g_comment;
5472       while (my_isblank(*p))
5473         p++;
5474       fprintf(fout, "  // %s", p);
5475       g_comment[0] = 0;
5476       no_output = 0;
5477     }
5478     if (!no_output)
5479       fprintf(fout, "\n");
5480
5481     // some sanity checking
5482     if (po->flags & OPF_REP) {
5483       if (po->op != OP_STOS && po->op != OP_MOVS
5484           && po->op != OP_CMPS && po->op != OP_SCAS)
5485         ferr(po, "unexpected rep\n");
5486       if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
5487           && (po->op == OP_CMPS || po->op == OP_SCAS))
5488         ferr(po, "cmps/scas with plain rep\n");
5489     }
5490     if ((po->flags & (OPF_REPZ|OPF_REPNZ))
5491         && po->op != OP_CMPS && po->op != OP_SCAS)
5492       ferr(po, "unexpected repz/repnz\n");
5493
5494     if (pfomask != 0)
5495       ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
5496
5497     // see is delayed flag stuff is still valid
5498     if (delayed_flag_op != NULL && delayed_flag_op != po) {
5499       if (is_any_opr_modified(delayed_flag_op, po, 0))
5500         delayed_flag_op = NULL;
5501     }
5502
5503     if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
5504       if (is_opr_modified(last_arith_dst, po))
5505         last_arith_dst = NULL;
5506     }
5507
5508     label_pending = 0;
5509   }
5510
5511   if (g_stack_fsz && !g_stack_frame_used)
5512     fprintf(fout, "  (void)sf;\n");
5513
5514   fprintf(fout, "}\n\n");
5515
5516   gen_x_cleanup(opcnt);
5517 }
5518
5519 static void gen_x_cleanup(int opcnt)
5520 {
5521   int i;
5522
5523   for (i = 0; i < opcnt; i++) {
5524     struct label_ref *lr, *lr_del;
5525
5526     lr = g_label_refs[i].next;
5527     while (lr != NULL) {
5528       lr_del = lr;
5529       lr = lr->next;
5530       free(lr_del);
5531     }
5532     g_label_refs[i].i = -1;
5533     g_label_refs[i].next = NULL;
5534
5535     if (ops[i].op == OP_CALL) {
5536       if (ops[i].pp)
5537         proto_release(ops[i].pp);
5538     }
5539   }
5540   g_func_pp = NULL;
5541 }
5542
5543 struct func_proto_dep;
5544
5545 struct func_prototype {
5546   char name[NAMELEN];
5547   int id;
5548   int argc_stack;
5549   int regmask_dep;
5550   int has_ret:3;                 // -1, 0, 1: unresolved, no, yes
5551   unsigned int dep_resolved:1;
5552   unsigned int is_stdcall:1;
5553   struct func_proto_dep *dep_func;
5554   int dep_func_cnt;
5555   const struct parsed_proto *pp; // seed pp, if any
5556 };
5557
5558 struct func_proto_dep {
5559   char *name;
5560   struct func_prototype *proto;
5561   int regmask_live;             // .. at the time of call
5562   unsigned int ret_dep:1;       // return from this is caller's return
5563 };
5564
5565 static struct func_prototype *hg_fp;
5566 static int hg_fp_cnt;
5567
5568 static struct scanned_var {
5569   char name[NAMELEN];
5570   enum opr_lenmod lmod;
5571   unsigned int is_seeded:1;
5572   unsigned int is_c_str:1;
5573   const struct parsed_proto *pp; // seed pp, if any
5574 } *hg_vars;
5575 static int hg_var_cnt;
5576
5577 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
5578   int count);
5579
5580 static struct func_proto_dep *hg_fp_find_dep(struct func_prototype *fp,
5581   const char *name)
5582 {
5583   int i;
5584
5585   for (i = 0; i < fp->dep_func_cnt; i++)
5586     if (IS(fp->dep_func[i].name, name))
5587       return &fp->dep_func[i];
5588
5589   return NULL;
5590 }
5591
5592 static void hg_fp_add_dep(struct func_prototype *fp, const char *name)
5593 {
5594   // is it a dupe?
5595   if (hg_fp_find_dep(fp, name))
5596     return;
5597
5598   if ((fp->dep_func_cnt & 0xff) == 0) {
5599     fp->dep_func = realloc(fp->dep_func,
5600       sizeof(fp->dep_func[0]) * (fp->dep_func_cnt + 0x100));
5601     my_assert_not(fp->dep_func, NULL);
5602     memset(&fp->dep_func[fp->dep_func_cnt], 0,
5603       sizeof(fp->dep_func[0]) * 0x100);
5604   }
5605   fp->dep_func[fp->dep_func_cnt].name = strdup(name);
5606   fp->dep_func_cnt++;
5607 }
5608
5609 static int hg_fp_cmp_name(const void *p1_, const void *p2_)
5610 {
5611   const struct func_prototype *p1 = p1_, *p2 = p2_;
5612   return strcmp(p1->name, p2->name);
5613 }
5614
5615 #if 0
5616 static int hg_fp_cmp_id(const void *p1_, const void *p2_)
5617 {
5618   const struct func_prototype *p1 = p1_, *p2 = p2_;
5619   return p1->id - p2->id;
5620 }
5621 #endif
5622
5623 // recursive register dep pass
5624 // - track saved regs (part 2)
5625 // - try to figure out arg-regs
5626 // - calculate reg deps
5627 static void gen_hdr_dep_pass(int i, int opcnt, unsigned char *cbits,
5628   struct func_prototype *fp, int regmask_save, int regmask_dst,
5629   int *regmask_dep, int *has_ret)
5630 {
5631   struct func_proto_dep *dep;
5632   struct parsed_op *po;
5633   int from_caller = 0;
5634   int depth;
5635   int j, l;
5636   int reg;
5637   int ret;
5638
5639   for (; i < opcnt; i++)
5640   {
5641     if (cbits[i >> 3] & (1 << (i & 7)))
5642       return;
5643     cbits[i >> 3] |= (1 << (i & 7));
5644
5645     po = &ops[i];
5646
5647     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
5648       if (po->btj != NULL) {
5649         // jumptable
5650         for (j = 0; j < po->btj->count; j++) {
5651           gen_hdr_dep_pass(po->btj->d[j].bt_i, opcnt, cbits, fp,
5652             regmask_save, regmask_dst, regmask_dep, has_ret);
5653         }
5654         return;
5655       }
5656
5657       if (po->bt_i < 0) {
5658         ferr(po, "dead branch\n");
5659         return;
5660       }
5661
5662       if (po->flags & OPF_CJMP) {
5663         gen_hdr_dep_pass(po->bt_i, opcnt, cbits, fp,
5664           regmask_save, regmask_dst, regmask_dep, has_ret);
5665       }
5666       else {
5667         i = po->bt_i - 1;
5668       }
5669       continue;
5670     }
5671
5672     if (po->flags & OPF_FARG)
5673       /* (just calculate register deps) */;
5674     else if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
5675     {
5676       reg = po->operand[0].reg;
5677       if (reg < 0)
5678         ferr(po, "reg not set for push?\n");
5679
5680       if (po->flags & OPF_RSAVE) {
5681         regmask_save |= 1 << reg;
5682         continue;
5683       }
5684       if (po->flags & OPF_DONE)
5685         continue;
5686
5687       depth = 0;
5688       ret = scan_for_pop(i + 1, opcnt,
5689               po->operand[0].name, i + opcnt * 2, 0, &depth, 0);
5690       if (ret == 1) {
5691         regmask_save |= 1 << reg;
5692         po->flags |= OPF_RMD;
5693         scan_for_pop(i + 1, opcnt,
5694           po->operand[0].name, i + opcnt * 3, 0, &depth, 1);
5695         continue;
5696       }
5697     }
5698     else if (po->flags & OPF_RMD)
5699       continue;
5700     else if (po->op == OP_CALL) {
5701       po->regmask_dst |= 1 << xAX;
5702
5703       dep = hg_fp_find_dep(fp, po->operand[0].name);
5704       if (dep != NULL)
5705         dep->regmask_live = regmask_save | regmask_dst;
5706     }
5707     else if (po->op == OP_RET) {
5708       if (po->operand_cnt > 0) {
5709         fp->is_stdcall = 1;
5710         if (fp->argc_stack >= 0
5711             && fp->argc_stack != po->operand[0].val / 4)
5712           ferr(po, "ret mismatch? (%d)\n", fp->argc_stack * 4);
5713         fp->argc_stack = po->operand[0].val / 4;
5714       }
5715     }
5716
5717     if (*has_ret != 0 && (po->flags & OPF_TAIL)) {
5718       if (po->op == OP_CALL) {
5719         j = i;
5720         ret = 1;
5721       }
5722       else {
5723         struct parsed_opr opr = { 0, };
5724         opr.type = OPT_REG;
5725         opr.reg = xAX;
5726         j = -1;
5727         from_caller = 0;
5728         ret = resolve_origin(i, &opr, i + opcnt * 4, &j, &from_caller);
5729       }
5730
5731       if (ret == -1 && from_caller) {
5732         // unresolved eax - probably void func
5733         *has_ret = 0;
5734       }
5735       else {
5736         if (ops[j].op == OP_CALL) {
5737           dep = hg_fp_find_dep(fp, po->operand[0].name);
5738           if (dep != NULL)
5739             dep->ret_dep = 1;
5740           else
5741             *has_ret = 1;
5742         }
5743         else
5744           *has_ret = 1;
5745       }
5746     }
5747
5748     l = regmask_save | regmask_dst;
5749     if (g_bp_frame && !(po->flags & OPF_EBP_S))
5750       l |= 1 << xBP;
5751
5752     l = po->regmask_src & ~l;
5753 #if 0
5754     if (l)
5755       fnote(po, "dep |= %04x, dst %04x, save %04x (f %x)\n",
5756         l, regmask_dst, regmask_save, po->flags);
5757 #endif
5758     *regmask_dep |= l;
5759     regmask_dst |= po->regmask_dst;
5760
5761     if (po->flags & OPF_TAIL)
5762       return;
5763   }
5764 }
5765
5766 static void gen_hdr(const char *funcn, int opcnt)
5767 {
5768   int save_arg_vars[MAX_ARG_GRP] = { 0, };
5769   unsigned char cbits[MAX_OPS / 8];
5770   const struct parsed_proto *pp_c;
5771   struct parsed_proto *pp;
5772   struct func_prototype *fp;
5773   struct parsed_data *pd;
5774   struct parsed_op *po;
5775   const char *tmpname;
5776   int regmask_dummy = 0;
5777   int regmask_dep;
5778   int max_bp_offset = 0;
5779   int has_ret;
5780   int i, j, l, ret;
5781
5782   if ((hg_fp_cnt & 0xff) == 0) {
5783     hg_fp = realloc(hg_fp, sizeof(hg_fp[0]) * (hg_fp_cnt + 0x100));
5784     my_assert_not(hg_fp, NULL);
5785     memset(hg_fp + hg_fp_cnt, 0, sizeof(hg_fp[0]) * 0x100);
5786   }
5787
5788   fp = &hg_fp[hg_fp_cnt];
5789   snprintf(fp->name, sizeof(fp->name), "%s", funcn);
5790   fp->id = hg_fp_cnt;
5791   fp->argc_stack = -1;
5792   hg_fp_cnt++;
5793
5794   // perhaps already in seed header?
5795   fp->pp = proto_parse(g_fhdr, funcn, 1);
5796   if (fp->pp != NULL) {
5797     fp->argc_stack = fp->pp->argc_stack;
5798     fp->is_stdcall = fp->pp->is_stdcall;
5799     fp->regmask_dep = get_pp_arg_regmask(fp->pp);
5800     fp->has_ret = !IS(fp->pp->ret_type.name, "void");
5801     return;
5802   }
5803
5804   g_bp_frame = g_sp_frame = g_stack_fsz = 0;
5805   g_stack_frame_used = 0;
5806
5807   // pass1:
5808   // - handle ebp/esp frame, remove ops related to it
5809   scan_prologue_epilogue(opcnt);
5810
5811   // pass2:
5812   // - collect calls
5813   // - resolve all branches
5814   for (i = 0; i < opcnt; i++)
5815   {
5816     po = &ops[i];
5817     po->bt_i = -1;
5818     po->btj = NULL;
5819
5820     if (po->flags & (OPF_RMD|OPF_DONE))
5821       continue;
5822
5823     if (po->op == OP_CALL) {
5824       tmpname = opr_name(po, 0);
5825       pp = NULL;
5826       if (po->operand[0].type == OPT_LABEL) {
5827         hg_fp_add_dep(fp, tmpname);
5828
5829         // perhaps a call to already known func?
5830         pp_c = proto_parse(g_fhdr, tmpname, 1);
5831         if (pp_c != NULL)
5832           pp = proto_clone(pp_c);
5833       }
5834       else if (po->datap != NULL) {
5835         pp = calloc(1, sizeof(*pp));
5836         my_assert_not(pp, NULL);
5837
5838         ret = parse_protostr(po->datap, pp);
5839         if (ret < 0)
5840           ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
5841         free(po->datap);
5842         po->datap = NULL;
5843       }
5844       if (pp != NULL && pp->is_noreturn)
5845         po->flags |= OPF_TAIL;
5846
5847       po->pp = pp;
5848       continue;
5849     }
5850
5851     if (!(po->flags & OPF_JMP) || po->op == OP_RET)
5852       continue;
5853
5854     if (po->operand[0].type == OPT_REGMEM) {
5855       pd = try_resolve_jumptab(i, opcnt);
5856       if (pd == NULL)
5857         goto tailcall;
5858
5859       po->btj = pd;
5860       continue;
5861     }
5862
5863     for (l = 0; l < opcnt; l++) {
5864       if (g_labels[l] != NULL
5865           && IS(po->operand[0].name, g_labels[l]))
5866       {
5867         add_label_ref(&g_label_refs[l], i);
5868         po->bt_i = l;
5869         break;
5870       }
5871     }
5872
5873     if (po->bt_i != -1 || (po->flags & OPF_RMD))
5874       continue;
5875
5876     if (po->operand[0].type == OPT_LABEL)
5877       // assume tail call
5878       goto tailcall;
5879
5880     ferr(po, "unhandled branch\n");
5881
5882 tailcall:
5883     po->op = OP_CALL;
5884     po->flags |= OPF_TAIL;
5885     if (i > 0 && ops[i - 1].op == OP_POP)
5886       po->flags |= OPF_ATAIL;
5887     i--; // reprocess
5888   }
5889
5890   // pass3:
5891   // - remove dead labels
5892   // - handle push <const>/pop pairs
5893   for (i = 0; i < opcnt; i++)
5894   {
5895     if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
5896       free(g_labels[i]);
5897       g_labels[i] = NULL;
5898     }
5899
5900     po = &ops[i];
5901     if (po->flags & (OPF_RMD|OPF_DONE))
5902       continue;
5903
5904     if (po->op == OP_PUSH && po->operand[0].type == OPT_CONST)
5905       scan_for_pop_const(i, opcnt, &regmask_dummy);
5906   }
5907
5908   // pass4:
5909   // - process trivial calls
5910   for (i = 0; i < opcnt; i++)
5911   {
5912     po = &ops[i];
5913     if (po->flags & (OPF_RMD|OPF_DONE))
5914       continue;
5915
5916     if (po->op == OP_CALL)
5917     {
5918       pp = process_call_early(i, opcnt, &j);
5919       if (pp != NULL) {
5920         if (!(po->flags & OPF_ATAIL))
5921           // since we know the args, try to collect them
5922           if (collect_call_args_early(po, i, pp, &regmask_dummy) != 0)
5923             pp = NULL;
5924       }
5925
5926       if (pp != NULL) {
5927         if (j >= 0) {
5928           // commit esp adjust
5929           ops[j].flags |= OPF_RMD;
5930           if (ops[j].op != OP_POP)
5931             patch_esp_adjust(&ops[j], pp->argc_stack * 4);
5932           else
5933             ops[j].flags |= OPF_DONE;
5934         }
5935
5936         po->flags |= OPF_DONE;
5937       }
5938     }
5939   }
5940
5941   // pass5:
5942   // - track saved regs (simple)
5943   // - process calls
5944   for (i = 0; i < opcnt; i++)
5945   {
5946     po = &ops[i];
5947     if (po->flags & (OPF_RMD|OPF_DONE))
5948       continue;
5949
5950     if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
5951     {
5952       ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
5953       if (ret == 0) {
5954         // regmask_save |= 1 << po->operand[0].reg; // do it later
5955         po->flags |= OPF_RSAVE | OPF_RMD | OPF_DONE;
5956         scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, OPF_RMD);
5957       }
5958     }
5959     else if (po->op == OP_CALL && !(po->flags & OPF_DONE))
5960     {
5961       pp = process_call(i, opcnt);
5962
5963       if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
5964         // since we know the args, collect them
5965         ret = collect_call_args(po, i, pp, &regmask_dummy, save_arg_vars,
5966           i + opcnt * 1);
5967       }
5968     }
5969   }
5970
5971   // pass6
5972   memset(cbits, 0, sizeof(cbits));
5973   regmask_dep = 0;
5974   has_ret = -1;
5975
5976   gen_hdr_dep_pass(0, opcnt, cbits, fp, 0, 0, &regmask_dep, &has_ret);
5977
5978   // find unreachable code - must be fixed in IDA
5979   for (i = 0; i < opcnt; i++)
5980   {
5981     if (cbits[i >> 3] & (1 << (i & 7)))
5982       continue;
5983
5984     if (ops[i].op != OP_NOP)
5985       ferr(&ops[i], "unreachable code\n");
5986   }
5987
5988   if (has_ret == -1 && (regmask_dep & (1 << xAX)))
5989     has_ret = 1;
5990
5991   for (i = 0; i < g_eqcnt; i++) {
5992     if (g_eqs[i].offset > max_bp_offset && g_eqs[i].offset < 4*32)
5993       max_bp_offset = g_eqs[i].offset;
5994   }
5995
5996   if (fp->argc_stack < 0) {
5997     max_bp_offset = (max_bp_offset + 3) & ~3;
5998     fp->argc_stack = max_bp_offset / 4;
5999     if ((g_ida_func_attr & IDAFA_BP_FRAME) && fp->argc_stack > 0)
6000       fp->argc_stack--;
6001   }
6002
6003   fp->regmask_dep = regmask_dep & ~(1 << xSP);
6004   fp->has_ret = has_ret;
6005 #if 0
6006   printf("// has_ret %d, regmask_dep %x\n",
6007     fp->has_ret, fp->regmask_dep);
6008   output_hdr_fp(stdout, fp, 1);
6009   if (IS(funcn, "sub_100073FD")) exit(1);
6010 #endif
6011
6012   gen_x_cleanup(opcnt);
6013 }
6014
6015 static void hg_fp_resolve_deps(struct func_prototype *fp)
6016 {
6017   struct func_prototype fp_s;
6018   int dep;
6019   int i;
6020
6021   // this thing is recursive, so mark first..
6022   fp->dep_resolved = 1;
6023
6024   for (i = 0; i < fp->dep_func_cnt; i++) {
6025     strcpy(fp_s.name, fp->dep_func[i].name);
6026     fp->dep_func[i].proto = bsearch(&fp_s, hg_fp, hg_fp_cnt,
6027       sizeof(hg_fp[0]), hg_fp_cmp_name);
6028     if (fp->dep_func[i].proto != NULL) {
6029       if (!fp->dep_func[i].proto->dep_resolved)
6030         hg_fp_resolve_deps(fp->dep_func[i].proto);
6031
6032       dep = ~fp->dep_func[i].regmask_live
6033            & fp->dep_func[i].proto->regmask_dep;
6034       fp->regmask_dep |= dep;
6035       // printf("dep %s %s |= %x\n", fp->name,
6036       //   fp->dep_func[i].name, dep);
6037
6038       if (fp->has_ret == -1)
6039         fp->has_ret = fp->dep_func[i].proto->has_ret;
6040     }
6041   }
6042 }
6043
6044 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
6045   int count)
6046 {
6047   const struct parsed_proto *pp;
6048   char *p, namebuf[NAMELEN];
6049   const char *name;
6050   int regmask_dep;
6051   int argc_stack;
6052   int j, arg;
6053
6054   for (; count > 0; count--, fp++) {
6055     if (fp->has_ret == -1)
6056       fprintf(fout, "// ret unresolved\n");
6057 #if 0
6058     fprintf(fout, "// dep:");
6059     for (j = 0; j < fp->dep_func_cnt; j++) {
6060       fprintf(fout, " %s/", fp->dep_func[j].name);
6061       if (fp->dep_func[j].proto != NULL)
6062         fprintf(fout, "%04x/%d", fp->dep_func[j].proto->regmask_dep,
6063           fp->dep_func[j].proto->has_ret);
6064     }
6065     fprintf(fout, "\n");
6066 #endif
6067
6068     p = strchr(fp->name, '@');
6069     if (p != NULL) {
6070       memcpy(namebuf, fp->name, p - fp->name);
6071       namebuf[p - fp->name] = 0;
6072       name = namebuf;
6073     }
6074     else
6075       name = fp->name;
6076     if (name[0] == '_')
6077       name++;
6078
6079     pp = proto_parse(g_fhdr, name, 1);
6080     if (pp != NULL && pp->is_include)
6081       continue;
6082
6083     if (fp->pp != NULL) {
6084       // part of seed, output later
6085       continue;
6086     }
6087
6088     regmask_dep = fp->regmask_dep;
6089     argc_stack = fp->argc_stack;
6090
6091     fprintf(fout, "%-5s", fp->pp ? fp->pp->ret_type.name :
6092       (fp->has_ret ? "int" : "void"));
6093     if (regmask_dep && (fp->is_stdcall || argc_stack == 0)
6094       && (regmask_dep & ~((1 << xCX) | (1 << xDX))) == 0)
6095     {
6096       fprintf(fout, "  __fastcall    ");
6097       if (!(regmask_dep & (1 << xDX)) && argc_stack == 0)
6098         argc_stack = 1;
6099       else
6100         argc_stack += 2;
6101       regmask_dep = 0;
6102     }
6103     else if (regmask_dep && !fp->is_stdcall) {
6104       fprintf(fout, "/*__usercall*/  ");
6105     }
6106     else if (regmask_dep) {
6107       fprintf(fout, "/*__userpurge*/ ");
6108     }
6109     else if (fp->is_stdcall)
6110       fprintf(fout, "  __stdcall     ");
6111     else
6112       fprintf(fout, "  __cdecl       ");
6113
6114     fprintf(fout, "%s(", name);
6115
6116     arg = 0;
6117     for (j = 0; j < xSP; j++) {
6118       if (regmask_dep & (1 << j)) {
6119         arg++;
6120         if (arg != 1)
6121           fprintf(fout, ", ");
6122         if (fp->pp != NULL)
6123           fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6124         else
6125           fprintf(fout, "int");
6126         fprintf(fout, " a%d/*<%s>*/", arg, regs_r32[j]);
6127       }
6128     }
6129
6130     for (j = 0; j < argc_stack; j++) {
6131       arg++;
6132       if (arg != 1)
6133         fprintf(fout, ", ");
6134       if (fp->pp != NULL) {
6135         fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6136         if (!fp->pp->arg[arg - 1].type.is_ptr)
6137           fprintf(fout, " ");
6138       }
6139       else
6140         fprintf(fout, "int ");
6141       fprintf(fout, "a%d", arg);
6142     }
6143
6144     fprintf(fout, ");\n");
6145   }
6146 }
6147
6148 static void output_hdr(FILE *fout)
6149 {
6150   static const char *lmod_c_names[] = {
6151     [OPLM_UNSPEC] = "???",
6152     [OPLM_BYTE]  = "uint8_t",
6153     [OPLM_WORD]  = "uint16_t",
6154     [OPLM_DWORD] = "uint32_t",
6155     [OPLM_QWORD] = "uint64_t",
6156   };
6157   const struct scanned_var *var;
6158   char line[256] = { 0, };
6159   int i;
6160
6161   // resolve deps
6162   qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_name);
6163   for (i = 0; i < hg_fp_cnt; i++)
6164     hg_fp_resolve_deps(&hg_fp[i]);
6165
6166   // note: messes up .proto ptr, don't use
6167   //qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_id);
6168
6169   // output variables
6170   for (i = 0; i < hg_var_cnt; i++) {
6171     var = &hg_vars[i];
6172
6173     if (var->pp != NULL)
6174       // part of seed
6175       continue;
6176     else if (var->is_c_str)
6177       fprintf(fout, "extern %-8s %s[];", "char", var->name);
6178     else
6179       fprintf(fout, "extern %-8s %s;",
6180         lmod_c_names[var->lmod], var->name);
6181
6182     if (var->is_seeded)
6183       fprintf(fout, " // seeded");
6184     fprintf(fout, "\n");
6185   }
6186
6187   fprintf(fout, "\n");
6188
6189   // output function prototypes
6190   output_hdr_fp(fout, hg_fp, hg_fp_cnt);
6191
6192   // seed passthrough
6193   fprintf(fout, "\n// - seed -\n");
6194
6195   rewind(g_fhdr);
6196   while (fgets(line, sizeof(line), g_fhdr))
6197     fwrite(line, 1, strlen(line), fout);
6198 }
6199
6200 // read a line, truncating it if it doesn't fit
6201 static char *my_fgets(char *s, size_t size, FILE *stream)
6202 {
6203   char *ret, *ret2;
6204   char buf[64];
6205   int p;
6206
6207   p = size - 2;
6208   if (p >= 0)
6209     s[p] = 0;
6210
6211   ret = fgets(s, size, stream);
6212   if (ret != NULL && p >= 0 && s[p] != 0 && s[p] != '\n') {
6213     p = sizeof(buf) - 2;
6214     do {
6215       buf[p] = 0;
6216       ret2 = fgets(buf, sizeof(buf), stream);
6217     }
6218     while (ret2 != NULL && buf[p] != 0 && buf[p] != '\n');
6219   }
6220
6221   return ret;
6222 }
6223
6224 // '=' needs special treatment
6225 // also ' quote
6226 static char *next_word_s(char *w, size_t wsize, char *s)
6227 {
6228   size_t i;
6229
6230   s = sskip(s);
6231
6232   i = 0;
6233   if (*s == '\'') {
6234     w[0] = s[0];
6235     for (i = 1; i < wsize - 1; i++) {
6236       if (s[i] == 0) {
6237         printf("warning: missing closing quote: \"%s\"\n", s);
6238         break;
6239       }
6240       if (s[i] == '\'')
6241         break;
6242       w[i] = s[i];
6243     }
6244   }
6245
6246   for (; i < wsize - 1; i++) {
6247     if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
6248       break;
6249     w[i] = s[i];
6250   }
6251   w[i] = 0;
6252
6253   if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
6254     printf("warning: '%s' truncated\n", w);
6255
6256   return s + i;
6257 }
6258
6259 static void scan_variables(FILE *fasm)
6260 {
6261   struct scanned_var *var;
6262   char line[256] = { 0, };
6263   char words[3][256];
6264   char *p = NULL;
6265   int wordc;
6266   int l;
6267
6268   while (!feof(fasm))
6269   {
6270     // skip to next data section
6271     while (my_fgets(line, sizeof(line), fasm))
6272     {
6273       asmln++;
6274
6275       p = sskip(line);
6276       if (*p == 0 || *p == ';')
6277         continue;
6278
6279       p = sskip(next_word_s(words[0], sizeof(words[0]), p));
6280       if (*p == 0 || *p == ';')
6281         continue;
6282
6283       if (*p != 's' || !IS_START(p, "segment para public"))
6284         continue;
6285
6286       break;
6287     }
6288
6289     if (p == NULL || !IS_START(p, "segment para public"))
6290       break;
6291     p = sskip(p + 19);
6292
6293     if (!IS_START(p, "'DATA'"))
6294       continue;
6295
6296     // now process it
6297     while (my_fgets(line, sizeof(line), fasm))
6298     {
6299       asmln++;
6300
6301       p = line;
6302       if (my_isblank(*p))
6303         continue;
6304
6305       p = sskip(p);
6306       if (*p == 0 || *p == ';')
6307         continue;
6308
6309       for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6310         words[wordc][0] = 0;
6311         p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6312         if (*p == 0 || *p == ';') {
6313           wordc++;
6314           break;
6315         }
6316       }
6317
6318       if (wordc == 2 && IS(words[1], "ends"))
6319         break;
6320       if (wordc < 2)
6321         continue;
6322
6323       if ((hg_var_cnt & 0xff) == 0) {
6324         hg_vars = realloc(hg_vars, sizeof(hg_vars[0])
6325                    * (hg_var_cnt + 0x100));
6326         my_assert_not(hg_vars, NULL);
6327         memset(hg_vars + hg_var_cnt, 0, sizeof(hg_vars[0]) * 0x100);
6328       }
6329
6330       var = &hg_vars[hg_var_cnt++];
6331       snprintf(var->name, sizeof(var->name), "%s", words[0]);
6332
6333       // maybe already in seed header?
6334       var->pp = proto_parse(g_fhdr, var->name, 1);
6335       if (var->pp != NULL) {
6336         if (var->pp->is_fptr) {
6337           var->lmod = OPLM_DWORD;
6338           //var->is_ptr = 1;
6339         }
6340         else if (var->pp->is_func)
6341           aerr("func?\n");
6342         else if (!guess_lmod_from_c_type(&var->lmod, &var->pp->type))
6343           aerr("unhandled C type '%s' for '%s'\n",
6344             var->pp->type.name, var->name);
6345
6346         var->is_seeded = 1;
6347         continue;
6348       }
6349
6350       if      (IS(words[1], "dd"))
6351         var->lmod = OPLM_DWORD;
6352       else if (IS(words[1], "dw"))
6353         var->lmod = OPLM_WORD;
6354       else if (IS(words[1], "db")) {
6355         var->lmod = OPLM_BYTE;
6356         if (wordc >= 3 && (l = strlen(words[2])) > 4) {
6357           if (words[2][0] == '\'' && IS(words[2] + l - 2, ",0"))
6358             var->is_c_str = 1;
6359         }
6360       }
6361       else if (IS(words[1], "dq"))
6362         var->lmod = OPLM_QWORD;
6363       //else if (IS(words[1], "dt"))
6364       else
6365         aerr("type '%s' not known\n", words[1]);
6366     }
6367   }
6368
6369   rewind(fasm);
6370   asmln = 0;
6371 }
6372
6373 static void set_label(int i, const char *name)
6374 {
6375   const char *p;
6376   int len;
6377
6378   len = strlen(name);
6379   p = strchr(name, ':');
6380   if (p != NULL)
6381     len = p - name;
6382
6383   if (g_labels[i] != NULL && !IS_START(g_labels[i], "algn_"))
6384     aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
6385   g_labels[i] = realloc(g_labels[i], len + 1);
6386   my_assert_not(g_labels[i], NULL);
6387   memcpy(g_labels[i], name, len);
6388   g_labels[i][len] = 0;
6389 }
6390
6391 struct chunk_item {
6392   char *name;
6393   long fptr;
6394   int asmln;
6395 };
6396
6397 static struct chunk_item *func_chunks;
6398 static int func_chunk_cnt;
6399 static int func_chunk_alloc;
6400
6401 static void add_func_chunk(FILE *fasm, const char *name, int line)
6402 {
6403   if (func_chunk_cnt >= func_chunk_alloc) {
6404     func_chunk_alloc *= 2;
6405     func_chunks = realloc(func_chunks,
6406       func_chunk_alloc * sizeof(func_chunks[0]));
6407     my_assert_not(func_chunks, NULL);
6408   }
6409   func_chunks[func_chunk_cnt].fptr = ftell(fasm);
6410   func_chunks[func_chunk_cnt].name = strdup(name);
6411   func_chunks[func_chunk_cnt].asmln = line;
6412   func_chunk_cnt++;
6413 }
6414
6415 static int cmp_chunks(const void *p1, const void *p2)
6416 {
6417   const struct chunk_item *c1 = p1, *c2 = p2;
6418   return strcmp(c1->name, c2->name);
6419 }
6420
6421 static int cmpstringp(const void *p1, const void *p2)
6422 {
6423   return strcmp(*(char * const *)p1, *(char * const *)p2);
6424 }
6425
6426 static void scan_ahead(FILE *fasm)
6427 {
6428   char words[2][256];
6429   char line[256];
6430   long oldpos;
6431   int oldasmln;
6432   int wordc;
6433   char *p;
6434   int i;
6435
6436   oldpos = ftell(fasm);
6437   oldasmln = asmln;
6438
6439   while (my_fgets(line, sizeof(line), fasm))
6440   {
6441     wordc = 0;
6442     asmln++;
6443
6444     p = sskip(line);
6445     if (*p == 0)
6446       continue;
6447
6448     if (*p == ';')
6449     {
6450       // get rid of random tabs
6451       for (i = 0; line[i] != 0; i++)
6452         if (line[i] == '\t')
6453           line[i] = ' ';
6454
6455       if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6456       {
6457         p += 30;
6458         next_word(words[0], sizeof(words[0]), p);
6459         if (words[0][0] == 0)
6460           aerr("missing name for func chunk?\n");
6461
6462         add_func_chunk(fasm, words[0], asmln);
6463       }
6464       else if (IS_START(p, "; sctend"))
6465         break;
6466
6467       continue;
6468     } // *p == ';'
6469
6470     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6471       words[wordc][0] = 0;
6472       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6473       if (*p == 0 || *p == ';') {
6474         wordc++;
6475         break;
6476       }
6477     }
6478
6479     if (wordc == 2 && IS(words[1], "ends"))
6480       break;
6481   }
6482
6483   fseek(fasm, oldpos, SEEK_SET);
6484   asmln = oldasmln;
6485 }
6486
6487 int main(int argc, char *argv[])
6488 {
6489   FILE *fout, *fasm, *frlist;
6490   struct parsed_data *pd = NULL;
6491   int pd_alloc = 0;
6492   char **rlist = NULL;
6493   int rlist_len = 0;
6494   int rlist_alloc = 0;
6495   int func_chunks_used = 0;
6496   int func_chunks_sorted = 0;
6497   int func_chunk_i = -1;
6498   long func_chunk_ret = 0;
6499   int func_chunk_ret_ln = 0;
6500   int scanned_ahead = 0;
6501   char line[256];
6502   char words[20][256];
6503   enum opr_lenmod lmod;
6504   char *sctproto = NULL;
6505   int in_func = 0;
6506   int pending_endp = 0;
6507   int skip_func = 0;
6508   int skip_warned = 0;
6509   int eq_alloc;
6510   int verbose = 0;
6511   int multi_seg = 0;
6512   int end = 0;
6513   int arg_out;
6514   int arg;
6515   int pi = 0;
6516   int i, j;
6517   int ret, len;
6518   char *p;
6519   int wordc;
6520
6521   for (arg = 1; arg < argc; arg++) {
6522     if (IS(argv[arg], "-v"))
6523       verbose = 1;
6524     else if (IS(argv[arg], "-rf"))
6525       g_allow_regfunc = 1;
6526     else if (IS(argv[arg], "-m"))
6527       multi_seg = 1;
6528     else if (IS(argv[arg], "-hdr"))
6529       g_header_mode = g_quiet_pp = g_allow_regfunc = 1;
6530     else
6531       break;
6532   }
6533
6534   if (argc < arg + 3) {
6535     printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdr.h> [rlist]*\n"
6536            "%s -hdr <out.h> <.asm> <seed.h> [rlist]*\n"
6537            "options:\n"
6538            "  -hdr - header generation mode\n"
6539            "  -rf  - allow unannotated indirect calls\n"
6540            "  -m   - allow multiple .text sections\n"
6541            "[rlist] is a file with function names to skip,"
6542            " one per line\n",
6543       argv[0], argv[0]);
6544     return 1;
6545   }
6546
6547   arg_out = arg++;
6548
6549   asmfn = argv[arg++];
6550   fasm = fopen(asmfn, "r");
6551   my_assert_not(fasm, NULL);
6552
6553   hdrfn = argv[arg++];
6554   g_fhdr = fopen(hdrfn, "r");
6555   my_assert_not(g_fhdr, NULL);
6556
6557   rlist_alloc = 64;
6558   rlist = malloc(rlist_alloc * sizeof(rlist[0]));
6559   my_assert_not(rlist, NULL);
6560   // needs special handling..
6561   rlist[rlist_len++] = "__alloca_probe";
6562
6563   func_chunk_alloc = 32;
6564   func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
6565   my_assert_not(func_chunks, NULL);
6566
6567   memset(words, 0, sizeof(words));
6568
6569   for (; arg < argc; arg++) {
6570     frlist = fopen(argv[arg], "r");
6571     my_assert_not(frlist, NULL);
6572
6573     while (my_fgets(line, sizeof(line), frlist)) {
6574       p = sskip(line);
6575       if (*p == 0 || *p == ';')
6576         continue;
6577       if (*p == '#') {
6578         if (IS_START(p, "#if 0")
6579          || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
6580         {
6581           skip_func = 1;
6582         }
6583         else if (IS_START(p, "#endif"))
6584           skip_func = 0;
6585         continue;
6586       }
6587       if (skip_func)
6588         continue;
6589
6590       p = next_word(words[0], sizeof(words[0]), p);
6591       if (words[0][0] == 0)
6592         continue;
6593
6594       if (rlist_len >= rlist_alloc) {
6595         rlist_alloc = rlist_alloc * 2 + 64;
6596         rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
6597         my_assert_not(rlist, NULL);
6598       }
6599       rlist[rlist_len++] = strdup(words[0]);
6600     }
6601     skip_func = 0;
6602
6603     fclose(frlist);
6604     frlist = NULL;
6605   }
6606
6607   if (rlist_len > 0)
6608     qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
6609
6610   fout = fopen(argv[arg_out], "w");
6611   my_assert_not(fout, NULL);
6612
6613   eq_alloc = 128;
6614   g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
6615   my_assert_not(g_eqs, NULL);
6616
6617   for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
6618     g_label_refs[i].i = -1;
6619     g_label_refs[i].next = NULL;
6620   }
6621
6622   if (g_header_mode)
6623     scan_variables(fasm);
6624
6625   while (my_fgets(line, sizeof(line), fasm))
6626   {
6627     wordc = 0;
6628     asmln++;
6629
6630     p = sskip(line);
6631     if (*p == 0)
6632       continue;
6633
6634     // get rid of random tabs
6635     for (i = 0; line[i] != 0; i++)
6636       if (line[i] == '\t')
6637         line[i] = ' ';
6638
6639     if (*p == ';')
6640     {
6641       if (p[2] == '=' && IS_START(p, "; =============== S U B"))
6642         goto do_pending_endp; // eww..
6643
6644       if (p[2] == 'A' && IS_START(p, "; Attributes:"))
6645       {
6646         static const char *attrs[] = {
6647           "bp-based frame",
6648           "library function",
6649           "static",
6650           "noreturn",
6651           "thunk",
6652           "fpd=",
6653         };
6654
6655         // parse IDA's attribute-list comment
6656         g_ida_func_attr = 0;
6657         p = sskip(p + 13);
6658
6659         for (; *p != 0; p = sskip(p)) {
6660           for (i = 0; i < ARRAY_SIZE(attrs); i++) {
6661             if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
6662               g_ida_func_attr |= 1 << i;
6663               p += strlen(attrs[i]);
6664               break;
6665             }
6666           }
6667           if (i == ARRAY_SIZE(attrs)) {
6668             anote("unparsed IDA attr: %s\n", p);
6669             break;
6670           }
6671           if (IS(attrs[i], "fpd=")) {
6672             p = next_word(words[0], sizeof(words[0]), p);
6673             // ignore for now..
6674           }
6675         }
6676       }
6677       else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6678       {
6679         p += 30;
6680         next_word(words[0], sizeof(words[0]), p);
6681         if (words[0][0] == 0)
6682           aerr("missing name for func chunk?\n");
6683
6684         if (!scanned_ahead) {
6685           add_func_chunk(fasm, words[0], asmln);
6686           func_chunks_sorted = 0;
6687         }
6688       }
6689       else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
6690       {
6691         if (func_chunk_i >= 0) {
6692           if (func_chunk_i < func_chunk_cnt
6693             && IS(func_chunks[func_chunk_i].name, g_func))
6694           {
6695             // move on to next chunk
6696             ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
6697             if (ret)
6698               aerr("seek failed for '%s' chunk #%d\n",
6699                 g_func, func_chunk_i);
6700             asmln = func_chunks[func_chunk_i].asmln;
6701             func_chunk_i++;
6702           }
6703           else {
6704             if (func_chunk_ret == 0)
6705               aerr("no return from chunk?\n");
6706             fseek(fasm, func_chunk_ret, SEEK_SET);
6707             asmln = func_chunk_ret_ln;
6708             func_chunk_ret = 0;
6709             pending_endp = 1;
6710           }
6711         }
6712       }
6713       else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
6714         func_chunks_used = 1;
6715         p += 20;
6716         if (IS_START(g_func, "sub_")) {
6717           unsigned long addr = strtoul(p, NULL, 16);
6718           unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
6719           if (addr > f_addr && !scanned_ahead) {
6720             anote("scan_ahead caused by '%s', addr %lx\n",
6721               g_func, addr);
6722             scan_ahead(fasm);
6723             scanned_ahead = 1;
6724             func_chunks_sorted = 0;
6725           }
6726         }
6727       }
6728       continue;
6729     } // *p == ';'
6730
6731 parse_words:
6732     for (i = wordc; i < ARRAY_SIZE(words); i++)
6733       words[i][0] = 0;
6734     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6735       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6736       if (*p == 0 || *p == ';') {
6737         wordc++;
6738         break;
6739       }
6740     }
6741     if (*p != 0 && *p != ';')
6742       aerr("too many words\n");
6743
6744     // alow asm patches in comments
6745     if (*p == ';') {
6746       if (IS_START(p, "; sctpatch:")) {
6747         p = sskip(p + 11);
6748         if (*p == 0 || *p == ';')
6749           continue;
6750         goto parse_words; // lame
6751       }
6752       if (IS_START(p, "; sctproto:")) {
6753         sctproto = strdup(p + 11);
6754       }
6755       else if (IS_START(p, "; sctend")) {
6756         end = 1;
6757         if (!pending_endp)
6758           break;
6759       }
6760     }
6761
6762     if (wordc == 0) {
6763       // shouldn't happen
6764       awarn("wordc == 0?\n");
6765       continue;
6766     }
6767
6768     // don't care about this:
6769     if (words[0][0] == '.'
6770         || IS(words[0], "include")
6771         || IS(words[0], "assume") || IS(words[1], "segment")
6772         || IS(words[0], "align"))
6773     {
6774       continue;
6775     }
6776
6777 do_pending_endp:
6778     // do delayed endp processing to collect switch jumptables
6779     if (pending_endp) {
6780       if (in_func && !g_skip_func && !end && wordc >= 2
6781           && ((words[0][0] == 'd' && words[0][2] == 0)
6782               || (words[1][0] == 'd' && words[1][2] == 0)))
6783       {
6784         i = 1;
6785         if (words[1][0] == 'd' && words[1][2] == 0) {
6786           // label
6787           if (g_func_pd_cnt >= pd_alloc) {
6788             pd_alloc = pd_alloc * 2 + 16;
6789             g_func_pd = realloc(g_func_pd,
6790               sizeof(g_func_pd[0]) * pd_alloc);
6791             my_assert_not(g_func_pd, NULL);
6792           }
6793           pd = &g_func_pd[g_func_pd_cnt];
6794           g_func_pd_cnt++;
6795           memset(pd, 0, sizeof(*pd));
6796           strcpy(pd->label, words[0]);
6797           pd->type = OPT_CONST;
6798           pd->lmod = lmod_from_directive(words[1]);
6799           i = 2;
6800         }
6801         else {
6802           if (pd == NULL) {
6803             if (verbose)
6804               anote("skipping alignment byte?\n");
6805             continue;
6806           }
6807           lmod = lmod_from_directive(words[0]);
6808           if (lmod != pd->lmod)
6809             aerr("lmod change? %d->%d\n", pd->lmod, lmod);
6810         }
6811
6812         if (pd->count_alloc < pd->count + wordc) {
6813           pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
6814           pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
6815           my_assert_not(pd->d, NULL);
6816         }
6817         for (; i < wordc; i++) {
6818           if (IS(words[i], "offset")) {
6819             pd->type = OPT_OFFSET;
6820             i++;
6821           }
6822           p = strchr(words[i], ',');
6823           if (p != NULL)
6824             *p = 0;
6825           if (pd->type == OPT_OFFSET)
6826             pd->d[pd->count].u.label = strdup(words[i]);
6827           else
6828             pd->d[pd->count].u.val = parse_number(words[i]);
6829           pd->d[pd->count].bt_i = -1;
6830           pd->count++;
6831         }
6832         continue;
6833       }
6834
6835       if (in_func && !g_skip_func) {
6836         if (g_header_mode)
6837           gen_hdr(g_func, pi);
6838         else
6839           gen_func(fout, g_fhdr, g_func, pi);
6840       }
6841
6842       pending_endp = 0;
6843       in_func = 0;
6844       g_ida_func_attr = 0;
6845       skip_warned = 0;
6846       g_skip_func = 0;
6847       g_func[0] = 0;
6848       func_chunks_used = 0;
6849       func_chunk_i = -1;
6850       if (pi != 0) {
6851         memset(&ops, 0, pi * sizeof(ops[0]));
6852         clear_labels(pi);
6853         pi = 0;
6854       }
6855       g_eqcnt = 0;
6856       for (i = 0; i < g_func_pd_cnt; i++) {
6857         pd = &g_func_pd[i];
6858         if (pd->type == OPT_OFFSET) {
6859           for (j = 0; j < pd->count; j++)
6860             free(pd->d[j].u.label);
6861         }
6862         free(pd->d);
6863         pd->d = NULL;
6864       }
6865       g_func_pd_cnt = 0;
6866       pd = NULL;
6867
6868       if (end)
6869         break;
6870       if (wordc == 0)
6871         continue;
6872     }
6873
6874     if (IS(words[1], "proc")) {
6875       if (in_func)
6876         aerr("proc '%s' while in_func '%s'?\n",
6877           words[0], g_func);
6878       p = words[0];
6879       if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
6880         g_skip_func = 1;
6881       strcpy(g_func, words[0]);
6882       set_label(0, words[0]);
6883       in_func = 1;
6884       continue;
6885     }
6886
6887     if (IS(words[1], "endp"))
6888     {
6889       if (!in_func)
6890         aerr("endp '%s' while not in_func?\n", words[0]);
6891       if (!IS(g_func, words[0]))
6892         aerr("endp '%s' while in_func '%s'?\n",
6893           words[0], g_func);
6894
6895       if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
6896         && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
6897       {
6898         // import jump
6899         g_skip_func = 1;
6900       }
6901
6902       if (!g_skip_func && func_chunks_used) {
6903         // start processing chunks
6904         struct chunk_item *ci, key = { g_func, 0 };
6905
6906         func_chunk_ret = ftell(fasm);
6907         func_chunk_ret_ln = asmln;
6908         if (!func_chunks_sorted) {
6909           qsort(func_chunks, func_chunk_cnt,
6910             sizeof(func_chunks[0]), cmp_chunks);
6911           func_chunks_sorted = 1;
6912         }
6913         ci = bsearch(&key, func_chunks, func_chunk_cnt,
6914                sizeof(func_chunks[0]), cmp_chunks);
6915         if (ci == NULL)
6916           aerr("'%s' needs chunks, but none found\n", g_func);
6917         func_chunk_i = ci - func_chunks;
6918         for (; func_chunk_i > 0; func_chunk_i--)
6919           if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
6920             break;
6921
6922         ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
6923         if (ret)
6924           aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
6925         asmln = func_chunks[func_chunk_i].asmln;
6926         func_chunk_i++;
6927         continue;
6928       }
6929       pending_endp = 1;
6930       continue;
6931     }
6932
6933     if (wordc == 2 && IS(words[1], "ends")) {
6934       if (!multi_seg) {
6935         end = 1;
6936         if (pending_endp)
6937           goto do_pending_endp;
6938         break;
6939       }
6940
6941       // scan for next text segment
6942       while (my_fgets(line, sizeof(line), fasm)) {
6943         asmln++;
6944         p = sskip(line);
6945         if (*p == 0 || *p == ';')
6946           continue;
6947
6948         if (strstr(p, "segment para public 'CODE' use32"))
6949           break;
6950       }
6951
6952       continue;
6953     }
6954
6955     p = strchr(words[0], ':');
6956     if (p != NULL) {
6957       set_label(pi, words[0]);
6958       continue;
6959     }
6960
6961     if (!in_func || g_skip_func) {
6962       if (!skip_warned && !g_skip_func && g_labels[pi] != NULL) {
6963         if (verbose)
6964           anote("skipping from '%s'\n", g_labels[pi]);
6965         skip_warned = 1;
6966       }
6967       free(g_labels[pi]);
6968       g_labels[pi] = NULL;
6969       continue;
6970     }
6971
6972     if (wordc > 1 && IS(words[1], "="))
6973     {
6974       if (wordc != 5)
6975         aerr("unhandled equ, wc=%d\n", wordc);
6976       if (g_eqcnt >= eq_alloc) {
6977         eq_alloc *= 2;
6978         g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
6979         my_assert_not(g_eqs, NULL);
6980       }
6981
6982       len = strlen(words[0]);
6983       if (len > sizeof(g_eqs[0].name) - 1)
6984         aerr("equ name too long: %d\n", len);
6985       strcpy(g_eqs[g_eqcnt].name, words[0]);
6986
6987       if (!IS(words[3], "ptr"))
6988         aerr("unhandled equ\n");
6989       if (IS(words[2], "dword"))
6990         g_eqs[g_eqcnt].lmod = OPLM_DWORD;
6991       else if (IS(words[2], "word"))
6992         g_eqs[g_eqcnt].lmod = OPLM_WORD;
6993       else if (IS(words[2], "byte"))
6994         g_eqs[g_eqcnt].lmod = OPLM_BYTE;
6995       else if (IS(words[2], "qword"))
6996         g_eqs[g_eqcnt].lmod = OPLM_QWORD;
6997       else
6998         aerr("bad lmod: '%s'\n", words[2]);
6999
7000       g_eqs[g_eqcnt].offset = parse_number(words[4]);
7001       g_eqcnt++;
7002       continue;
7003     }
7004
7005     if (pi >= ARRAY_SIZE(ops))
7006       aerr("too many ops\n");
7007
7008     parse_op(&ops[pi], words, wordc);
7009
7010     if (sctproto != NULL) {
7011       if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
7012         ops[pi].datap = sctproto;
7013       sctproto = NULL;
7014     }
7015     pi++;
7016   }
7017
7018   if (g_header_mode)
7019     output_hdr(fout);
7020
7021   fclose(fout);
7022   fclose(fasm);
7023   fclose(g_fhdr);
7024
7025   return 0;
7026 }
7027
7028 // vim:ts=2:shiftwidth=2:expandtab