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