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