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