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