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