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