translate: many improvements for header gen
[ia32rtools.git] / tools / translate.c
1 /*
2  * ia32rtools
3  * (C) notaz, 2013-2015
4  *
5  * This work is licensed under the terms of 3-clause BSD license.
6  * See COPYING file in the top-level directory.
7  */
8
9 #define _GNU_SOURCE
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13
14 #include "my_assert.h"
15 #include "my_str.h"
16
17 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
18 #define IS(w, y) !strcmp(w, y)
19 #define IS_START(w, y) !strncmp(w, y, strlen(y))
20
21 #include "protoparse.h"
22
23 static const char *asmfn;
24 static int asmln;
25 static FILE *g_fhdr;
26
27 #define anote(fmt, ...) \
28         printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
29 #define awarn(fmt, ...) \
30         printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
31 #define aerr(fmt, ...) do { \
32         printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
33   fcloseall(); \
34         exit(1); \
35 } while (0)
36
37 #include "masm_tools.h"
38
39 enum op_flags {
40   OPF_RMD    = (1 << 0), /* removed 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 // scan for positive, constant esp adjust
2525 static int scan_for_esp_adjust(int i, int opcnt,
2526   int adj_expect, int *adj, int *multipath)
2527 {
2528   struct parsed_op *po;
2529   int first_pop = -1;
2530
2531   *adj = *multipath = 0;
2532
2533   for (; i < opcnt && *adj < adj_expect; i++) {
2534     if (g_labels[i] != NULL)
2535       *multipath = 1;
2536
2537     po = &ops[i];
2538     if (po->flags & OPF_DONE)
2539       continue;
2540
2541     if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2542       if (po->operand[1].type != OPT_CONST)
2543         ferr(&ops[i], "non-const esp adjust?\n");
2544       *adj += po->operand[1].val;
2545       if (*adj & 3)
2546         ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2547       return i;
2548     }
2549     else if (po->op == OP_PUSH) {
2550       //if (first_pop == -1)
2551       //  first_pop = -2; // none
2552       *adj -= lmod_bytes(po, po->operand[0].lmod);
2553     }
2554     else if (po->op == OP_POP) {
2555       if (!(po->flags & OPF_DONE)) {
2556         // seems like msvc only uses 'pop ecx' for stack realignment..
2557         if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2558           break;
2559         if (first_pop == -1 && *adj >= 0)
2560           first_pop = i;
2561       }
2562       *adj += lmod_bytes(po, po->operand[0].lmod);
2563     }
2564     else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2565       if (po->op == OP_JMP && po->btj == NULL) {
2566         if (po->bt_i <= i)
2567           break;
2568         i = po->bt_i - 1;
2569         continue;
2570       }
2571       if (po->op != OP_CALL)
2572         break;
2573       if (po->operand[0].type != OPT_LABEL)
2574         break;
2575       if (po->pp != NULL && po->pp->is_stdcall)
2576         break;
2577       // assume it's another cdecl call
2578     }
2579   }
2580
2581   if (first_pop >= 0) {
2582     // probably 'pop ecx' was used..
2583     return first_pop;
2584   }
2585
2586   return -1;
2587 }
2588
2589 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2590 {
2591   struct parsed_op *po;
2592   int j;
2593
2594   if (i < 0)
2595     ferr(ops, "%s: followed bad branch?\n", __func__);
2596
2597   for (; i < opcnt; i++) {
2598     po = &ops[i];
2599     if (po->cc_scratch == magic)
2600       return;
2601     po->cc_scratch = magic;
2602     po->flags |= flags;
2603
2604     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2605       if (po->btj != NULL) {
2606         // jumptable
2607         for (j = 0; j < po->btj->count; j++)
2608           scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2609         return;
2610       }
2611
2612       scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2613       if (!(po->flags & OPF_CJMP))
2614         return;
2615     }
2616     if (po->flags & OPF_TAIL)
2617       return;
2618   }
2619 }
2620
2621 static const struct parsed_proto *try_recover_pp(
2622   struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2623 {
2624   const struct parsed_proto *pp = NULL;
2625   char buf[256];
2626   char *p;
2627
2628   // maybe an arg of g_func?
2629   if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2630   {
2631     char ofs_reg[16] = { 0, };
2632     int arg, arg_s, arg_i;
2633     int stack_ra = 0;
2634     int offset = 0;
2635
2636     if (g_header_mode)
2637       return NULL;
2638
2639     parse_stack_access(po, opr->name, ofs_reg,
2640       &offset, &stack_ra, NULL, 0);
2641     if (ofs_reg[0] != 0)
2642       ferr(po, "offset reg on arg access?\n");
2643     if (offset <= stack_ra) {
2644       // search who set the stack var instead
2645       if (search_instead != NULL)
2646         *search_instead = 1;
2647       return NULL;
2648     }
2649
2650     arg_i = (offset - stack_ra - 4) / 4;
2651     for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2652       if (g_func_pp->arg[arg].reg != NULL)
2653         continue;
2654       if (arg_s == arg_i)
2655         break;
2656       arg_s++;
2657     }
2658     if (arg == g_func_pp->argc)
2659       ferr(po, "stack arg %d not in prototype?\n", arg_i);
2660
2661     pp = g_func_pp->arg[arg].fptr;
2662     if (pp == NULL)
2663       ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2664     check_func_pp(po, pp, "icall arg");
2665   }
2666   else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2667     // label[index]
2668     p = strchr(opr->name + 1, '[');
2669     memcpy(buf, opr->name, p - opr->name);
2670     buf[p - opr->name] = 0;
2671     pp = proto_parse(g_fhdr, buf, g_quiet_pp);
2672   }
2673   else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2674     pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
2675     if (pp == NULL) {
2676       if (!g_header_mode)
2677         ferr(po, "proto_parse failed for icall to '%s'\n", opr->name);
2678     }
2679     else
2680       check_func_pp(po, pp, "reg-fptr ref");
2681   }
2682
2683   return pp;
2684 }
2685
2686 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2687   int magic, const struct parsed_proto **pp_found, int *multi)
2688 {
2689   const struct parsed_proto *pp = NULL;
2690   struct parsed_op *po;
2691   struct label_ref *lr;
2692
2693   ops[i].cc_scratch = magic;
2694
2695   while (1) {
2696     if (g_labels[i] != NULL) {
2697       lr = &g_label_refs[i];
2698       for (; lr != NULL; lr = lr->next) {
2699         check_i(&ops[i], lr->i);
2700         scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2701       }
2702       if (i > 0 && LAST_OP(i - 1))
2703         return;
2704     }
2705
2706     i--;
2707     if (i < 0)
2708       break;
2709
2710     if (ops[i].cc_scratch == magic)
2711       return;
2712     ops[i].cc_scratch = magic;
2713
2714     if (!(ops[i].flags & OPF_DATA))
2715       continue;
2716     if (!is_opr_modified(opr, &ops[i]))
2717       continue;
2718     if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2719       // most probably trashed by some processing
2720       *pp_found = NULL;
2721       return;
2722     }
2723
2724     opr = &ops[i].operand[1];
2725     if (opr->type != OPT_REG)
2726       break;
2727   }
2728
2729   po = (i >= 0) ? &ops[i] : ops;
2730
2731   if (i < 0) {
2732     // reached the top - can only be an arg-reg
2733     if (opr->type != OPT_REG)
2734       return;
2735
2736     for (i = 0; i < g_func_pp->argc; i++) {
2737       if (g_func_pp->arg[i].reg == NULL)
2738         continue;
2739       if (IS(opr->name, g_func_pp->arg[i].reg))
2740         break;
2741     }
2742     if (i == g_func_pp->argc)
2743       return;
2744     pp = g_func_pp->arg[i].fptr;
2745     if (pp == NULL)
2746       ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2747         i + 1, g_func_pp->arg[i].reg);
2748     check_func_pp(po, pp, "icall reg-arg");
2749   }
2750   else
2751     pp = try_recover_pp(po, opr, NULL);
2752
2753   if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2754     if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2755       || (*pp_found)->is_stdcall != pp->is_stdcall
2756       || (*pp_found)->is_fptr != pp->is_fptr
2757       || (*pp_found)->argc != pp->argc
2758       || (*pp_found)->argc_reg != pp->argc_reg
2759       || (*pp_found)->argc_stack != pp->argc_stack)
2760     {
2761       ferr(po, "icall: parsed_proto mismatch\n");
2762     }
2763     *multi = 1;
2764   }
2765   if (pp != NULL)
2766     *pp_found = pp;
2767 }
2768
2769 // early check for tail call or branch back
2770 static int is_like_tailjmp(int j)
2771 {
2772   if (!(ops[j].flags & OPF_JMP))
2773     return 0;
2774
2775   if (ops[j].op == OP_JMP && !ops[j].operand[0].had_ds)
2776     // probably local branch back..
2777     return 1;
2778   if (ops[j].op == OP_CALL)
2779     // probably noreturn call..
2780     return 1;
2781
2782   return 0;
2783 }
2784
2785 static void scan_prologue_epilogue(int opcnt)
2786 {
2787   int ecx_push = 0, esp_sub = 0;
2788   int found;
2789   int i, j, l;
2790
2791   if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2792       && ops[1].op == OP_MOV
2793       && IS(opr_name(&ops[1], 0), "ebp")
2794       && IS(opr_name(&ops[1], 1), "esp"))
2795   {
2796     g_bp_frame = 1;
2797     ops[0].flags |= OPF_RMD | OPF_DONE;
2798     ops[1].flags |= OPF_RMD | OPF_DONE;
2799     i = 2;
2800
2801     if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2802       g_stack_fsz = opr_const(&ops[2], 1);
2803       ops[2].flags |= OPF_RMD | OPF_DONE;
2804       i++;
2805     }
2806     else {
2807       // another way msvc builds stack frame..
2808       i = 2;
2809       while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2810         g_stack_fsz += 4;
2811         ops[i].flags |= OPF_RMD | OPF_DONE;
2812         ecx_push++;
2813         i++;
2814       }
2815       // and another way..
2816       if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2817           && ops[i].operand[1].type == OPT_CONST
2818           && ops[i + 1].op == OP_CALL
2819           && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2820       {
2821         g_stack_fsz += ops[i].operand[1].val;
2822         ops[i].flags |= OPF_RMD | OPF_DONE;
2823         i++;
2824         ops[i].flags |= OPF_RMD | OPF_DONE;
2825         i++;
2826       }
2827     }
2828
2829     found = 0;
2830     do {
2831       for (; i < opcnt; i++)
2832         if (ops[i].op == OP_RET)
2833           break;
2834       j = i - 1;
2835       if (i == opcnt && (ops[j].flags & OPF_JMP)) {
2836         if (found && is_like_tailjmp(j))
2837             break;
2838         j--;
2839       }
2840
2841       if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
2842           || ops[j].op == OP_LEAVE)
2843       {
2844         ops[j].flags |= OPF_RMD | OPF_DONE;
2845       }
2846       else if (!(g_ida_func_attr & IDAFA_NORETURN))
2847         ferr(&ops[j], "'pop ebp' expected\n");
2848
2849       if (g_stack_fsz != 0) {
2850         if (ops[j - 1].op == OP_MOV
2851             && IS(opr_name(&ops[j - 1], 0), "esp")
2852             && IS(opr_name(&ops[j - 1], 1), "ebp"))
2853         {
2854           ops[j - 1].flags |= OPF_RMD | OPF_DONE;
2855         }
2856         else if (ops[j].op != OP_LEAVE
2857           && !(g_ida_func_attr & IDAFA_NORETURN))
2858         {
2859           ferr(&ops[j - 1], "esp restore expected\n");
2860         }
2861
2862         if (ecx_push && ops[j - 2].op == OP_POP
2863           && IS(opr_name(&ops[j - 2], 0), "ecx"))
2864         {
2865           ferr(&ops[j - 2], "unexpected ecx pop\n");
2866         }
2867       }
2868
2869       found = 1;
2870       i++;
2871     } while (i < opcnt);
2872
2873     return;
2874   }
2875
2876   // non-bp frame
2877   i = 0;
2878   while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2879     ops[i].flags |= OPF_RMD | OPF_DONE;
2880     g_stack_fsz += 4;
2881     ecx_push++;
2882     i++;
2883   }
2884
2885   for (; i < opcnt; i++) {
2886     if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2887       break;
2888     if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2889       && ops[i].operand[1].type == OPT_CONST)
2890     {
2891       g_stack_fsz = ops[i].operand[1].val;
2892       ops[i].flags |= OPF_RMD | OPF_DONE;
2893       esp_sub = 1;
2894       break;
2895     }
2896   }
2897
2898   if (ecx_push && !esp_sub) {
2899     // could actually be args for a call..
2900     for (; i < opcnt; i++)
2901       if (ops[i].op != OP_PUSH)
2902         break;
2903
2904     if (ops[i].op == OP_CALL && ops[i].operand[0].type == OPT_LABEL) {
2905       const struct parsed_proto *pp;
2906       pp = proto_parse(g_fhdr, opr_name(&ops[i], 0), 1);
2907       j = pp ? pp->argc_stack : 0;
2908       while (i > 0 && j > 0) {
2909         i--;
2910         if (ops[i].op == OP_PUSH) {
2911           ops[i].flags &= ~(OPF_RMD | OPF_DONE);
2912           j--;
2913         }
2914       }
2915       if (j != 0)
2916         ferr(&ops[i], "unhandled prologue\n");
2917
2918       // recheck
2919       i = g_stack_fsz = ecx_push = 0;
2920       while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2921         if (!(ops[i].flags & OPF_RMD))
2922           break;
2923         g_stack_fsz += 4;
2924         ecx_push++;
2925         i++;
2926       }
2927     }
2928   }
2929
2930   found = 0;
2931   if (ecx_push || esp_sub)
2932   {
2933     g_sp_frame = 1;
2934
2935     i++;
2936     do {
2937       for (; i < opcnt; i++)
2938         if (ops[i].op == OP_RET)
2939           break;
2940       j = i - 1;
2941       if (i == opcnt && (ops[j].flags & OPF_JMP)) {
2942         if (found && is_like_tailjmp(j))
2943             break;
2944         j--;
2945       }
2946
2947       if (ecx_push > 0) {
2948         for (l = 0; l < ecx_push; l++) {
2949           if (ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ecx"))
2950             /* pop ecx */;
2951           else if (ops[j].op == OP_ADD
2952                    && IS(opr_name(&ops[j], 0), "esp")
2953                    && ops[j].operand[1].type == OPT_CONST)
2954           {
2955             /* add esp, N */
2956             l += ops[j].operand[1].val / 4 - 1;
2957           }
2958           else
2959             ferr(&ops[j], "'pop ecx' expected\n");
2960
2961           ops[j].flags |= OPF_RMD | OPF_DONE;
2962           j--;
2963         }
2964         if (l != ecx_push)
2965           ferr(&ops[j], "epilogue scan failed\n");
2966
2967         found = 1;
2968       }
2969
2970       if (esp_sub) {
2971         if (ops[j].op != OP_ADD
2972             || !IS(opr_name(&ops[j], 0), "esp")
2973             || ops[j].operand[1].type != OPT_CONST
2974             || ops[j].operand[1].val != g_stack_fsz)
2975           ferr(&ops[j], "'add esp' expected\n");
2976
2977         ops[j].flags |= OPF_RMD | OPF_DONE;
2978         ops[j].operand[1].val = 0; // hack for stack arg scanner
2979         found = 1;
2980       }
2981
2982       i++;
2983     } while (i < opcnt);
2984   }
2985 }
2986
2987 static const struct parsed_proto *resolve_icall(int i, int opcnt,
2988   int *multi_src)
2989 {
2990   const struct parsed_proto *pp = NULL;
2991   int search_advice = 0;
2992
2993   *multi_src = 0;
2994
2995   switch (ops[i].operand[0].type) {
2996   case OPT_REGMEM:
2997   case OPT_LABEL:
2998   case OPT_OFFSET:
2999     pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
3000     if (!search_advice)
3001       break;
3002     // fallthrough
3003   default:
3004     scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
3005       multi_src);
3006     break;
3007   }
3008
3009   return pp;
3010 }
3011
3012 // find an instruction that changed opr before i op
3013 // *op_i must be set to -1 by caller
3014 // *entry is set to 1 if one source is determined to be the caller
3015 // returns 1 if found, *op_i is then set to origin
3016 static int resolve_origin(int i, const struct parsed_opr *opr,
3017   int magic, int *op_i, int *is_caller)
3018 {
3019   struct label_ref *lr;
3020   int ret = 0;
3021
3022   if (ops[i].cc_scratch == magic)
3023     return 0;
3024   ops[i].cc_scratch = magic;
3025
3026   while (1) {
3027     if (g_labels[i] != NULL) {
3028       lr = &g_label_refs[i];
3029       for (; lr != NULL; lr = lr->next) {
3030         check_i(&ops[i], lr->i);
3031         ret |= resolve_origin(lr->i, opr, magic, op_i, is_caller);
3032       }
3033       if (i > 0 && LAST_OP(i - 1))
3034         return ret;
3035     }
3036
3037     i--;
3038     if (i < 0) {
3039       if (is_caller != NULL)
3040         *is_caller = 1;
3041       return -1;
3042     }
3043
3044     if (ops[i].cc_scratch == magic)
3045       return 0;
3046     ops[i].cc_scratch = magic;
3047
3048     if (!(ops[i].flags & OPF_DATA))
3049       continue;
3050     if (!is_opr_modified(opr, &ops[i]))
3051       continue;
3052
3053     if (*op_i >= 0) {
3054       if (*op_i == i)
3055         return 1;
3056       // XXX: could check if the other op does the same
3057       return -1;
3058     }
3059
3060     *op_i = i;
3061     return 1;
3062   }
3063 }
3064
3065 static int try_resolve_const(int i, const struct parsed_opr *opr,
3066   int magic, unsigned int *val)
3067 {
3068   int s_i = -1;
3069   int ret;
3070
3071   ret = resolve_origin(i, opr, magic, &s_i, NULL);
3072   if (ret == 1) {
3073     i = s_i;
3074     if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
3075       return -1;
3076
3077     *val = ops[i].operand[1].val;
3078     return 1;
3079   }
3080
3081   return -1;
3082 }
3083
3084 static struct parsed_proto *process_call_early(int i, int opcnt,
3085   int *adj_i)
3086 {
3087   struct parsed_op *po = &ops[i];
3088   struct parsed_proto *pp;
3089   int multipath = 0;
3090   int adj = 0;
3091   int ret;
3092
3093   pp = po->pp;
3094   if (pp == NULL || pp->is_vararg || pp->argc_reg != 0)
3095     // leave for later
3096     return NULL;
3097
3098   // look for and make use of esp adjust
3099   *adj_i = ret = -1;
3100   if (!pp->is_stdcall && pp->argc_stack > 0)
3101     ret = scan_for_esp_adjust(i + 1, opcnt,
3102             pp->argc_stack * 4, &adj, &multipath);
3103   if (ret >= 0) {
3104     if (pp->argc_stack > adj / 4)
3105       return NULL;
3106     if (multipath)
3107       return NULL;
3108     if (ops[ret].op == OP_POP && adj != 4)
3109       return NULL;
3110   }
3111
3112   *adj_i = ret;
3113   return pp;
3114 }
3115
3116 static void patch_esp_adjust(struct parsed_op *po, int adj)
3117 {
3118   ferr_assert(po, po->op == OP_ADD);
3119   ferr_assert(po, IS(opr_name(po, 0), "esp"));
3120   ferr_assert(po, po->operand[1].type == OPT_CONST);
3121
3122   // this is a bit of a hack, but deals with use of
3123   // single adj for multiple calls
3124   po->operand[1].val -= adj;
3125   po->flags |= OPF_RMD;
3126   if (po->operand[1].val == 0)
3127     po->flags |= OPF_DONE;
3128   ferr_assert(po, (int)po->operand[1].val >= 0);
3129 }
3130
3131 static struct parsed_proto *process_call(int i, int opcnt)
3132 {
3133   struct parsed_op *po = &ops[i];
3134   const struct parsed_proto *pp_c;
3135   struct parsed_proto *pp;
3136   const char *tmpname;
3137   int adj = 0, multipath = 0;
3138   int ret, arg;
3139
3140   tmpname = opr_name(po, 0);
3141   pp = po->pp;
3142   if (pp == NULL)
3143   {
3144     // indirect call
3145     pp_c = resolve_icall(i, opcnt, &multipath);
3146     if (pp_c != NULL) {
3147       if (!pp_c->is_func && !pp_c->is_fptr)
3148         ferr(po, "call to non-func: %s\n", pp_c->name);
3149       pp = proto_clone(pp_c);
3150       my_assert_not(pp, NULL);
3151       if (multipath)
3152         // not resolved just to single func
3153         pp->is_fptr = 1;
3154
3155       switch (po->operand[0].type) {
3156       case OPT_REG:
3157         // we resolved this call and no longer need the register
3158         po->regmask_src &= ~(1 << po->operand[0].reg);
3159         break;
3160       case OPT_REGMEM:
3161         pp->is_fptr = 1;
3162         break;
3163       default:
3164         break;
3165       }
3166     }
3167     if (pp == NULL) {
3168       pp = calloc(1, sizeof(*pp));
3169       my_assert_not(pp, NULL);
3170
3171       pp->is_fptr = 1;
3172       ret = scan_for_esp_adjust(i + 1, opcnt, 32*4, &adj, &multipath);
3173       if (ret < 0 || adj < 0) {
3174         if (!g_allow_regfunc)
3175           ferr(po, "non-__cdecl indirect call unhandled yet\n");
3176         pp->is_unresolved = 1;
3177         adj = 0;
3178       }
3179       adj /= 4;
3180       if (adj > ARRAY_SIZE(pp->arg))
3181         ferr(po, "esp adjust too large: %d\n", adj);
3182       pp->ret_type.name = strdup("int");
3183       pp->argc = pp->argc_stack = adj;
3184       for (arg = 0; arg < pp->argc; arg++)
3185         pp->arg[arg].type.name = strdup("int");
3186     }
3187     po->pp = pp;
3188   }
3189
3190   // look for and make use of esp adjust
3191   multipath = 0;
3192   ret = -1;
3193   if (!pp->is_stdcall && pp->argc_stack > 0)
3194     ret = scan_for_esp_adjust(i + 1, opcnt,
3195             pp->argc_stack * 4, &adj, &multipath);
3196   if (ret >= 0) {
3197     if (pp->is_vararg) {
3198       if (adj / 4 < pp->argc_stack) {
3199         fnote(po, "(this call)\n");
3200         ferr(&ops[ret], "esp adjust is too small: %x < %x\n",
3201           adj, pp->argc_stack * 4);
3202       }
3203       // modify pp to make it have varargs as normal args
3204       arg = pp->argc;
3205       pp->argc += adj / 4 - pp->argc_stack;
3206       for (; arg < pp->argc; arg++) {
3207         pp->arg[arg].type.name = strdup("int");
3208         pp->argc_stack++;
3209       }
3210       if (pp->argc > ARRAY_SIZE(pp->arg))
3211         ferr(po, "too many args for '%s'\n", tmpname);
3212     }
3213     if (pp->argc_stack > adj / 4) {
3214       fnote(po, "(this call)\n");
3215       ferr(&ops[ret], "stack tracking failed for '%s': %x %x\n",
3216         tmpname, pp->argc_stack * 4, adj);
3217     }
3218
3219     ops[ret].flags |= OPF_RMD;
3220     if (ops[ret].op == OP_POP) {
3221       if (adj > 4) {
3222         // deal with multi-pop stack adjust
3223         adj = pp->argc_stack;
3224         while (ops[ret].op == OP_POP && adj > 0 && ret < opcnt) {
3225           ops[ret].flags |= OPF_RMD | OPF_DONE;
3226           adj--;
3227           ret++;
3228         }
3229       }
3230     }
3231     else if (!multipath)
3232       patch_esp_adjust(&ops[ret], pp->argc_stack * 4);
3233   }
3234   else if (pp->is_vararg)
3235     ferr(po, "missing esp_adjust for vararg func '%s'\n",
3236       pp->name);
3237
3238   return pp;
3239 }
3240
3241 static int collect_call_args_early(struct parsed_op *po, int i,
3242   struct parsed_proto *pp, int *regmask)
3243 {
3244   int arg, ret;
3245   int j;
3246
3247   for (arg = 0; arg < pp->argc; arg++)
3248     if (pp->arg[arg].reg == NULL)
3249       break;
3250
3251   // first see if it can be easily done
3252   for (j = i; j > 0 && arg < pp->argc; )
3253   {
3254     if (g_labels[j] != NULL)
3255       return -1;
3256     j--;
3257
3258     if (ops[j].op == OP_CALL)
3259       return -1;
3260     else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP)
3261       return -1;
3262     else if (ops[j].op == OP_POP)
3263       return -1;
3264     else if (ops[j].flags & OPF_CJMP)
3265       return -1;
3266     else if (ops[j].op == OP_PUSH) {
3267       if (ops[j].flags & (OPF_FARG|OPF_FARGNR))
3268         return -1;
3269       ret = scan_for_mod(&ops[j], j + 1, i, 1);
3270       if (ret >= 0)
3271         return -1;
3272
3273       if (pp->arg[arg].type.is_va_list)
3274         return -1;
3275
3276       // next arg
3277       for (arg++; arg < pp->argc; arg++)
3278         if (pp->arg[arg].reg == NULL)
3279           break;
3280     }
3281   }
3282
3283   if (arg < pp->argc)
3284     return -1;
3285
3286   // now do it
3287   for (arg = 0; arg < pp->argc; arg++)
3288     if (pp->arg[arg].reg == NULL)
3289       break;
3290
3291   for (j = i; j > 0 && arg < pp->argc; )
3292   {
3293     j--;
3294
3295     if (ops[j].op == OP_PUSH)
3296     {
3297       ops[j].p_argnext = -1;
3298       ferr_assert(&ops[j], pp->arg[arg].datap == NULL);
3299       pp->arg[arg].datap = &ops[j];
3300
3301       if (ops[j].operand[0].type == OPT_REG)
3302         *regmask |= 1 << ops[j].operand[0].reg;
3303
3304       ops[j].flags |= OPF_RMD | OPF_DONE | OPF_FARGNR | OPF_FARG;
3305       ops[j].flags &= ~OPF_RSAVE;
3306
3307       // next arg
3308       for (arg++; arg < pp->argc; arg++)
3309         if (pp->arg[arg].reg == NULL)
3310           break;
3311     }
3312   }
3313
3314   return 0;
3315 }
3316
3317 static int collect_call_args_r(struct parsed_op *po, int i,
3318   struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3319   int *arg_grp, int arg, int magic, int need_op_saving, int may_reuse)
3320 {
3321   struct parsed_proto *pp_tmp;
3322   struct parsed_op *po_tmp;
3323   struct label_ref *lr;
3324   int need_to_save_current;
3325   int arg_grp_current = 0;
3326   int save_args_seen = 0;
3327   int save_args;
3328   int ret = 0;
3329   int reg;
3330   char buf[32];
3331   int j, k;
3332
3333   if (i < 0) {
3334     ferr(po, "dead label encountered\n");
3335     return -1;
3336   }
3337
3338   for (; arg < pp->argc; arg++)
3339     if (pp->arg[arg].reg == NULL)
3340       break;
3341   magic = (magic & 0xffffff) | (arg << 24);
3342
3343   for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
3344   {
3345     if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
3346       if (ops[j].cc_scratch != magic) {
3347         ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
3348            pp->name);
3349         return -1;
3350       }
3351       // ok: have already been here
3352       return 0;
3353     }
3354     ops[j].cc_scratch = magic;
3355
3356     if (g_labels[j] != NULL && g_label_refs[j].i != -1) {
3357       lr = &g_label_refs[j];
3358       if (lr->next != NULL)
3359         need_op_saving = 1;
3360       for (; lr->next; lr = lr->next) {
3361         check_i(&ops[j], lr->i);
3362         if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
3363           may_reuse = 1;
3364         ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3365                 arg_grp, arg, magic, need_op_saving, may_reuse);
3366         if (ret < 0)
3367           return ret;
3368       }
3369
3370       check_i(&ops[j], lr->i);
3371       if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
3372         may_reuse = 1;
3373       if (j > 0 && LAST_OP(j - 1)) {
3374         // follow last branch in reverse
3375         j = lr->i;
3376         continue;
3377       }
3378       need_op_saving = 1;
3379       ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3380                arg_grp, arg, magic, need_op_saving, may_reuse);
3381       if (ret < 0)
3382         return ret;
3383     }
3384     j--;
3385
3386     if (ops[j].op == OP_CALL)
3387     {
3388       if (pp->is_unresolved)
3389         break;
3390
3391       pp_tmp = ops[j].pp;
3392       if (pp_tmp == NULL)
3393         ferr(po, "arg collect hit unparsed call '%s'\n",
3394           ops[j].operand[0].name);
3395       if (may_reuse && pp_tmp->argc_stack > 0)
3396         ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
3397           arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
3398     }
3399     // esp adjust of 0 means we collected it before
3400     else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP
3401       && (ops[j].operand[1].type != OPT_CONST
3402           || ops[j].operand[1].val != 0))
3403     {
3404       if (pp->is_unresolved)
3405         break;
3406
3407       ferr(po, "arg collect %d/%d hit esp adjust of %d\n",
3408         arg, pp->argc, ops[j].operand[1].val);
3409     }
3410     else if (ops[j].op == OP_POP && !(ops[j].flags & OPF_DONE))
3411     {
3412       if (pp->is_unresolved)
3413         break;
3414
3415       ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
3416     }
3417     else if (ops[j].flags & OPF_CJMP)
3418     {
3419       if (pp->is_unresolved)
3420         break;
3421
3422       may_reuse = 1;
3423     }
3424     else if (ops[j].op == OP_PUSH
3425       && !(ops[j].flags & (OPF_FARGNR|OPF_DONE)))
3426     {
3427       if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
3428         break;
3429
3430       ops[j].p_argnext = -1;
3431       po_tmp = pp->arg[arg].datap;
3432       if (po_tmp != NULL)
3433         ops[j].p_argnext = po_tmp - ops;
3434       pp->arg[arg].datap = &ops[j];
3435
3436       need_to_save_current = 0;
3437       save_args = 0;
3438       reg = -1;
3439       if (ops[j].operand[0].type == OPT_REG)
3440         reg = ops[j].operand[0].reg;
3441
3442       if (!need_op_saving) {
3443         ret = scan_for_mod(&ops[j], j + 1, i, 1);
3444         need_to_save_current = (ret >= 0);
3445       }
3446       if (need_op_saving || need_to_save_current) {
3447         // mark this push as one that needs operand saving
3448         ops[j].flags &= ~OPF_RMD;
3449         if (ops[j].p_argnum == 0) {
3450           ops[j].p_argnum = arg + 1;
3451           save_args |= 1 << arg;
3452         }
3453         else if (ops[j].p_argnum < arg + 1) {
3454           // XXX: might kill valid var..
3455           //*save_arg_vars &= ~(1 << (ops[j].p_argnum - 1));
3456           ops[j].p_argnum = arg + 1;
3457           save_args |= 1 << arg;
3458         }
3459
3460         if (save_args_seen & (1 << (ops[j].p_argnum - 1))) {
3461           save_args_seen = 0;
3462           arg_grp_current++;
3463           if (arg_grp_current >= MAX_ARG_GRP)
3464             ferr(&ops[j], "out of arg groups (arg%d), f %s\n",
3465               ops[j].p_argnum, pp->name);
3466         }
3467       }
3468       else if (ops[j].p_argnum == 0)
3469         ops[j].flags |= OPF_RMD;
3470
3471       // some PUSHes are reused by different calls on other branches,
3472       // but that can't happen if we didn't branch, so they
3473       // can be removed from future searches (handles nested calls)
3474       if (!may_reuse)
3475         ops[j].flags |= OPF_FARGNR;
3476
3477       ops[j].flags |= OPF_FARG;
3478       ops[j].flags &= ~OPF_RSAVE;
3479
3480       // check for __VALIST
3481       if (!pp->is_unresolved && pp->arg[arg].type.is_va_list) {
3482         k = -1;
3483         ret = resolve_origin(j, &ops[j].operand[0],
3484                 magic + 1, &k, NULL);
3485         if (ret == 1 && k >= 0)
3486         {
3487           if (ops[k].op == OP_LEA) {
3488             snprintf(buf, sizeof(buf), "arg_%X",
3489               g_func_pp->argc_stack * 4);
3490             if (!g_func_pp->is_vararg
3491               || strstr(ops[k].operand[1].name, buf))
3492             {
3493               ops[k].flags |= OPF_RMD | OPF_DONE;
3494               ops[j].flags |= OPF_RMD | OPF_VAPUSH;
3495               save_args &= ~(1 << arg);
3496               reg = -1;
3497             }
3498             else
3499               ferr(&ops[j], "lea va_list used, but no vararg?\n");
3500           }
3501           // check for va_list from g_func_pp arg too
3502           else if (ops[k].op == OP_MOV
3503             && is_stack_access(&ops[k], &ops[k].operand[1]))
3504           {
3505             ret = stack_frame_access(&ops[k], &ops[k].operand[1],
3506               buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
3507             if (ret >= 0) {
3508               ops[k].flags |= OPF_RMD | OPF_DONE;
3509               ops[j].flags |= OPF_RMD;
3510               ops[j].p_argpass = ret + 1;
3511               save_args &= ~(1 << arg);
3512               reg = -1;
3513             }
3514           }
3515         }
3516       }
3517
3518       *save_arg_vars |= save_args;
3519
3520       // tracking reg usage
3521       if (reg >= 0)
3522         *regmask |= 1 << reg;
3523
3524       arg++;
3525       if (!pp->is_unresolved) {
3526         // next arg
3527         for (; arg < pp->argc; arg++)
3528           if (pp->arg[arg].reg == NULL)
3529             break;
3530       }
3531       magic = (magic & 0xffffff) | (arg << 24);
3532     }
3533
3534     if (ops[j].p_arggrp > arg_grp_current) {
3535       save_args_seen = 0;
3536       arg_grp_current = ops[j].p_arggrp;
3537     }
3538     if (ops[j].p_argnum > 0)
3539       save_args_seen |= 1 << (ops[j].p_argnum - 1);
3540   }
3541
3542   if (arg < pp->argc) {
3543     ferr(po, "arg collect failed for '%s': %d/%d\n",
3544       pp->name, arg, pp->argc);
3545     return -1;
3546   }
3547
3548   if (arg_grp_current > *arg_grp)
3549     *arg_grp = arg_grp_current;
3550
3551   return arg;
3552 }
3553
3554 static int collect_call_args(struct parsed_op *po, int i,
3555   struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3556   int magic)
3557 {
3558   // arg group is for cases when pushes for
3559   // multiple funcs are going on
3560   struct parsed_op *po_tmp;
3561   int save_arg_vars_current = 0;
3562   int arg_grp = 0;
3563   int ret;
3564   int a;
3565
3566   ret = collect_call_args_r(po, i, pp, regmask,
3567           &save_arg_vars_current, &arg_grp, 0, magic, 0, 0);
3568   if (ret < 0)
3569     return ret;
3570
3571   if (arg_grp != 0) {
3572     // propagate arg_grp
3573     for (a = 0; a < pp->argc; a++) {
3574       if (pp->arg[a].reg != NULL)
3575         continue;
3576
3577       po_tmp = pp->arg[a].datap;
3578       while (po_tmp != NULL) {
3579         po_tmp->p_arggrp = arg_grp;
3580         if (po_tmp->p_argnext > 0)
3581           po_tmp = &ops[po_tmp->p_argnext];
3582         else
3583           po_tmp = NULL;
3584       }
3585     }
3586   }
3587   save_arg_vars[arg_grp] |= save_arg_vars_current;
3588
3589   if (pp->is_unresolved) {
3590     pp->argc += ret;
3591     pp->argc_stack += ret;
3592     for (a = 0; a < pp->argc; a++)
3593       if (pp->arg[a].type.name == NULL)
3594         pp->arg[a].type.name = strdup("int");
3595   }
3596
3597   return ret;
3598 }
3599
3600 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
3601 {
3602   int i;
3603
3604   for (i = 0; i < pp->argc; i++)
3605     if (pp->arg[i].reg == NULL)
3606       break;
3607
3608   if (pp->argc_stack)
3609     memmove(&pp->arg[i + 1], &pp->arg[i],
3610       sizeof(pp->arg[0]) * pp->argc_stack);
3611   memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
3612   pp->arg[i].reg = strdup(reg);
3613   pp->arg[i].type.name = strdup("int");
3614   pp->argc++;
3615   pp->argc_reg++;
3616 }
3617
3618 static void add_label_ref(struct label_ref *lr, int op_i)
3619 {
3620   struct label_ref *lr_new;
3621
3622   if (lr->i == -1) {
3623     lr->i = op_i;
3624     return;
3625   }
3626
3627   lr_new = calloc(1, sizeof(*lr_new));
3628   lr_new->i = op_i;
3629   lr_new->next = lr->next;
3630   lr->next = lr_new;
3631 }
3632
3633 static struct parsed_data *try_resolve_jumptab(int i, int opcnt)
3634 {
3635   struct parsed_op *po = &ops[i];
3636   struct parsed_data *pd;
3637   char label[NAMELEN], *p;
3638   int len, j, l;
3639
3640   p = strchr(po->operand[0].name, '[');
3641   if (p == NULL)
3642     return NULL;
3643
3644   len = p - po->operand[0].name;
3645   strncpy(label, po->operand[0].name, len);
3646   label[len] = 0;
3647
3648   for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3649     if (IS(g_func_pd[j].label, label)) {
3650       pd = &g_func_pd[j];
3651       break;
3652     }
3653   }
3654   if (pd == NULL)
3655     //ferr(po, "label '%s' not parsed?\n", label);
3656     return NULL;
3657
3658   if (pd->type != OPT_OFFSET)
3659     ferr(po, "label '%s' with non-offset data?\n", label);
3660
3661   // find all labels, link
3662   for (j = 0; j < pd->count; j++) {
3663     for (l = 0; l < opcnt; l++) {
3664       if (g_labels[l] != NULL && IS(g_labels[l], pd->d[j].u.label)) {
3665         add_label_ref(&g_label_refs[l], i);
3666         pd->d[j].bt_i = l;
3667         break;
3668       }
3669     }
3670   }
3671
3672   return pd;
3673 }
3674
3675 static void clear_labels(int count)
3676 {
3677   int i;
3678
3679   for (i = 0; i < count; i++) {
3680     if (g_labels[i] != NULL) {
3681       free(g_labels[i]);
3682       g_labels[i] = NULL;
3683     }
3684   }
3685 }
3686
3687 static void output_std_flags(FILE *fout, struct parsed_op *po,
3688   int *pfomask, const char *dst_opr_text)
3689 {
3690   if (*pfomask & (1 << PFO_Z)) {
3691     fprintf(fout, "\n  cond_z = (%s%s == 0);",
3692       lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
3693     *pfomask &= ~(1 << PFO_Z);
3694   }
3695   if (*pfomask & (1 << PFO_S)) {
3696     fprintf(fout, "\n  cond_s = (%s%s < 0);",
3697       lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
3698     *pfomask &= ~(1 << PFO_S);
3699   }
3700 }
3701
3702 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
3703   int is_noreturn)
3704 {
3705   if (pp->is_fastcall)
3706     fprintf(fout, "__fastcall ");
3707   else if (pp->is_stdcall && pp->argc_reg == 0)
3708     fprintf(fout, "__stdcall ");
3709   if (pp->is_noreturn || is_noreturn)
3710     fprintf(fout, "noreturn ");
3711 }
3712
3713 static int get_pp_arg_regmask(const struct parsed_proto *pp)
3714 {
3715   int regmask = 0;
3716   int i, reg;
3717
3718   for (i = 0; i < pp->argc; i++) {
3719     if (pp->arg[i].reg != NULL) {
3720       reg = char_array_i(regs_r32,
3721               ARRAY_SIZE(regs_r32), pp->arg[i].reg);
3722       if (reg < 0)
3723         ferr(ops, "arg '%s' of func '%s' is not a reg?\n",
3724           pp->arg[i].reg, pp->name);
3725       regmask |= 1 << reg;
3726     }
3727   }
3728
3729   return regmask;
3730 }
3731
3732 static char *saved_arg_name(char *buf, size_t buf_size, int grp, int num)
3733 {
3734   char buf1[16];
3735
3736   buf1[0] = 0;
3737   if (grp > 0)
3738     snprintf(buf1, sizeof(buf1), "%d", grp);
3739   snprintf(buf, buf_size, "s%s_a%d", buf1, num);
3740
3741   return buf;
3742 }
3743
3744 static void gen_x_cleanup(int opcnt);
3745
3746 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
3747 {
3748   struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
3749   struct parsed_opr *last_arith_dst = NULL;
3750   char buf1[256], buf2[256], buf3[256], cast[64];
3751   const struct parsed_proto *pp_c;
3752   struct parsed_proto *pp, *pp_tmp;
3753   struct parsed_data *pd;
3754   const char *tmpname;
3755   unsigned int uval;
3756   int save_arg_vars[MAX_ARG_GRP] = { 0, };
3757   int cond_vars = 0;
3758   int need_tmp_var = 0;
3759   int need_tmp64 = 0;
3760   int had_decl = 0;
3761   int label_pending = 0;
3762   int regmask_save = 0;
3763   int regmask_arg = 0;
3764   int regmask_now = 0;
3765   int regmask_init = 0;
3766   int regmask = 0;
3767   int pfomask = 0;
3768   int found = 0;
3769   int depth = 0;
3770   int no_output;
3771   int i, j, l;
3772   int arg;
3773   int reg;
3774   int ret;
3775
3776   g_bp_frame = g_sp_frame = g_stack_fsz = 0;
3777   g_stack_frame_used = 0;
3778
3779   g_func_pp = proto_parse(fhdr, funcn, 0);
3780   if (g_func_pp == NULL)
3781     ferr(ops, "proto_parse failed for '%s'\n", funcn);
3782
3783   regmask_arg = get_pp_arg_regmask(g_func_pp);
3784
3785   // pass1:
3786   // - handle ebp/esp frame, remove ops related to it
3787   scan_prologue_epilogue(opcnt);
3788
3789   // pass2:
3790   // - parse calls with labels
3791   // - resolve all branches
3792   for (i = 0; i < opcnt; i++)
3793   {
3794     po = &ops[i];
3795     po->bt_i = -1;
3796     po->btj = NULL;
3797
3798     if (po->flags & (OPF_RMD|OPF_DONE))
3799       continue;
3800
3801     if (po->op == OP_CALL) {
3802       pp = NULL;
3803
3804       if (po->operand[0].type == OPT_LABEL) {
3805         tmpname = opr_name(po, 0);
3806         if (IS_START(tmpname, "loc_"))
3807           ferr(po, "call to loc_*\n");
3808         pp_c = proto_parse(fhdr, tmpname, 0);
3809         if (pp_c == NULL)
3810           ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3811
3812         pp = proto_clone(pp_c);
3813         my_assert_not(pp, NULL);
3814       }
3815       else if (po->datap != NULL) {
3816         pp = calloc(1, sizeof(*pp));
3817         my_assert_not(pp, NULL);
3818
3819         ret = parse_protostr(po->datap, pp);
3820         if (ret < 0)
3821           ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3822         free(po->datap);
3823         po->datap = NULL;
3824       }
3825
3826       if (pp != NULL) {
3827         if (pp->is_fptr)
3828           check_func_pp(po, pp, "fptr var call");
3829         if (pp->is_noreturn)
3830           po->flags |= OPF_TAIL;
3831       }
3832       po->pp = pp;
3833       continue;
3834     }
3835
3836     if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3837       continue;
3838
3839     if (po->operand[0].type == OPT_REGMEM) {
3840       pd = try_resolve_jumptab(i, opcnt);
3841       if (pd == NULL)
3842         goto tailcall;
3843
3844       po->btj = pd;
3845       continue;
3846     }
3847
3848     for (l = 0; l < opcnt; l++) {
3849       if (g_labels[l] != NULL
3850           && IS(po->operand[0].name, g_labels[l]))
3851       {
3852         if (l == i + 1 && po->op == OP_JMP) {
3853           // yet another alignment type..
3854           po->flags |= OPF_RMD|OPF_DONE;
3855           break;
3856         }
3857         add_label_ref(&g_label_refs[l], i);
3858         po->bt_i = l;
3859         break;
3860       }
3861     }
3862
3863     if (po->bt_i != -1 || (po->flags & OPF_RMD))
3864       continue;
3865
3866     if (po->operand[0].type == OPT_LABEL)
3867       // assume tail call
3868       goto tailcall;
3869
3870     ferr(po, "unhandled branch\n");
3871
3872 tailcall:
3873     po->op = OP_CALL;
3874     po->flags |= OPF_TAIL;
3875     if (i > 0 && ops[i - 1].op == OP_POP)
3876       po->flags |= OPF_ATAIL;
3877     i--; // reprocess
3878   }
3879
3880   // pass3:
3881   // - remove dead labels
3882   // - process trivial calls
3883   for (i = 0; i < opcnt; i++)
3884   {
3885     if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
3886       free(g_labels[i]);
3887       g_labels[i] = NULL;
3888     }
3889
3890     po = &ops[i];
3891     if (po->flags & (OPF_RMD|OPF_DONE))
3892       continue;
3893
3894     if (po->op == OP_CALL)
3895     {
3896       pp = process_call_early(i, opcnt, &j);
3897       if (pp != NULL) {
3898         if (!(po->flags & OPF_ATAIL))
3899           // since we know the args, try to collect them
3900           if (collect_call_args_early(po, i, pp, &regmask) != 0)
3901             pp = NULL;
3902       }
3903
3904       if (pp != NULL) {
3905         if (j >= 0) {
3906           // commit esp adjust
3907           ops[j].flags |= OPF_RMD;
3908           if (ops[j].op != OP_POP)
3909             patch_esp_adjust(&ops[j], pp->argc_stack * 4);
3910           else
3911             ops[j].flags |= OPF_DONE;
3912         }
3913
3914         if (strstr(pp->ret_type.name, "int64"))
3915           need_tmp64 = 1;
3916
3917         po->flags |= OPF_DONE;
3918       }
3919     }
3920   }
3921
3922   // pass4:
3923   // - process calls
3924   for (i = 0; i < opcnt; i++)
3925   {
3926     po = &ops[i];
3927     if (po->flags & (OPF_RMD|OPF_DONE))
3928       continue;
3929
3930     if (po->op == OP_CALL && !(po->flags & OPF_DONE))
3931     {
3932       pp = process_call(i, opcnt);
3933
3934       if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
3935         // since we know the args, collect them
3936         collect_call_args(po, i, pp, &regmask, save_arg_vars,
3937           i + opcnt * 2);
3938       }
3939
3940       if (strstr(pp->ret_type.name, "int64"))
3941         need_tmp64 = 1;
3942     }
3943   }
3944
3945   // pass5:
3946   // - find POPs for PUSHes, rm both
3947   // - scan for STD/CLD, propagate DF
3948   // - scan for all used registers
3949   // - find flag set ops for their users
3950   // - do unreselved calls
3951   // - declare indirect functions
3952   for (i = 0; i < opcnt; i++)
3953   {
3954     po = &ops[i];
3955     if (po->flags & (OPF_RMD|OPF_DONE))
3956       continue;
3957
3958     if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3959       reg = po->operand[0].reg;
3960       if (!(regmask & (1 << reg)))
3961         // not a reg save after all, rerun scan_for_pop
3962         po->flags &= ~OPF_RSAVE;
3963       else
3964         regmask_save |= 1 << reg;
3965     }
3966
3967     if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
3968       && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
3969     {
3970       if (po->operand[0].type == OPT_REG)
3971       {
3972         reg = po->operand[0].reg;
3973         if (reg < 0)
3974           ferr(po, "reg not set for push?\n");
3975
3976         depth = 0;
3977         ret = scan_for_pop(i + 1, opcnt,
3978                 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3979         if (ret == 1) {
3980           if (depth > 1)
3981             ferr(po, "too much depth: %d\n", depth);
3982
3983           po->flags |= OPF_RMD;
3984           scan_for_pop(i + 1, opcnt, po->operand[0].name,
3985             i + opcnt * 4, 0, &depth, 1);
3986           continue;
3987         }
3988         ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3989         if (ret == 0) {
3990           arg = OPF_RMD;
3991           if (regmask & (1 << reg)) {
3992             if (regmask_save & (1 << reg))
3993               ferr(po, "%s already saved?\n", po->operand[0].name);
3994             arg = OPF_RSAVE;
3995           }
3996           po->flags |= arg;
3997           scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3998           continue;
3999         }
4000       }
4001       else if (po->operand[0].type == OPT_CONST) {
4002         scan_for_pop_const(i, opcnt);
4003       }
4004     }
4005
4006     if (po->op == OP_STD) {
4007       po->flags |= OPF_DF | OPF_RMD | OPF_DONE;
4008       scan_propagate_df(i + 1, opcnt);
4009     }
4010
4011     regmask_now = po->regmask_src | po->regmask_dst;
4012     if (regmask_now & (1 << xBP)) {
4013       if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
4014         if (po->regmask_dst & (1 << xBP))
4015           // compiler decided to drop bp frame and use ebp as scratch
4016           scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
4017         else
4018           regmask_now &= ~(1 << xBP);
4019       }
4020     }
4021
4022     regmask |= regmask_now;
4023
4024     if (po->flags & OPF_CC)
4025     {
4026       int setters[16], cnt = 0, branched = 0;
4027
4028       ret = scan_for_flag_set(i, i + opcnt * 6,
4029               &branched, setters, &cnt);
4030       if (ret < 0 || cnt <= 0)
4031         ferr(po, "unable to trace flag setter(s)\n");
4032       if (cnt > ARRAY_SIZE(setters))
4033         ferr(po, "too many flag setters\n");
4034
4035       for (j = 0; j < cnt; j++)
4036       {
4037         tmp_op = &ops[setters[j]]; // flag setter
4038         pfomask = 0;
4039
4040         // to get nicer code, we try to delay test and cmp;
4041         // if we can't because of operand modification, or if we
4042         // have arith op, or branch, make it calculate flags explicitly
4043         if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
4044         {
4045           if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
4046             pfomask = 1 << po->pfo;
4047         }
4048         else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
4049           pfomask = 1 << po->pfo;
4050         }
4051         else {
4052           // see if we'll be able to handle based on op result
4053           if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
4054                && po->pfo != PFO_Z && po->pfo != PFO_S
4055                && po->pfo != PFO_P)
4056               || branched
4057               || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
4058           {
4059             pfomask = 1 << po->pfo;
4060           }
4061
4062           if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
4063             propagate_lmod(tmp_op, &tmp_op->operand[0],
4064               &tmp_op->operand[1]);
4065             if (tmp_op->operand[0].lmod == OPLM_DWORD)
4066               need_tmp64 = 1;
4067           }
4068         }
4069         if (pfomask) {
4070           tmp_op->pfomask |= pfomask;
4071           cond_vars |= pfomask;
4072         }
4073         // note: may overwrite, currently not a problem
4074         po->datap = tmp_op;
4075       }
4076
4077       if (po->op == OP_RCL || po->op == OP_RCR
4078        || po->op == OP_ADC || po->op == OP_SBB)
4079         cond_vars |= 1 << PFO_C;
4080     }
4081
4082     if (po->op == OP_CMPS || po->op == OP_SCAS) {
4083       cond_vars |= 1 << PFO_Z;
4084     }
4085     else if (po->op == OP_MUL
4086       || (po->op == OP_IMUL && po->operand_cnt == 1))
4087     {
4088       if (po->operand[0].lmod == OPLM_DWORD)
4089         need_tmp64 = 1;
4090     }
4091     else if (po->op == OP_CALL) {
4092       // note: resolved non-reg calls are OPF_DONE already
4093       pp = po->pp;
4094       if (pp == NULL)
4095         ferr(po, "NULL pp\n");
4096
4097       if (pp->is_unresolved) {
4098         int regmask_stack = 0;
4099         collect_call_args(po, i, pp, &regmask, save_arg_vars,
4100           i + opcnt * 2);
4101
4102         // this is pretty rough guess:
4103         // see ecx and edx were pushed (and not their saved versions)
4104         for (arg = 0; arg < pp->argc; arg++) {
4105           if (pp->arg[arg].reg != NULL)
4106             continue;
4107
4108           tmp_op = pp->arg[arg].datap;
4109           if (tmp_op == NULL)
4110             ferr(po, "parsed_op missing for arg%d\n", arg);
4111           if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
4112             regmask_stack |= 1 << tmp_op->operand[0].reg;
4113         }
4114
4115         if (!((regmask_stack & (1 << xCX))
4116           && (regmask_stack & (1 << xDX))))
4117         {
4118           if (pp->argc_stack != 0
4119            || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
4120           {
4121             pp_insert_reg_arg(pp, "ecx");
4122             pp->is_fastcall = 1;
4123             regmask_init |= 1 << xCX;
4124             regmask |= 1 << xCX;
4125           }
4126           if (pp->argc_stack != 0
4127            || ((regmask | regmask_arg) & (1 << xDX)))
4128           {
4129             pp_insert_reg_arg(pp, "edx");
4130             regmask_init |= 1 << xDX;
4131             regmask |= 1 << xDX;
4132           }
4133         }
4134
4135         // note: __cdecl doesn't fall into is_unresolved category
4136         if (pp->argc_stack > 0)
4137           pp->is_stdcall = 1;
4138       }
4139
4140       for (arg = 0; arg < pp->argc; arg++) {
4141         if (pp->arg[arg].reg != NULL) {
4142           reg = char_array_i(regs_r32,
4143                   ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
4144           if (reg < 0)
4145             ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
4146           if (!(regmask & (1 << reg))) {
4147             regmask_init |= 1 << reg;
4148             regmask |= 1 << reg;
4149           }
4150         }
4151       }
4152     }
4153     else if (po->op == OP_MOV && po->operand[0].pp != NULL
4154       && po->operand[1].pp != NULL)
4155     {
4156       // <var> = offset <something>
4157       if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
4158         && !IS_START(po->operand[1].name, "off_"))
4159       {
4160         if (!po->operand[0].pp->is_fptr)
4161           ferr(po, "%s not declared as fptr when it should be\n",
4162             po->operand[0].name);
4163         if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
4164           pp_print(buf1, sizeof(buf1), po->operand[0].pp);
4165           pp_print(buf2, sizeof(buf2), po->operand[1].pp);
4166           fnote(po, "var:  %s\n", buf1);
4167           fnote(po, "func: %s\n", buf2);
4168           ferr(po, "^ mismatch\n");
4169         }
4170       }
4171     }
4172     else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
4173       regmask |= 1 << xAX;
4174     else if (po->op == OP_DIV || po->op == OP_IDIV) {
4175       // 32bit division is common, look for it
4176       if (po->op == OP_DIV)
4177         ret = scan_for_reg_clear(i, xDX);
4178       else
4179         ret = scan_for_cdq_edx(i);
4180       if (ret >= 0)
4181         po->flags |= OPF_32BIT;
4182       else
4183         need_tmp64 = 1;
4184     }
4185     else if (po->op == OP_CLD)
4186       po->flags |= OPF_RMD | OPF_DONE;
4187
4188     if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
4189       need_tmp_var = 1;
4190     }
4191   }
4192
4193   // pass6:
4194   // - confirm regmask_save, it might have been reduced
4195   if (regmask_save != 0)
4196   {
4197     regmask_save = 0;
4198     for (i = 0; i < opcnt; i++) {
4199       po = &ops[i];
4200       if (po->flags & OPF_RMD)
4201         continue;
4202
4203       if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
4204         regmask_save |= 1 << po->operand[0].reg;
4205     }
4206   }
4207
4208   // output starts here
4209
4210   // define userstack size
4211   if (g_func_pp->is_userstack) {
4212     fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
4213     fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
4214     fprintf(fout, "#endif\n");
4215   }
4216
4217   // the function itself
4218   fprintf(fout, "%s ", g_func_pp->ret_type.name);
4219   output_pp_attrs(fout, g_func_pp, g_ida_func_attr & IDAFA_NORETURN);
4220   fprintf(fout, "%s(", g_func_pp->name);
4221
4222   for (i = 0; i < g_func_pp->argc; i++) {
4223     if (i > 0)
4224       fprintf(fout, ", ");
4225     if (g_func_pp->arg[i].fptr != NULL) {
4226       // func pointer..
4227       pp = g_func_pp->arg[i].fptr;
4228       fprintf(fout, "%s (", pp->ret_type.name);
4229       output_pp_attrs(fout, pp, 0);
4230       fprintf(fout, "*a%d)(", i + 1);
4231       for (j = 0; j < pp->argc; j++) {
4232         if (j > 0)
4233           fprintf(fout, ", ");
4234         if (pp->arg[j].fptr)
4235           ferr(ops, "nested fptr\n");
4236         fprintf(fout, "%s", pp->arg[j].type.name);
4237       }
4238       if (pp->is_vararg) {
4239         if (j > 0)
4240           fprintf(fout, ", ");
4241         fprintf(fout, "...");
4242       }
4243       fprintf(fout, ")");
4244     }
4245     else if (g_func_pp->arg[i].type.is_retreg) {
4246       fprintf(fout, "u32 *r_%s", g_func_pp->arg[i].reg);
4247     }
4248     else {
4249       fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
4250     }
4251   }
4252   if (g_func_pp->is_vararg) {
4253     if (i > 0)
4254       fprintf(fout, ", ");
4255     fprintf(fout, "...");
4256   }
4257
4258   fprintf(fout, ")\n{\n");
4259
4260   // declare indirect functions
4261   for (i = 0; i < opcnt; i++) {
4262     po = &ops[i];
4263     if (po->flags & OPF_RMD)
4264       continue;
4265
4266     if (po->op == OP_CALL) {
4267       pp = po->pp;
4268       if (pp == NULL)
4269         ferr(po, "NULL pp\n");
4270
4271       if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
4272         if (pp->name[0] != 0) {
4273           memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
4274           memcpy(pp->name, "i_", 2);
4275
4276           // might be declared already
4277           found = 0;
4278           for (j = 0; j < i; j++) {
4279             if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
4280               if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
4281                 found = 1;
4282                 break;
4283               }
4284             }
4285           }
4286           if (found)
4287             continue;
4288         }
4289         else
4290           snprintf(pp->name, sizeof(pp->name), "icall%d", i);
4291
4292         fprintf(fout, "  %s (", pp->ret_type.name);
4293         output_pp_attrs(fout, pp, 0);
4294         fprintf(fout, "*%s)(", pp->name);
4295         for (j = 0; j < pp->argc; j++) {
4296           if (j > 0)
4297             fprintf(fout, ", ");
4298           fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
4299         }
4300         fprintf(fout, ");\n");
4301       }
4302     }
4303   }
4304
4305   // output LUTs/jumptables
4306   for (i = 0; i < g_func_pd_cnt; i++) {
4307     pd = &g_func_pd[i];
4308     fprintf(fout, "  static const ");
4309     if (pd->type == OPT_OFFSET) {
4310       fprintf(fout, "void *jt_%s[] =\n    { ", pd->label);
4311
4312       for (j = 0; j < pd->count; j++) {
4313         if (j > 0)
4314           fprintf(fout, ", ");
4315         fprintf(fout, "&&%s", pd->d[j].u.label);
4316       }
4317     }
4318     else {
4319       fprintf(fout, "%s %s[] =\n    { ",
4320         lmod_type_u(ops, pd->lmod), pd->label);
4321
4322       for (j = 0; j < pd->count; j++) {
4323         if (j > 0)
4324           fprintf(fout, ", ");
4325         fprintf(fout, "%u", pd->d[j].u.val);
4326       }
4327     }
4328     fprintf(fout, " };\n");
4329     had_decl = 1;
4330   }
4331
4332   // declare stack frame, va_arg
4333   if (g_stack_fsz) {
4334     fprintf(fout, "  union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
4335       (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
4336     had_decl = 1;
4337   }
4338
4339   if (g_func_pp->is_userstack) {
4340     fprintf(fout, "  u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
4341     fprintf(fout, "  u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
4342     had_decl = 1;
4343   }
4344
4345   if (g_func_pp->is_vararg) {
4346     fprintf(fout, "  va_list ap;\n");
4347     had_decl = 1;
4348   }
4349
4350   // declare arg-registers
4351   for (i = 0; i < g_func_pp->argc; i++) {
4352     if (g_func_pp->arg[i].reg != NULL) {
4353       reg = char_array_i(regs_r32,
4354               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
4355       if (regmask & (1 << reg)) {
4356         if (g_func_pp->arg[i].type.is_retreg)
4357           fprintf(fout, "  u32 %s = *r_%s;\n",
4358             g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
4359         else
4360           fprintf(fout, "  u32 %s = (u32)a%d;\n",
4361             g_func_pp->arg[i].reg, i + 1);
4362       }
4363       else {
4364         if (g_func_pp->arg[i].type.is_retreg)
4365           ferr(ops, "retreg '%s' is unused?\n",
4366             g_func_pp->arg[i].reg);
4367         fprintf(fout, "  // %s = a%d; // unused\n",
4368           g_func_pp->arg[i].reg, i + 1);
4369       }
4370       had_decl = 1;
4371     }
4372   }
4373
4374   regmask_now = regmask & ~regmask_arg;
4375   regmask_now &= ~(1 << xSP);
4376   if (regmask_now & 0x00ff) {
4377     for (reg = 0; reg < 8; reg++) {
4378       if (regmask_now & (1 << reg)) {
4379         fprintf(fout, "  u32 %s", regs_r32[reg]);
4380         if (regmask_init & (1 << reg))
4381           fprintf(fout, " = 0");
4382         fprintf(fout, ";\n");
4383         had_decl = 1;
4384       }
4385     }
4386   }
4387   if (regmask_now & 0xff00) {
4388     for (reg = 8; reg < 16; reg++) {
4389       if (regmask_now & (1 << reg)) {
4390         fprintf(fout, "  mmxr %s", regs_r32[reg]);
4391         if (regmask_init & (1 << reg))
4392           fprintf(fout, " = { 0, }");
4393         fprintf(fout, ";\n");
4394         had_decl = 1;
4395       }
4396     }
4397   }
4398
4399   if (regmask_save) {
4400     for (reg = 0; reg < 8; reg++) {
4401       if (regmask_save & (1 << reg)) {
4402         fprintf(fout, "  u32 s_%s;\n", regs_r32[reg]);
4403         had_decl = 1;
4404       }
4405     }
4406   }
4407
4408   for (i = 0; i < ARRAY_SIZE(save_arg_vars); i++) {
4409     if (save_arg_vars[i] == 0)
4410       continue;
4411     for (reg = 0; reg < 32; reg++) {
4412       if (save_arg_vars[i] & (1 << reg)) {
4413         fprintf(fout, "  u32 %s;\n",
4414           saved_arg_name(buf1, sizeof(buf1), i, reg + 1));
4415         had_decl = 1;
4416       }
4417     }
4418   }
4419
4420   if (cond_vars) {
4421     for (i = 0; i < 8; i++) {
4422       if (cond_vars & (1 << i)) {
4423         fprintf(fout, "  u32 cond_%s;\n", parsed_flag_op_names[i]);
4424         had_decl = 1;
4425       }
4426     }
4427   }
4428
4429   if (need_tmp_var) {
4430     fprintf(fout, "  u32 tmp;\n");
4431     had_decl = 1;
4432   }
4433
4434   if (need_tmp64) {
4435     fprintf(fout, "  u64 tmp64;\n");
4436     had_decl = 1;
4437   }
4438
4439   if (had_decl)
4440     fprintf(fout, "\n");
4441
4442   if (g_func_pp->is_vararg) {
4443     if (g_func_pp->argc_stack == 0)
4444       ferr(ops, "vararg func without stack args?\n");
4445     fprintf(fout, "  va_start(ap, a%d);\n", g_func_pp->argc);
4446   }
4447
4448   // output ops
4449   for (i = 0; i < opcnt; i++)
4450   {
4451     if (g_labels[i] != NULL) {
4452       fprintf(fout, "\n%s:\n", g_labels[i]);
4453       label_pending = 1;
4454
4455       delayed_flag_op = NULL;
4456       last_arith_dst = NULL;
4457     }
4458
4459     po = &ops[i];
4460     if (po->flags & OPF_RMD)
4461       continue;
4462
4463     no_output = 0;
4464
4465     #define assert_operand_cnt(n_) \
4466       if (po->operand_cnt != n_) \
4467         ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
4468
4469     // conditional/flag using op?
4470     if (po->flags & OPF_CC)
4471     {
4472       int is_delayed = 0;
4473
4474       tmp_op = po->datap;
4475
4476       // we go through all this trouble to avoid using parsed_flag_op,
4477       // which makes generated code much nicer
4478       if (delayed_flag_op != NULL)
4479       {
4480         out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
4481           po->pfo, po->pfo_inv);
4482         is_delayed = 1;
4483       }
4484       else if (last_arith_dst != NULL
4485         && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
4486            || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
4487            ))
4488       {
4489         out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4490         out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
4491           last_arith_dst->lmod, buf3);
4492         is_delayed = 1;
4493       }
4494       else if (tmp_op != NULL) {
4495         // use preprocessed flag calc results
4496         if (!(tmp_op->pfomask & (1 << po->pfo)))
4497           ferr(po, "not prepared for pfo %d\n", po->pfo);
4498
4499         // note: pfo_inv was not yet applied
4500         snprintf(buf1, sizeof(buf1), "(%scond_%s)",
4501           po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
4502       }
4503       else {
4504         ferr(po, "all methods of finding comparison failed\n");
4505       }
4506  
4507       if (po->flags & OPF_JMP) {
4508         fprintf(fout, "  if %s", buf1);
4509       }
4510       else if (po->op == OP_RCL || po->op == OP_RCR
4511                || po->op == OP_ADC || po->op == OP_SBB)
4512       {
4513         if (is_delayed)
4514           fprintf(fout, "  cond_%s = %s;\n",
4515             parsed_flag_op_names[po->pfo], buf1);
4516       }
4517       else if (po->flags & OPF_DATA) { // SETcc
4518         out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
4519         fprintf(fout, "  %s = %s;", buf2, buf1);
4520       }
4521       else {
4522         ferr(po, "unhandled conditional op\n");
4523       }
4524     }
4525
4526     pfomask = po->pfomask;
4527
4528     if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
4529       struct parsed_opr opr = {0,};
4530       opr.type = OPT_REG;
4531       opr.reg = xCX;
4532       opr.lmod = OPLM_DWORD;
4533       ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
4534
4535       if (ret != 1 || uval == 0) {
4536         // we need initial flags for ecx=0 case..
4537         if (i > 0 && ops[i - 1].op == OP_XOR
4538           && IS(ops[i - 1].operand[0].name,
4539                 ops[i - 1].operand[1].name))
4540         {
4541           fprintf(fout, "  cond_z = ");
4542           if (pfomask & (1 << PFO_C))
4543             fprintf(fout, "cond_c = ");
4544           fprintf(fout, "0;\n");
4545         }
4546         else if (last_arith_dst != NULL) {
4547           out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4548           out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
4549             last_arith_dst->lmod, buf3);
4550           fprintf(fout, "  cond_z = %s;\n", buf1);
4551         }
4552         else
4553           ferr(po, "missing initial ZF\n");
4554       }
4555     }
4556
4557     switch (po->op)
4558     {
4559       case OP_MOV:
4560         assert_operand_cnt(2);
4561         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4562         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4563         default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
4564         fprintf(fout, "  %s = %s;", buf1,
4565             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4566               buf3, 0));
4567         break;
4568
4569       case OP_LEA:
4570         assert_operand_cnt(2);
4571         po->operand[1].lmod = OPLM_DWORD; // always
4572         fprintf(fout, "  %s = %s;",
4573             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4574             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4575               NULL, 1));
4576         break;
4577
4578       case OP_MOVZX:
4579         assert_operand_cnt(2);
4580         fprintf(fout, "  %s = %s;",
4581             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4582             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4583         break;
4584
4585       case OP_MOVSX:
4586         assert_operand_cnt(2);
4587         switch (po->operand[1].lmod) {
4588         case OPLM_BYTE:
4589           strcpy(buf3, "(s8)");
4590           break;
4591         case OPLM_WORD:
4592           strcpy(buf3, "(s16)");
4593           break;
4594         default:
4595           ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
4596         }
4597         fprintf(fout, "  %s = %s;",
4598             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4599             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4600               buf3, 0));
4601         break;
4602
4603       case OP_XCHG:
4604         assert_operand_cnt(2);
4605         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4606         fprintf(fout, "  tmp = %s;",
4607           out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
4608         fprintf(fout, " %s = %s;",
4609           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4610           out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4611             default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4612         fprintf(fout, " %s = %stmp;",
4613           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
4614           default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
4615         snprintf(g_comment, sizeof(g_comment), "xchg");
4616         break;
4617
4618       case OP_NOT:
4619         assert_operand_cnt(1);
4620         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4621         fprintf(fout, "  %s = ~%s;", buf1, buf1);
4622         break;
4623
4624       case OP_CDQ:
4625         assert_operand_cnt(2);
4626         fprintf(fout, "  %s = (s32)%s >> 31;",
4627             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4628             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4629         strcpy(g_comment, "cdq");
4630         break;
4631
4632       case OP_LODS:
4633         assert_operand_cnt(3);
4634         if (po->flags & OPF_REP) {
4635           // hmh..
4636           ferr(po, "TODO\n");
4637         }
4638         else {
4639           fprintf(fout, "  eax = %sesi; esi %c= %d;",
4640             lmod_cast_u_ptr(po, po->operand[0].lmod),
4641             (po->flags & OPF_DF) ? '-' : '+',
4642             lmod_bytes(po, po->operand[0].lmod));
4643           strcpy(g_comment, "lods");
4644         }
4645         break;
4646
4647       case OP_STOS:
4648         assert_operand_cnt(3);
4649         if (po->flags & OPF_REP) {
4650           fprintf(fout, "  for (; ecx != 0; ecx--, edi %c= %d)\n",
4651             (po->flags & OPF_DF) ? '-' : '+',
4652             lmod_bytes(po, po->operand[0].lmod));
4653           fprintf(fout, "    %sedi = eax;",
4654             lmod_cast_u_ptr(po, po->operand[0].lmod));
4655           strcpy(g_comment, "rep stos");
4656         }
4657         else {
4658           fprintf(fout, "  %sedi = eax; edi %c= %d;",
4659             lmod_cast_u_ptr(po, po->operand[0].lmod),
4660             (po->flags & OPF_DF) ? '-' : '+',
4661             lmod_bytes(po, po->operand[0].lmod));
4662           strcpy(g_comment, "stos");
4663         }
4664         break;
4665
4666       case OP_MOVS:
4667         assert_operand_cnt(3);
4668         j = lmod_bytes(po, po->operand[0].lmod);
4669         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4670         l = (po->flags & OPF_DF) ? '-' : '+';
4671         if (po->flags & OPF_REP) {
4672           fprintf(fout,
4673             "  for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
4674             l, j, l, j);
4675           fprintf(fout,
4676             "    %sedi = %sesi;", buf1, buf1);
4677           strcpy(g_comment, "rep movs");
4678         }
4679         else {
4680           fprintf(fout, "  %sedi = %sesi; edi %c= %d; esi %c= %d;",
4681             buf1, buf1, l, j, l, j);
4682           strcpy(g_comment, "movs");
4683         }
4684         break;
4685
4686       case OP_CMPS:
4687         // repe ~ repeat while ZF=1
4688         assert_operand_cnt(3);
4689         j = lmod_bytes(po, po->operand[0].lmod);
4690         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4691         l = (po->flags & OPF_DF) ? '-' : '+';
4692         if (po->flags & OPF_REP) {
4693           fprintf(fout,
4694             "  for (; ecx != 0; ecx--) {\n");
4695           if (pfomask & (1 << PFO_C)) {
4696             // ugh..
4697             fprintf(fout,
4698             "    cond_c = %sesi < %sedi;\n", buf1, buf1);
4699             pfomask &= ~(1 << PFO_C);
4700           }
4701           fprintf(fout,
4702             "    cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
4703               buf1, buf1, l, j, l, j);
4704           fprintf(fout,
4705             "    if (cond_z %s 0) break;\n",
4706               (po->flags & OPF_REPZ) ? "==" : "!=");
4707           fprintf(fout,
4708             "  }");
4709           snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
4710             (po->flags & OPF_REPZ) ? "e" : "ne");
4711         }
4712         else {
4713           fprintf(fout,
4714             "  cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
4715             buf1, buf1, l, j, l, j);
4716           strcpy(g_comment, "cmps");
4717         }
4718         pfomask &= ~(1 << PFO_Z);
4719         last_arith_dst = NULL;
4720         delayed_flag_op = NULL;
4721         break;
4722
4723       case OP_SCAS:
4724         // only does ZF (for now)
4725         // repe ~ repeat while ZF=1
4726         assert_operand_cnt(3);
4727         j = lmod_bytes(po, po->operand[0].lmod);
4728         l = (po->flags & OPF_DF) ? '-' : '+';
4729         if (po->flags & OPF_REP) {
4730           fprintf(fout,
4731             "  for (; ecx != 0; ecx--) {\n");
4732           fprintf(fout,
4733             "    cond_z = (%seax == %sedi); edi %c= %d;\n",
4734               lmod_cast_u(po, po->operand[0].lmod),
4735               lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4736           fprintf(fout,
4737             "    if (cond_z %s 0) break;\n",
4738               (po->flags & OPF_REPZ) ? "==" : "!=");
4739           fprintf(fout,
4740             "  }");
4741           snprintf(g_comment, sizeof(g_comment), "rep%s scas",
4742             (po->flags & OPF_REPZ) ? "e" : "ne");
4743         }
4744         else {
4745           fprintf(fout, "  cond_z = (%seax == %sedi); edi %c= %d;",
4746               lmod_cast_u(po, po->operand[0].lmod),
4747               lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4748           strcpy(g_comment, "scas");
4749         }
4750         pfomask &= ~(1 << PFO_Z);
4751         last_arith_dst = NULL;
4752         delayed_flag_op = NULL;
4753         break;
4754
4755       // arithmetic w/flags
4756       case OP_AND:
4757       case OP_OR:
4758         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4759         // fallthrough
4760       dualop_arith:
4761         assert_operand_cnt(2);
4762         fprintf(fout, "  %s %s= %s;",
4763             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4764             op_to_c(po),
4765             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4766         output_std_flags(fout, po, &pfomask, buf1);
4767         last_arith_dst = &po->operand[0];
4768         delayed_flag_op = NULL;
4769         break;
4770
4771       case OP_SHL:
4772       case OP_SHR:
4773         assert_operand_cnt(2);
4774         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4775         if (pfomask & (1 << PFO_C)) {
4776           if (po->operand[1].type == OPT_CONST) {
4777             l = lmod_bytes(po, po->operand[0].lmod) * 8;
4778             j = po->operand[1].val;
4779             j %= l;
4780             if (j != 0) {
4781               if (po->op == OP_SHL)
4782                 j = l - j;
4783               else
4784                 j -= 1;
4785               fprintf(fout, "  cond_c = (%s >> %d) & 1;\n",
4786                 buf1, j);
4787             }
4788             else
4789               ferr(po, "zero shift?\n");
4790           }
4791           else
4792             ferr(po, "TODO\n");
4793           pfomask &= ~(1 << PFO_C);
4794         }
4795         fprintf(fout, "  %s %s= %s;", buf1, op_to_c(po),
4796             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4797         output_std_flags(fout, po, &pfomask, buf1);
4798         last_arith_dst = &po->operand[0];
4799         delayed_flag_op = NULL;
4800         break;
4801
4802       case OP_SAR:
4803         assert_operand_cnt(2);
4804         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4805         fprintf(fout, "  %s = %s%s >> %s;", buf1,
4806           lmod_cast_s(po, po->operand[0].lmod), buf1,
4807           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4808         output_std_flags(fout, po, &pfomask, buf1);
4809         last_arith_dst = &po->operand[0];
4810         delayed_flag_op = NULL;
4811         break;
4812
4813       case OP_SHRD:
4814         assert_operand_cnt(3);
4815         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4816         l = lmod_bytes(po, po->operand[0].lmod) * 8;
4817         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4818         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4819         out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[2]);
4820         fprintf(fout, "  %s >>= %s; %s |= %s << (%d - %s);",
4821           buf1, buf3, buf1, buf2, l, buf3);
4822         strcpy(g_comment, "shrd");
4823         output_std_flags(fout, po, &pfomask, buf1);
4824         last_arith_dst = &po->operand[0];
4825         delayed_flag_op = NULL;
4826         break;
4827
4828       case OP_ROL:
4829       case OP_ROR:
4830         assert_operand_cnt(2);
4831         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4832         if (po->operand[1].type == OPT_CONST) {
4833           j = po->operand[1].val;
4834           j %= lmod_bytes(po, po->operand[0].lmod) * 8;
4835           fprintf(fout, po->op == OP_ROL ?
4836             "  %s = (%s << %d) | (%s >> %d);" :
4837             "  %s = (%s >> %d) | (%s << %d);",
4838             buf1, buf1, j, buf1,
4839             lmod_bytes(po, po->operand[0].lmod) * 8 - j);
4840         }
4841         else
4842           ferr(po, "TODO\n");
4843         output_std_flags(fout, po, &pfomask, buf1);
4844         last_arith_dst = &po->operand[0];
4845         delayed_flag_op = NULL;
4846         break;
4847
4848       case OP_RCL:
4849       case OP_RCR:
4850         assert_operand_cnt(2);
4851         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4852         l = lmod_bytes(po, po->operand[0].lmod) * 8;
4853         if (po->operand[1].type == OPT_CONST) {
4854           j = po->operand[1].val % l;
4855           if (j == 0)
4856             ferr(po, "zero rotate\n");
4857           fprintf(fout, "  tmp = (%s >> %d) & 1;\n",
4858             buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
4859           if (po->op == OP_RCL) {
4860             fprintf(fout,
4861               "  %s = (%s << %d) | (cond_c << %d)",
4862               buf1, buf1, j, j - 1);
4863             if (j != 1)
4864               fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
4865           }
4866           else {
4867             fprintf(fout,
4868               "  %s = (%s >> %d) | (cond_c << %d)",
4869               buf1, buf1, j, l - j);
4870             if (j != 1)
4871               fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
4872           }
4873           fprintf(fout, ";\n");
4874           fprintf(fout, "  cond_c = tmp;");
4875         }
4876         else
4877           ferr(po, "TODO\n");
4878         strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
4879         output_std_flags(fout, po, &pfomask, buf1);
4880         last_arith_dst = &po->operand[0];
4881         delayed_flag_op = NULL;
4882         break;
4883
4884       case OP_XOR:
4885         assert_operand_cnt(2);
4886         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4887         if (IS(opr_name(po, 0), opr_name(po, 1))) {
4888           // special case for XOR
4889           if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
4890             fprintf(fout, "  cond_be = 1;\n");
4891             pfomask &= ~(1 << PFO_BE);
4892           }
4893           fprintf(fout, "  %s = 0;",
4894             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4895           last_arith_dst = &po->operand[0];
4896           delayed_flag_op = NULL;
4897           break;
4898         }
4899         goto dualop_arith;
4900
4901       case OP_ADD:
4902         assert_operand_cnt(2);
4903         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4904         if (pfomask & (1 << PFO_C)) {
4905           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4906           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4907           if (po->operand[0].lmod == OPLM_DWORD) {
4908             fprintf(fout, "  tmp64 = (u64)%s + %s;\n", buf1, buf2);
4909             fprintf(fout, "  cond_c = tmp64 >> 32;\n");
4910             fprintf(fout, "  %s = (u32)tmp64;",
4911               out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4912             strcat(g_comment, "add64");
4913           }
4914           else {
4915             fprintf(fout, "  cond_c = ((u32)%s + %s) >> %d;\n",
4916               buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
4917             fprintf(fout, "  %s += %s;",
4918               out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4919               buf2);
4920           }
4921           pfomask &= ~(1 << PFO_C);
4922           output_std_flags(fout, po, &pfomask, buf1);
4923           last_arith_dst = &po->operand[0];
4924           delayed_flag_op = NULL;
4925           break;
4926         }
4927         goto dualop_arith;
4928
4929       case OP_SUB:
4930         assert_operand_cnt(2);
4931         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4932         if (pfomask & ~((1 << PFO_Z) | (1 << PFO_S))) {
4933           for (j = 0; j <= PFO_LE; j++) {
4934             if (!(pfomask & (1 << j)))
4935               continue;
4936             if (j == PFO_Z || j == PFO_S)
4937               continue;
4938
4939             out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
4940             fprintf(fout, "  cond_%s = %s;\n",
4941               parsed_flag_op_names[j], buf1);
4942             pfomask &= ~(1 << j);
4943           }
4944         }
4945         goto dualop_arith;
4946
4947       case OP_ADC:
4948       case OP_SBB:
4949         assert_operand_cnt(2);
4950         propagate_lmod(po, &po->operand[0], &po->operand[1]);
4951         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4952         if (po->op == OP_SBB
4953           && IS(po->operand[0].name, po->operand[1].name))
4954         {
4955           // avoid use of unitialized var
4956           fprintf(fout, "  %s = -cond_c;", buf1);
4957           // carry remains what it was
4958           pfomask &= ~(1 << PFO_C);
4959         }
4960         else {
4961           fprintf(fout, "  %s %s= %s + cond_c;", buf1, op_to_c(po),
4962             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4963         }
4964         output_std_flags(fout, po, &pfomask, buf1);
4965         last_arith_dst = &po->operand[0];
4966         delayed_flag_op = NULL;
4967         break;
4968
4969       case OP_BSF:
4970         assert_operand_cnt(2);
4971         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4972         fprintf(fout, "  %s = %s ? __builtin_ffs(%s) - 1 : 0;",
4973           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4974           buf2, buf2);
4975         output_std_flags(fout, po, &pfomask, buf1);
4976         last_arith_dst = &po->operand[0];
4977         delayed_flag_op = NULL;
4978         strcat(g_comment, "bsf");
4979         break;
4980
4981       case OP_DEC:
4982         if (pfomask & ~(PFOB_S | PFOB_S | PFOB_C)) {
4983           for (j = 0; j <= PFO_LE; j++) {
4984             if (!(pfomask & (1 << j)))
4985               continue;
4986             if (j == PFO_Z || j == PFO_S || j == PFO_C)
4987               continue;
4988
4989             out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
4990             fprintf(fout, "  cond_%s = %s;\n",
4991               parsed_flag_op_names[j], buf1);
4992             pfomask &= ~(1 << j);
4993           }
4994         }
4995         // fallthrough
4996
4997       case OP_INC:
4998         if (pfomask & (1 << PFO_C))
4999           // carry is unaffected by inc/dec.. wtf?
5000           ferr(po, "carry propagation needed\n");
5001
5002         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5003         if (po->operand[0].type == OPT_REG) {
5004           strcpy(buf2, po->op == OP_INC ? "++" : "--");
5005           fprintf(fout, "  %s%s;", buf1, buf2);
5006         }
5007         else {
5008           strcpy(buf2, po->op == OP_INC ? "+" : "-");
5009           fprintf(fout, "  %s %s= 1;", buf1, buf2);
5010         }
5011         output_std_flags(fout, po, &pfomask, buf1);
5012         last_arith_dst = &po->operand[0];
5013         delayed_flag_op = NULL;
5014         break;
5015
5016       case OP_NEG:
5017         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5018         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
5019         fprintf(fout, "  %s = -%s%s;", buf1,
5020           lmod_cast_s(po, po->operand[0].lmod), buf2);
5021         last_arith_dst = &po->operand[0];
5022         delayed_flag_op = NULL;
5023         if (pfomask & (1 << PFO_C)) {
5024           fprintf(fout, "\n  cond_c = (%s != 0);", buf1);
5025           pfomask &= ~(1 << PFO_C);
5026         }
5027         break;
5028
5029       case OP_IMUL:
5030         if (po->operand_cnt == 2) {
5031           propagate_lmod(po, &po->operand[0], &po->operand[1]);
5032           goto dualop_arith;
5033         }
5034         if (po->operand_cnt == 3)
5035           ferr(po, "TODO imul3\n");
5036         // fallthrough
5037       case OP_MUL:
5038         assert_operand_cnt(1);
5039         switch (po->operand[0].lmod) {
5040         case OPLM_DWORD:
5041           strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
5042           fprintf(fout, "  tmp64 = %seax * %s%s;\n", buf1, buf1,
5043             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
5044           fprintf(fout, "  edx = tmp64 >> 32;\n");
5045           fprintf(fout, "  eax = tmp64;");
5046           break;
5047         case OPLM_BYTE:
5048           strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
5049           fprintf(fout, "  LOWORD(eax) = %seax * %s;", buf1,
5050             out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
5051               buf1, 0));
5052           break;
5053         default:
5054           ferr(po, "TODO: unhandled mul type\n");
5055           break;
5056         }
5057         last_arith_dst = NULL;
5058         delayed_flag_op = NULL;
5059         break;
5060
5061       case OP_DIV:
5062       case OP_IDIV:
5063         assert_operand_cnt(1);
5064         if (po->operand[0].lmod != OPLM_DWORD)
5065           ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
5066
5067         out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5068         strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
5069           po->op == OP_IDIV));
5070         switch (po->operand[0].lmod) {
5071         case OPLM_DWORD:
5072           if (po->flags & OPF_32BIT)
5073             snprintf(buf3, sizeof(buf3), "%seax", buf2);
5074           else {
5075             fprintf(fout, "  tmp64 = ((u64)edx << 32) | eax;\n");
5076             snprintf(buf3, sizeof(buf3), "%stmp64",
5077               (po->op == OP_IDIV) ? "(s64)" : "");
5078           }
5079           if (po->operand[0].type == OPT_REG
5080             && po->operand[0].reg == xDX)
5081           {
5082             fprintf(fout, "  eax = %s / %s%s;", buf3, buf2, buf1);
5083             fprintf(fout, "  edx = %s %% %s%s;\n", buf3, buf2, buf1);
5084           }
5085           else {
5086             fprintf(fout, "  edx = %s %% %s%s;\n", buf3, buf2, buf1);
5087             fprintf(fout, "  eax = %s / %s%s;", buf3, buf2, buf1);
5088           }
5089           break;
5090         default:
5091           ferr(po, "unhandled division type\n");
5092         }
5093         last_arith_dst = NULL;
5094         delayed_flag_op = NULL;
5095         break;
5096
5097       case OP_TEST:
5098       case OP_CMP:
5099         propagate_lmod(po, &po->operand[0], &po->operand[1]);
5100         if (pfomask != 0) {
5101           for (j = 0; j < 8; j++) {
5102             if (pfomask & (1 << j)) {
5103               out_cmp_test(buf1, sizeof(buf1), po, j, 0);
5104               fprintf(fout, "  cond_%s = %s;",
5105                 parsed_flag_op_names[j], buf1);
5106             }
5107           }
5108           pfomask = 0;
5109         }
5110         else
5111           no_output = 1;
5112         last_arith_dst = NULL;
5113         delayed_flag_op = po;
5114         break;
5115
5116       case OP_SCC:
5117         // SETcc - should already be handled
5118         break;
5119
5120       // note: we reuse OP_Jcc for SETcc, only flags differ
5121       case OP_JCC:
5122         fprintf(fout, "\n    goto %s;", po->operand[0].name);
5123         break;
5124
5125       case OP_JECXZ:
5126         fprintf(fout, "  if (ecx == 0)\n");
5127         fprintf(fout, "    goto %s;", po->operand[0].name);
5128         strcat(g_comment, "jecxz");
5129         break;
5130
5131       case OP_JMP:
5132         assert_operand_cnt(1);
5133         last_arith_dst = NULL;
5134         delayed_flag_op = NULL;
5135
5136         if (po->operand[0].type == OPT_REGMEM) {
5137           ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
5138                   buf1, buf2);
5139           if (ret != 2)
5140             ferr(po, "parse failure for jmp '%s'\n",
5141               po->operand[0].name);
5142           fprintf(fout, "  goto *jt_%s[%s];", buf1, buf2);
5143           break;
5144         }
5145         else if (po->operand[0].type != OPT_LABEL)
5146           ferr(po, "unhandled jmp type\n");
5147
5148         fprintf(fout, "  goto %s;", po->operand[0].name);
5149         break;
5150
5151       case OP_CALL:
5152         assert_operand_cnt(1);
5153         pp = po->pp;
5154         my_assert_not(pp, NULL);
5155
5156         strcpy(buf3, "  ");
5157         if (po->flags & OPF_CC) {
5158           // we treat conditional branch to another func
5159           // (yes such code exists..) as conditional tailcall
5160           strcat(buf3, "  ");
5161           fprintf(fout, " {\n");
5162         }
5163
5164         if (pp->is_fptr && !pp->is_arg) {
5165           fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
5166             out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
5167               "(void *)", 0));
5168           if (pp->is_unresolved)
5169             fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
5170               buf3, asmfn, po->asmln, pp->name);
5171         }
5172
5173         fprintf(fout, "%s", buf3);
5174         if (strstr(pp->ret_type.name, "int64")) {
5175           if (po->flags & OPF_TAIL)
5176             ferr(po, "int64 and tail?\n");
5177           fprintf(fout, "tmp64 = ");
5178         }
5179         else if (!IS(pp->ret_type.name, "void")) {
5180           if (po->flags & OPF_TAIL) {
5181             if (!IS(g_func_pp->ret_type.name, "void")) {
5182               fprintf(fout, "return ");
5183               if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
5184                 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
5185             }
5186           }
5187           else if (regmask & (1 << xAX)) {
5188             fprintf(fout, "eax = ");
5189             if (pp->ret_type.is_ptr)
5190               fprintf(fout, "(u32)");
5191           }
5192         }
5193
5194         if (pp->name[0] == 0)
5195           ferr(po, "missing pp->name\n");
5196         fprintf(fout, "%s%s(", pp->name,
5197           pp->has_structarg ? "_sa" : "");
5198
5199         if (po->flags & OPF_ATAIL) {
5200           if (pp->argc_stack != g_func_pp->argc_stack
5201             || (pp->argc_stack > 0
5202                 && pp->is_stdcall != g_func_pp->is_stdcall))
5203             ferr(po, "incompatible tailcall\n");
5204           if (g_func_pp->has_retreg)
5205             ferr(po, "TODO: retreg+tailcall\n");
5206
5207           for (arg = j = 0; arg < pp->argc; arg++) {
5208             if (arg > 0)
5209               fprintf(fout, ", ");
5210
5211             cast[0] = 0;
5212             if (pp->arg[arg].type.is_ptr)
5213               snprintf(cast, sizeof(cast), "(%s)",
5214                 pp->arg[arg].type.name);
5215
5216             if (pp->arg[arg].reg != NULL) {
5217               fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5218               continue;
5219             }
5220             // stack arg
5221             for (; j < g_func_pp->argc; j++)
5222               if (g_func_pp->arg[j].reg == NULL)
5223                 break;
5224             fprintf(fout, "%sa%d", cast, j + 1);
5225             j++;
5226           }
5227         }
5228         else {
5229           for (arg = 0; arg < pp->argc; arg++) {
5230             if (arg > 0)
5231               fprintf(fout, ", ");
5232
5233             cast[0] = 0;
5234             if (pp->arg[arg].type.is_ptr)
5235               snprintf(cast, sizeof(cast), "(%s)",
5236                 pp->arg[arg].type.name);
5237
5238             if (pp->arg[arg].reg != NULL) {
5239               if (pp->arg[arg].type.is_retreg)
5240                 fprintf(fout, "&%s", pp->arg[arg].reg);
5241               else
5242                 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5243               continue;
5244             }
5245
5246             // stack arg
5247             tmp_op = pp->arg[arg].datap;
5248             if (tmp_op == NULL)
5249               ferr(po, "parsed_op missing for arg%d\n", arg);
5250
5251             if (tmp_op->flags & OPF_VAPUSH) {
5252               fprintf(fout, "ap");
5253             }
5254             else if (tmp_op->p_argpass != 0) {
5255               fprintf(fout, "a%d", tmp_op->p_argpass);
5256             }
5257             else if (tmp_op->p_argnum != 0) {
5258               fprintf(fout, "%s%s", cast,
5259                 saved_arg_name(buf1, sizeof(buf1),
5260                   tmp_op->p_arggrp, tmp_op->p_argnum));
5261             }
5262             else {
5263               fprintf(fout, "%s",
5264                 out_src_opr(buf1, sizeof(buf1),
5265                   tmp_op, &tmp_op->operand[0], cast, 0));
5266             }
5267           }
5268         }
5269         fprintf(fout, ");");
5270
5271         if (strstr(pp->ret_type.name, "int64")) {
5272           fprintf(fout, "\n");
5273           fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
5274           fprintf(fout, "%seax = tmp64;", buf3);
5275         }
5276
5277         if (pp->is_unresolved) {
5278           snprintf(buf2, sizeof(buf2), " unresolved %dreg",
5279             pp->argc_reg);
5280           strcat(g_comment, buf2);
5281         }
5282
5283         if (po->flags & OPF_TAIL) {
5284           ret = 0;
5285           if (i == opcnt - 1 || pp->is_noreturn)
5286             ret = 0;
5287           else if (IS(pp->ret_type.name, "void"))
5288             ret = 1;
5289           else if (IS(g_func_pp->ret_type.name, "void"))
5290             ret = 1;
5291           // else already handled as 'return f()'
5292
5293           if (ret) {
5294             if (!IS(g_func_pp->ret_type.name, "void")) {
5295               ferr(po, "int func -> void func tailcall?\n");
5296             }
5297             else {
5298               fprintf(fout, "\n%sreturn;", buf3);
5299               strcat(g_comment, " ^ tailcall");
5300             }
5301           }
5302           else
5303             strcat(g_comment, " tailcall");
5304         }
5305         if (pp->is_noreturn)
5306           strcat(g_comment, " noreturn");
5307         if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
5308           strcat(g_comment, " argframe");
5309         if (po->flags & OPF_CC)
5310           strcat(g_comment, " cond");
5311
5312         if (po->flags & OPF_CC)
5313           fprintf(fout, "\n  }");
5314
5315         delayed_flag_op = NULL;
5316         last_arith_dst = NULL;
5317         break;
5318
5319       case OP_RET:
5320         if (g_func_pp->is_vararg)
5321           fprintf(fout, "  va_end(ap);\n");
5322         if (g_func_pp->has_retreg) {
5323           for (arg = 0; arg < g_func_pp->argc; arg++)
5324             if (g_func_pp->arg[arg].type.is_retreg)
5325               fprintf(fout, "  *r_%s = %s;\n",
5326                 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
5327         }
5328  
5329         if (IS(g_func_pp->ret_type.name, "void")) {
5330           if (i != opcnt - 1 || label_pending)
5331             fprintf(fout, "  return;");
5332         }
5333         else if (g_func_pp->ret_type.is_ptr) {
5334           fprintf(fout, "  return (%s)eax;",
5335             g_func_pp->ret_type.name);
5336         }
5337         else if (IS(g_func_pp->ret_type.name, "__int64"))
5338           fprintf(fout, "  return ((u64)edx << 32) | eax;");
5339         else
5340           fprintf(fout, "  return eax;");
5341
5342         last_arith_dst = NULL;
5343         delayed_flag_op = NULL;
5344         break;
5345
5346       case OP_PUSH:
5347         out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5348         if (po->p_argnum != 0) {
5349           // special case - saved func arg
5350           fprintf(fout, "  %s = %s;",
5351             saved_arg_name(buf2, sizeof(buf2),
5352               po->p_arggrp, po->p_argnum), buf1);
5353           break;
5354         }
5355         else if (po->flags & OPF_RSAVE) {
5356           fprintf(fout, "  s_%s = %s;", buf1, buf1);
5357           break;
5358         }
5359         else if (g_func_pp->is_userstack) {
5360           fprintf(fout, "  *(--esp) = %s;", buf1);
5361           break;
5362         }
5363         if (!(g_ida_func_attr & IDAFA_NORETURN))
5364           ferr(po, "stray push encountered\n");
5365         no_output = 1;
5366         break;
5367
5368       case OP_POP:
5369         if (po->flags & OPF_RSAVE) {
5370           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5371           fprintf(fout, "  %s = s_%s;", buf1, buf1);
5372           break;
5373         }
5374         else if (po->datap != NULL) {
5375           // push/pop pair
5376           tmp_op = po->datap;
5377           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5378           fprintf(fout, "  %s = %s;", buf1,
5379             out_src_opr(buf2, sizeof(buf2),
5380               tmp_op, &tmp_op->operand[0],
5381               default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5382           break;
5383         }
5384         else if (g_func_pp->is_userstack) {
5385           fprintf(fout, "  %s = *esp++;",
5386             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5387           break;
5388         }
5389         else
5390           ferr(po, "stray pop encountered\n");
5391         break;
5392
5393       case OP_NOP:
5394         no_output = 1;
5395         break;
5396
5397       // mmx
5398       case OP_EMMS:
5399         strcpy(g_comment, "(emms)");
5400         break;
5401
5402       default:
5403         no_output = 1;
5404         ferr(po, "unhandled op type %d, flags %x\n",
5405           po->op, po->flags);
5406         break;
5407     }
5408
5409     if (g_comment[0] != 0) {
5410       char *p = g_comment;
5411       while (my_isblank(*p))
5412         p++;
5413       fprintf(fout, "  // %s", p);
5414       g_comment[0] = 0;
5415       no_output = 0;
5416     }
5417     if (!no_output)
5418       fprintf(fout, "\n");
5419
5420     // some sanity checking
5421     if (po->flags & OPF_REP) {
5422       if (po->op != OP_STOS && po->op != OP_MOVS
5423           && po->op != OP_CMPS && po->op != OP_SCAS)
5424         ferr(po, "unexpected rep\n");
5425       if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
5426           && (po->op == OP_CMPS || po->op == OP_SCAS))
5427         ferr(po, "cmps/scas with plain rep\n");
5428     }
5429     if ((po->flags & (OPF_REPZ|OPF_REPNZ))
5430         && po->op != OP_CMPS && po->op != OP_SCAS)
5431       ferr(po, "unexpected repz/repnz\n");
5432
5433     if (pfomask != 0)
5434       ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
5435
5436     // see is delayed flag stuff is still valid
5437     if (delayed_flag_op != NULL && delayed_flag_op != po) {
5438       if (is_any_opr_modified(delayed_flag_op, po, 0))
5439         delayed_flag_op = NULL;
5440     }
5441
5442     if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
5443       if (is_opr_modified(last_arith_dst, po))
5444         last_arith_dst = NULL;
5445     }
5446
5447     label_pending = 0;
5448   }
5449
5450   if (g_stack_fsz && !g_stack_frame_used)
5451     fprintf(fout, "  (void)sf;\n");
5452
5453   fprintf(fout, "}\n\n");
5454
5455   gen_x_cleanup(opcnt);
5456 }
5457
5458 static void gen_x_cleanup(int opcnt)
5459 {
5460   int i;
5461
5462   for (i = 0; i < opcnt; i++) {
5463     struct label_ref *lr, *lr_del;
5464
5465     lr = g_label_refs[i].next;
5466     while (lr != NULL) {
5467       lr_del = lr;
5468       lr = lr->next;
5469       free(lr_del);
5470     }
5471     g_label_refs[i].i = -1;
5472     g_label_refs[i].next = NULL;
5473
5474     if (ops[i].op == OP_CALL) {
5475       if (ops[i].pp)
5476         proto_release(ops[i].pp);
5477     }
5478   }
5479   g_func_pp = NULL;
5480 }
5481
5482 struct func_proto_dep;
5483
5484 struct func_prototype {
5485   char name[NAMELEN];
5486   int id;
5487   int argc_stack;
5488   int regmask_dep;
5489   int has_ret:3;                 // -1, 0, 1: unresolved, no, yes
5490   unsigned int dep_resolved:1;
5491   unsigned int is_stdcall:1;
5492   struct func_proto_dep *dep_func;
5493   int dep_func_cnt;
5494   const struct parsed_proto *pp; // seed pp, if any
5495 };
5496
5497 struct func_proto_dep {
5498   char *name;
5499   struct func_prototype *proto;
5500   int regmask_live;             // .. at the time of call
5501   unsigned int ret_dep:1;       // return from this is caller's return
5502 };
5503
5504 static struct func_prototype *hg_fp;
5505 static int hg_fp_cnt;
5506
5507 static struct scanned_var {
5508   char name[NAMELEN];
5509   enum opr_lenmod lmod;
5510   unsigned int is_seeded:1;
5511   unsigned int is_c_str:1;
5512 } *hg_vars;
5513 static int hg_var_cnt;
5514
5515 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
5516   int count);
5517
5518 static struct func_proto_dep *hg_fp_find_dep(struct func_prototype *fp,
5519   const char *name)
5520 {
5521   int i;
5522
5523   for (i = 0; i < fp->dep_func_cnt; i++)
5524     if (IS(fp->dep_func[i].name, name))
5525       return &fp->dep_func[i];
5526
5527   return NULL;
5528 }
5529
5530 static void hg_fp_add_dep(struct func_prototype *fp, const char *name)
5531 {
5532   // is it a dupe?
5533   if (hg_fp_find_dep(fp, name))
5534     return;
5535
5536   if ((fp->dep_func_cnt & 0xff) == 0) {
5537     fp->dep_func = realloc(fp->dep_func,
5538       sizeof(fp->dep_func[0]) * (fp->dep_func_cnt + 0x100));
5539     my_assert_not(fp->dep_func, NULL);
5540     memset(&fp->dep_func[fp->dep_func_cnt], 0,
5541       sizeof(fp->dep_func[0]) * 0x100);
5542   }
5543   fp->dep_func[fp->dep_func_cnt].name = strdup(name);
5544   fp->dep_func_cnt++;
5545 }
5546
5547 static int hg_fp_cmp_name(const void *p1_, const void *p2_)
5548 {
5549   const struct func_prototype *p1 = p1_, *p2 = p2_;
5550   return strcmp(p1->name, p2->name);
5551 }
5552
5553 #if 0
5554 static int hg_fp_cmp_id(const void *p1_, const void *p2_)
5555 {
5556   const struct func_prototype *p1 = p1_, *p2 = p2_;
5557   return p1->id - p2->id;
5558 }
5559 #endif
5560
5561 // recursive register dep pass
5562 // - track saved regs (part 2)
5563 // - try to figure out arg-regs
5564 // - calculate reg deps
5565 static void gen_hdr_dep_pass(int i, int opcnt, unsigned char *cbits,
5566   struct func_prototype *fp, int regmask_save, int regmask_dst,
5567   int *regmask_dep, int *has_ret)
5568 {
5569   struct func_proto_dep *dep;
5570   struct parsed_op *po;
5571   int from_caller = 0;
5572   int depth;
5573   int j, l;
5574   int reg;
5575   int ret;
5576
5577   for (; i < opcnt; i++)
5578   {
5579     if (cbits[i >> 3] & (1 << (i & 7)))
5580       return;
5581     cbits[i >> 3] |= (1 << (i & 7));
5582
5583     po = &ops[i];
5584
5585     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
5586       if (po->btj != NULL) {
5587         // jumptable
5588         for (j = 0; j < po->btj->count; j++) {
5589           gen_hdr_dep_pass(po->btj->d[j].bt_i, opcnt, cbits, fp,
5590             regmask_save, regmask_dst, regmask_dep, has_ret);
5591         }
5592         return;
5593       }
5594
5595       if (po->bt_i < 0) {
5596         ferr(po, "dead branch\n");
5597         return;
5598       }
5599
5600       if (po->flags & OPF_CJMP) {
5601         gen_hdr_dep_pass(po->bt_i, opcnt, cbits, fp,
5602           regmask_save, regmask_dst, regmask_dep, has_ret);
5603       }
5604       else {
5605         i = po->bt_i - 1;
5606       }
5607       continue;
5608     }
5609
5610     if (po->flags & OPF_FARG)
5611       /* (just calculate register deps) */;
5612     else if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
5613     {
5614       reg = po->operand[0].reg;
5615       if (reg < 0)
5616         ferr(po, "reg not set for push?\n");
5617
5618       if (po->flags & OPF_RSAVE) {
5619         regmask_save |= 1 << reg;
5620         continue;
5621       }
5622       if (po->flags & OPF_DONE)
5623         continue;
5624
5625       depth = 0;
5626       ret = scan_for_pop(i + 1, opcnt,
5627               po->operand[0].name, i + opcnt * 2, 0, &depth, 0);
5628       if (ret == 1) {
5629         regmask_save |= 1 << reg;
5630         po->flags |= OPF_RMD;
5631         scan_for_pop(i + 1, opcnt,
5632           po->operand[0].name, i + opcnt * 3, 0, &depth, 1);
5633         continue;
5634       }
5635     }
5636     else if (po->flags & OPF_RMD)
5637       continue;
5638     else if (po->op == OP_CALL) {
5639       po->regmask_dst |= 1 << xAX;
5640
5641       dep = hg_fp_find_dep(fp, po->operand[0].name);
5642       if (dep != NULL)
5643         dep->regmask_live = regmask_save | regmask_dst;
5644     }
5645     else if (po->op == OP_RET) {
5646       if (po->operand_cnt > 0) {
5647         fp->is_stdcall = 1;
5648         if (fp->argc_stack >= 0
5649             && fp->argc_stack != po->operand[0].val / 4)
5650           ferr(po, "ret mismatch? (%d)\n", fp->argc_stack * 4);
5651         fp->argc_stack = po->operand[0].val / 4;
5652       }
5653     }
5654
5655     if (*has_ret != 0 && (po->flags & OPF_TAIL)) {
5656       if (po->op == OP_CALL) {
5657         j = i;
5658         ret = 1;
5659       }
5660       else {
5661         struct parsed_opr opr = { 0, };
5662         opr.type = OPT_REG;
5663         opr.reg = xAX;
5664         j = -1;
5665         from_caller = 0;
5666         ret = resolve_origin(i, &opr, i + opcnt * 4, &j, &from_caller);
5667       }
5668
5669       if (ret == -1 && from_caller) {
5670         // unresolved eax - probably void func
5671         *has_ret = 0;
5672       }
5673       else {
5674         if (ops[j].op == OP_CALL) {
5675           dep = hg_fp_find_dep(fp, po->operand[0].name);
5676           if (dep != NULL)
5677             dep->ret_dep = 1;
5678           else
5679             *has_ret = 1;
5680         }
5681         else
5682           *has_ret = 1;
5683       }
5684     }
5685
5686     l = regmask_save | regmask_dst;
5687     if (g_bp_frame && !(po->flags & OPF_EBP_S))
5688       l |= 1 << xBP;
5689
5690     l = po->regmask_src & ~l;
5691 #if 0
5692     if (l)
5693       fnote(po, "dep |= %04x, dst %04x, save %04x (f %x)\n",
5694         l, regmask_dst, regmask_save, po->flags);
5695 #endif
5696     *regmask_dep |= l;
5697     regmask_dst |= po->regmask_dst;
5698
5699     if (po->flags & OPF_TAIL)
5700       return;
5701   }
5702 }
5703
5704 static void gen_hdr(const char *funcn, int opcnt)
5705 {
5706   int save_arg_vars[MAX_ARG_GRP] = { 0, };
5707   unsigned char cbits[MAX_OPS / 8];
5708   const struct parsed_proto *pp_c;
5709   struct parsed_proto *pp;
5710   struct func_prototype *fp;
5711   struct parsed_data *pd;
5712   struct parsed_op *po;
5713   const char *tmpname;
5714   int regmask_dummy = 0;
5715   int regmask_dep;
5716   int max_bp_offset = 0;
5717   int has_ret;
5718   int i, j, l, ret;
5719
5720   if ((hg_fp_cnt & 0xff) == 0) {
5721     hg_fp = realloc(hg_fp, sizeof(hg_fp[0]) * (hg_fp_cnt + 0x100));
5722     my_assert_not(hg_fp, NULL);
5723     memset(hg_fp + hg_fp_cnt, 0, sizeof(hg_fp[0]) * 0x100);
5724   }
5725
5726   fp = &hg_fp[hg_fp_cnt];
5727   snprintf(fp->name, sizeof(fp->name), "%s", funcn);
5728   fp->id = hg_fp_cnt;
5729   fp->argc_stack = -1;
5730   hg_fp_cnt++;
5731
5732   // perhaps already in seed header?
5733   fp->pp = proto_parse(g_fhdr, funcn, 1);
5734   if (fp->pp != NULL) {
5735     fp->argc_stack = fp->pp->argc_stack;
5736     fp->is_stdcall = fp->pp->is_stdcall;
5737     fp->regmask_dep = get_pp_arg_regmask(fp->pp);
5738     fp->has_ret = !IS(fp->pp->ret_type.name, "void");
5739     return;
5740   }
5741
5742   g_bp_frame = g_sp_frame = g_stack_fsz = 0;
5743   g_stack_frame_used = 0;
5744
5745   // pass1:
5746   // - handle ebp/esp frame, remove ops related to it
5747   scan_prologue_epilogue(opcnt);
5748
5749   // pass2:
5750   // - collect calls
5751   // - resolve all branches
5752   for (i = 0; i < opcnt; i++)
5753   {
5754     po = &ops[i];
5755     po->bt_i = -1;
5756     po->btj = NULL;
5757
5758     if (po->flags & (OPF_RMD|OPF_DONE))
5759       continue;
5760
5761     if (po->op == OP_CALL) {
5762       tmpname = opr_name(po, 0);
5763       pp = NULL;
5764       if (po->operand[0].type == OPT_LABEL) {
5765         hg_fp_add_dep(fp, tmpname);
5766
5767         // perhaps a call to already known func?
5768         pp_c = proto_parse(g_fhdr, tmpname, 1);
5769         if (pp_c != NULL)
5770           pp = proto_clone(pp_c);
5771       }
5772       else if (po->datap != NULL) {
5773         pp = calloc(1, sizeof(*pp));
5774         my_assert_not(pp, NULL);
5775
5776         ret = parse_protostr(po->datap, pp);
5777         if (ret < 0)
5778           ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
5779         free(po->datap);
5780         po->datap = NULL;
5781       }
5782       if (pp != NULL && pp->is_noreturn)
5783         po->flags |= OPF_TAIL;
5784
5785       po->pp = pp;
5786       continue;
5787     }
5788
5789     if (!(po->flags & OPF_JMP) || po->op == OP_RET)
5790       continue;
5791
5792     if (po->operand[0].type == OPT_REGMEM) {
5793       pd = try_resolve_jumptab(i, opcnt);
5794       if (pd == NULL)
5795         goto tailcall;
5796
5797       po->btj = pd;
5798       continue;
5799     }
5800
5801     for (l = 0; l < opcnt; l++) {
5802       if (g_labels[l] != NULL
5803           && IS(po->operand[0].name, g_labels[l]))
5804       {
5805         add_label_ref(&g_label_refs[l], i);
5806         po->bt_i = l;
5807         break;
5808       }
5809     }
5810
5811     if (po->bt_i != -1 || (po->flags & OPF_RMD))
5812       continue;
5813
5814     if (po->operand[0].type == OPT_LABEL)
5815       // assume tail call
5816       goto tailcall;
5817
5818     ferr(po, "unhandled branch\n");
5819
5820 tailcall:
5821     po->op = OP_CALL;
5822     po->flags |= OPF_TAIL;
5823     if (i > 0 && ops[i - 1].op == OP_POP)
5824       po->flags |= OPF_ATAIL;
5825     i--; // reprocess
5826   }
5827
5828   // pass3:
5829   // - remove dead labels
5830   // - handle push <const>/pop pairs
5831   for (i = 0; i < opcnt; i++)
5832   {
5833     if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
5834       free(g_labels[i]);
5835       g_labels[i] = NULL;
5836     }
5837
5838     po = &ops[i];
5839     if (po->flags & (OPF_RMD|OPF_DONE))
5840       continue;
5841
5842     if (po->op == OP_PUSH && po->operand[0].type == OPT_CONST)
5843       scan_for_pop_const(i, opcnt);
5844   }
5845
5846   // pass4:
5847   // - process trivial calls
5848   for (i = 0; i < opcnt; i++)
5849   {
5850     po = &ops[i];
5851     if (po->flags & (OPF_RMD|OPF_DONE))
5852       continue;
5853
5854     if (po->op == OP_CALL)
5855     {
5856       pp = process_call_early(i, opcnt, &j);
5857       if (pp != NULL) {
5858         if (!(po->flags & OPF_ATAIL))
5859           // since we know the args, try to collect them
5860           if (collect_call_args_early(po, i, pp, &regmask_dummy) != 0)
5861             pp = NULL;
5862       }
5863
5864       if (pp != NULL) {
5865         if (j >= 0) {
5866           // commit esp adjust
5867           ops[j].flags |= OPF_RMD;
5868           if (ops[j].op != OP_POP)
5869             patch_esp_adjust(&ops[j], pp->argc_stack * 4);
5870           else
5871             ops[j].flags |= OPF_DONE;
5872         }
5873
5874         po->flags |= OPF_DONE;
5875       }
5876     }
5877   }
5878
5879   // pass5:
5880   // - track saved regs (simple)
5881   // - process calls
5882   for (i = 0; i < opcnt; i++)
5883   {
5884     po = &ops[i];
5885     if (po->flags & (OPF_RMD|OPF_DONE))
5886       continue;
5887
5888     if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
5889     {
5890       ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
5891       if (ret == 0) {
5892         // regmask_save |= 1 << po->operand[0].reg; // do it later
5893         po->flags |= OPF_RSAVE | OPF_RMD | OPF_DONE;
5894         scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, OPF_RMD);
5895       }
5896     }
5897     else if (po->op == OP_CALL && !(po->flags & OPF_DONE))
5898     {
5899       pp = process_call(i, opcnt);
5900
5901       if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
5902         // since we know the args, collect them
5903         ret = collect_call_args(po, i, pp, &regmask_dummy, save_arg_vars,
5904           i + opcnt * 1);
5905       }
5906     }
5907   }
5908
5909   // pass6
5910   memset(cbits, 0, sizeof(cbits));
5911   regmask_dep = 0;
5912   has_ret = -1;
5913
5914   gen_hdr_dep_pass(0, opcnt, cbits, fp, 0, 0, &regmask_dep, &has_ret);
5915
5916   // find unreachable code - must be fixed in IDA
5917   for (i = 0; i < opcnt; i++)
5918   {
5919     if (cbits[i >> 3] & (1 << (i & 7)))
5920       continue;
5921
5922     if (ops[i].op != OP_NOP)
5923       ferr(&ops[i], "unreachable code\n");
5924   }
5925
5926   if (has_ret == -1 && (regmask_dep & (1 << xAX)))
5927     has_ret = 1;
5928
5929   for (i = 0; i < g_eqcnt; i++) {
5930     if (g_eqs[i].offset > max_bp_offset && g_eqs[i].offset < 4*32)
5931       max_bp_offset = g_eqs[i].offset;
5932   }
5933
5934   if (fp->argc_stack < 0) {
5935     max_bp_offset = (max_bp_offset + 3) & ~3;
5936     fp->argc_stack = max_bp_offset / 4;
5937     if ((g_ida_func_attr & IDAFA_BP_FRAME) && fp->argc_stack > 0)
5938       fp->argc_stack--;
5939   }
5940
5941   fp->regmask_dep = regmask_dep & ~(1 << xSP);
5942   fp->has_ret = has_ret;
5943 #if 0
5944   printf("// has_ret %d, regmask_dep %x\n",
5945     fp->has_ret, fp->regmask_dep);
5946   output_hdr_fp(stdout, fp, 1);
5947   if (IS(funcn, "sub_100073FD")) exit(1);
5948 #endif
5949
5950   gen_x_cleanup(opcnt);
5951 }
5952
5953 static void hg_fp_resolve_deps(struct func_prototype *fp)
5954 {
5955   struct func_prototype fp_s;
5956   int dep;
5957   int i;
5958
5959   // this thing is recursive, so mark first..
5960   fp->dep_resolved = 1;
5961
5962   for (i = 0; i < fp->dep_func_cnt; i++) {
5963     strcpy(fp_s.name, fp->dep_func[i].name);
5964     fp->dep_func[i].proto = bsearch(&fp_s, hg_fp, hg_fp_cnt,
5965       sizeof(hg_fp[0]), hg_fp_cmp_name);
5966     if (fp->dep_func[i].proto != NULL) {
5967       if (!fp->dep_func[i].proto->dep_resolved)
5968         hg_fp_resolve_deps(fp->dep_func[i].proto);
5969
5970       dep = ~fp->dep_func[i].regmask_live
5971            & fp->dep_func[i].proto->regmask_dep;
5972       fp->regmask_dep |= dep;
5973       // printf("dep %s %s |= %x\n", fp->name,
5974       //   fp->dep_func[i].name, dep);
5975
5976       if (fp->has_ret == -1)
5977         fp->has_ret = fp->dep_func[i].proto->has_ret;
5978     }
5979   }
5980 }
5981
5982 static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
5983   int count)
5984 {
5985   const struct parsed_proto *pp;
5986   char *p, namebuf[NAMELEN];
5987   const char *name;
5988   int regmask_dep;
5989   int argc_stack;
5990   int j, arg;
5991
5992   for (; count > 0; count--, fp++) {
5993     if (fp->has_ret == -1)
5994       fprintf(fout, "// ret unresolved\n");
5995 #if 0
5996     fprintf(fout, "// dep:");
5997     for (j = 0; j < fp->dep_func_cnt; j++) {
5998       fprintf(fout, " %s/", fp->dep_func[j].name);
5999       if (fp->dep_func[j].proto != NULL)
6000         fprintf(fout, "%04x/%d", fp->dep_func[j].proto->regmask_dep,
6001           fp->dep_func[j].proto->has_ret);
6002     }
6003     fprintf(fout, "\n");
6004 #endif
6005
6006     p = strchr(fp->name, '@');
6007     if (p != NULL) {
6008       memcpy(namebuf, fp->name, p - fp->name);
6009       namebuf[p - fp->name] = 0;
6010       name = namebuf;
6011     }
6012     else
6013       name = fp->name;
6014     if (name[0] == '_')
6015       name++;
6016
6017     pp = proto_parse(g_fhdr, name, 1);
6018     if (pp != NULL && pp->is_include)
6019       continue;
6020
6021     regmask_dep = fp->regmask_dep;
6022     argc_stack = fp->argc_stack;
6023
6024     fprintf(fout, "%-5s", fp->pp ? fp->pp->ret_type.name :
6025       (fp->has_ret ? "int" : "void"));
6026     if (regmask_dep && (fp->is_stdcall || argc_stack == 0)
6027       && (regmask_dep & ~((1 << xCX) | (1 << xDX))) == 0)
6028     {
6029       fprintf(fout, "  __fastcall    ");
6030       if (!(regmask_dep & (1 << xDX)) && argc_stack == 0)
6031         argc_stack = 1;
6032       else
6033         argc_stack += 2;
6034       regmask_dep = 0;
6035     }
6036     else if (regmask_dep && !fp->is_stdcall) {
6037       fprintf(fout, "/*__usercall*/  ");
6038     }
6039     else if (regmask_dep) {
6040       fprintf(fout, "/*__userpurge*/ ");
6041     }
6042     else if (fp->is_stdcall)
6043       fprintf(fout, "  __stdcall     ");
6044     else
6045       fprintf(fout, "  __cdecl       ");
6046
6047     fprintf(fout, "%s(", name);
6048
6049     arg = 0;
6050     for (j = 0; j < xSP; j++) {
6051       if (regmask_dep & (1 << j)) {
6052         arg++;
6053         if (arg != 1)
6054           fprintf(fout, ", ");
6055         if (fp->pp != NULL)
6056           fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6057         else
6058           fprintf(fout, "int");
6059         fprintf(fout, " a%d/*<%s>*/", arg, regs_r32[j]);
6060       }
6061     }
6062
6063     for (j = 0; j < argc_stack; j++) {
6064       arg++;
6065       if (arg != 1)
6066         fprintf(fout, ", ");
6067       if (fp->pp != NULL) {
6068         fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6069         if (!fp->pp->arg[arg - 1].type.is_ptr)
6070           fprintf(fout, " ");
6071       }
6072       else
6073         fprintf(fout, "int ");
6074       fprintf(fout, "a%d", arg);
6075     }
6076
6077     fprintf(fout, ");\n");
6078   }
6079 }
6080
6081 static void output_hdr(FILE *fout)
6082 {
6083   static const char *lmod_c_names[] = {
6084     [OPLM_UNSPEC] = "???",
6085     [OPLM_BYTE]  = "uint8_t",
6086     [OPLM_WORD]  = "uint16_t",
6087     [OPLM_DWORD] = "uint32_t",
6088     [OPLM_QWORD] = "uint64_t",
6089   };
6090   const struct scanned_var *var;
6091   int i;
6092
6093   // resolve deps
6094   qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_name);
6095   for (i = 0; i < hg_fp_cnt; i++)
6096     hg_fp_resolve_deps(&hg_fp[i]);
6097
6098   // note: messes up .proto ptr, don't use
6099   //qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_id);
6100
6101   // output variables
6102   for (i = 0; i < hg_var_cnt; i++) {
6103     var = &hg_vars[i];
6104
6105     if (var->is_c_str)
6106       fprintf(fout, "extern %-8s %s[];", "char", var->name);
6107     else
6108       fprintf(fout, "extern %-8s %s;",
6109         lmod_c_names[var->lmod], var->name);
6110
6111     if (var->is_seeded)
6112       fprintf(fout, " // seeded");
6113     fprintf(fout, "\n");
6114   }
6115
6116   fprintf(fout, "\n");
6117
6118   // output function prototypes
6119   output_hdr_fp(fout, hg_fp, hg_fp_cnt);
6120 }
6121
6122 // read a line, truncating it if it doesn't fit
6123 static char *my_fgets(char *s, size_t size, FILE *stream)
6124 {
6125   char *ret, *ret2;
6126   char buf[64];
6127   int p;
6128
6129   p = size - 2;
6130   if (p >= 0)
6131     s[p] = 0;
6132
6133   ret = fgets(s, size, stream);
6134   if (ret != NULL && p >= 0 && s[p] != 0 && s[p] != '\n') {
6135     p = sizeof(buf) - 2;
6136     do {
6137       buf[p] = 0;
6138       ret2 = fgets(buf, sizeof(buf), stream);
6139     }
6140     while (ret2 != NULL && buf[p] != 0 && buf[p] != '\n');
6141   }
6142
6143   return ret;
6144 }
6145
6146 // '=' needs special treatment
6147 // also ' quote
6148 static char *next_word_s(char *w, size_t wsize, char *s)
6149 {
6150   size_t i;
6151
6152   s = sskip(s);
6153
6154   i = 0;
6155   if (*s == '\'') {
6156     w[0] = s[0];
6157     for (i = 1; i < wsize - 1; i++) {
6158       if (s[i] == 0) {
6159         printf("warning: missing closing quote: \"%s\"\n", s);
6160         break;
6161       }
6162       if (s[i] == '\'')
6163         break;
6164       w[i] = s[i];
6165     }
6166   }
6167
6168   for (; i < wsize - 1; i++) {
6169     if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
6170       break;
6171     w[i] = s[i];
6172   }
6173   w[i] = 0;
6174
6175   if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
6176     printf("warning: '%s' truncated\n", w);
6177
6178   return s + i;
6179 }
6180
6181 static void scan_variables(FILE *fasm)
6182 {
6183   const struct parsed_proto *pp_c;
6184   struct scanned_var *var;
6185   char line[256] = { 0, };
6186   char words[3][256];
6187   char *p = NULL;
6188   int wordc;
6189   int l;
6190
6191   while (!feof(fasm))
6192   {
6193     // skip to next data section
6194     while (my_fgets(line, sizeof(line), fasm))
6195     {
6196       asmln++;
6197
6198       p = sskip(line);
6199       if (*p == 0 || *p == ';')
6200         continue;
6201
6202       p = sskip(next_word_s(words[0], sizeof(words[0]), p));
6203       if (*p == 0 || *p == ';')
6204         continue;
6205
6206       if (*p != 's' || !IS_START(p, "segment para public"))
6207         continue;
6208
6209       break;
6210     }
6211
6212     if (p == NULL || !IS_START(p, "segment para public"))
6213       break;
6214     p = sskip(p + 19);
6215
6216     if (!IS_START(p, "'DATA'"))
6217       continue;
6218
6219     // now process it
6220     while (my_fgets(line, sizeof(line), fasm))
6221     {
6222       asmln++;
6223
6224       p = line;
6225       if (my_isblank(*p))
6226         continue;
6227
6228       p = sskip(p);
6229       if (*p == 0 || *p == ';')
6230         continue;
6231
6232       for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6233         words[wordc][0] = 0;
6234         p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6235         if (*p == 0 || *p == ';') {
6236           wordc++;
6237           break;
6238         }
6239       }
6240
6241       if (wordc == 2 && IS(words[1], "ends"))
6242         break;
6243       if (wordc < 2)
6244         continue;
6245
6246       if ((hg_var_cnt & 0xff) == 0) {
6247         hg_vars = realloc(hg_vars, sizeof(hg_vars[0])
6248                    * (hg_var_cnt + 0x100));
6249         my_assert_not(hg_vars, NULL);
6250         memset(hg_vars + hg_var_cnt, 0, sizeof(hg_vars[0]) * 0x100);
6251       }
6252
6253       var = &hg_vars[hg_var_cnt++];
6254       snprintf(var->name, sizeof(var->name), "%s", words[0]);
6255
6256       // maybe already in seed header?
6257       pp_c = proto_parse(g_fhdr, var->name, 1);
6258       if (pp_c != NULL) {
6259         if (pp_c->is_func)
6260           aerr("func?\n");
6261         else if (pp_c->is_fptr) {
6262           var->lmod = OPLM_DWORD;
6263           //var->is_ptr = 1;
6264         }
6265         else if (!guess_lmod_from_c_type(&var->lmod, &pp_c->type))
6266           aerr("unhandled C type '%s' for '%s'\n",
6267             pp_c->type.name, var->name);
6268
6269         var->is_seeded = 1;
6270         continue;
6271       }
6272
6273       if      (IS(words[1], "dd"))
6274         var->lmod = OPLM_DWORD;
6275       else if (IS(words[1], "dw"))
6276         var->lmod = OPLM_WORD;
6277       else if (IS(words[1], "db")) {
6278         var->lmod = OPLM_BYTE;
6279         if (wordc >= 3 && (l = strlen(words[2])) > 4) {
6280           if (words[2][0] == '\'' && IS(words[2] + l - 2, ",0"))
6281             var->is_c_str = 1;
6282         }
6283       }
6284       else if (IS(words[1], "dq"))
6285         var->lmod = OPLM_QWORD;
6286       //else if (IS(words[1], "dt"))
6287       else
6288         aerr("type '%s' not known\n", words[1]);
6289     }
6290   }
6291
6292   rewind(fasm);
6293   asmln = 0;
6294 }
6295
6296 static void set_label(int i, const char *name)
6297 {
6298   const char *p;
6299   int len;
6300
6301   len = strlen(name);
6302   p = strchr(name, ':');
6303   if (p != NULL)
6304     len = p - name;
6305
6306   if (g_labels[i] != NULL && !IS_START(g_labels[i], "algn_"))
6307     aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
6308   g_labels[i] = realloc(g_labels[i], len + 1);
6309   my_assert_not(g_labels[i], NULL);
6310   memcpy(g_labels[i], name, len);
6311   g_labels[i][len] = 0;
6312 }
6313
6314 struct chunk_item {
6315   char *name;
6316   long fptr;
6317   int asmln;
6318 };
6319
6320 static struct chunk_item *func_chunks;
6321 static int func_chunk_cnt;
6322 static int func_chunk_alloc;
6323
6324 static void add_func_chunk(FILE *fasm, const char *name, int line)
6325 {
6326   if (func_chunk_cnt >= func_chunk_alloc) {
6327     func_chunk_alloc *= 2;
6328     func_chunks = realloc(func_chunks,
6329       func_chunk_alloc * sizeof(func_chunks[0]));
6330     my_assert_not(func_chunks, NULL);
6331   }
6332   func_chunks[func_chunk_cnt].fptr = ftell(fasm);
6333   func_chunks[func_chunk_cnt].name = strdup(name);
6334   func_chunks[func_chunk_cnt].asmln = line;
6335   func_chunk_cnt++;
6336 }
6337
6338 static int cmp_chunks(const void *p1, const void *p2)
6339 {
6340   const struct chunk_item *c1 = p1, *c2 = p2;
6341   return strcmp(c1->name, c2->name);
6342 }
6343
6344 static int cmpstringp(const void *p1, const void *p2)
6345 {
6346   return strcmp(*(char * const *)p1, *(char * const *)p2);
6347 }
6348
6349 static void scan_ahead(FILE *fasm)
6350 {
6351   char words[2][256];
6352   char line[256];
6353   long oldpos;
6354   int oldasmln;
6355   int wordc;
6356   char *p;
6357   int i;
6358
6359   oldpos = ftell(fasm);
6360   oldasmln = asmln;
6361
6362   while (my_fgets(line, sizeof(line), fasm))
6363   {
6364     wordc = 0;
6365     asmln++;
6366
6367     p = sskip(line);
6368     if (*p == 0)
6369       continue;
6370
6371     if (*p == ';')
6372     {
6373       // get rid of random tabs
6374       for (i = 0; line[i] != 0; i++)
6375         if (line[i] == '\t')
6376           line[i] = ' ';
6377
6378       if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6379       {
6380         p += 30;
6381         next_word(words[0], sizeof(words[0]), p);
6382         if (words[0][0] == 0)
6383           aerr("missing name for func chunk?\n");
6384
6385         add_func_chunk(fasm, words[0], asmln);
6386       }
6387       else if (IS_START(p, "; sctend"))
6388         break;
6389
6390       continue;
6391     } // *p == ';'
6392
6393     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6394       words[wordc][0] = 0;
6395       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6396       if (*p == 0 || *p == ';') {
6397         wordc++;
6398         break;
6399       }
6400     }
6401
6402     if (wordc == 2 && IS(words[1], "ends"))
6403       break;
6404   }
6405
6406   fseek(fasm, oldpos, SEEK_SET);
6407   asmln = oldasmln;
6408 }
6409
6410 int main(int argc, char *argv[])
6411 {
6412   FILE *fout, *fasm, *frlist;
6413   struct parsed_data *pd = NULL;
6414   int pd_alloc = 0;
6415   char **rlist = NULL;
6416   int rlist_len = 0;
6417   int rlist_alloc = 0;
6418   int func_chunks_used = 0;
6419   int func_chunks_sorted = 0;
6420   int func_chunk_i = -1;
6421   long func_chunk_ret = 0;
6422   int func_chunk_ret_ln = 0;
6423   int scanned_ahead = 0;
6424   char line[256];
6425   char words[20][256];
6426   enum opr_lenmod lmod;
6427   char *sctproto = NULL;
6428   int in_func = 0;
6429   int pending_endp = 0;
6430   int skip_func = 0;
6431   int skip_warned = 0;
6432   int eq_alloc;
6433   int verbose = 0;
6434   int multi_seg = 0;
6435   int end = 0;
6436   int arg_out;
6437   int arg;
6438   int pi = 0;
6439   int i, j;
6440   int ret, len;
6441   char *p;
6442   int wordc;
6443
6444   for (arg = 1; arg < argc; arg++) {
6445     if (IS(argv[arg], "-v"))
6446       verbose = 1;
6447     else if (IS(argv[arg], "-rf"))
6448       g_allow_regfunc = 1;
6449     else if (IS(argv[arg], "-m"))
6450       multi_seg = 1;
6451     else if (IS(argv[arg], "-hdr"))
6452       g_header_mode = g_quiet_pp = g_allow_regfunc = 1;
6453     else
6454       break;
6455   }
6456
6457   if (argc < arg + 3) {
6458     printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdrf> [rlist]*\n"
6459            "%s -hdr <out.h> <.asm> <seed.h> [rlist]*\n",
6460       argv[0], argv[0]);
6461     return 1;
6462   }
6463
6464   arg_out = arg++;
6465
6466   asmfn = argv[arg++];
6467   fasm = fopen(asmfn, "r");
6468   my_assert_not(fasm, NULL);
6469
6470   hdrfn = argv[arg++];
6471   g_fhdr = fopen(hdrfn, "r");
6472   my_assert_not(g_fhdr, NULL);
6473
6474   rlist_alloc = 64;
6475   rlist = malloc(rlist_alloc * sizeof(rlist[0]));
6476   my_assert_not(rlist, NULL);
6477   // needs special handling..
6478   rlist[rlist_len++] = "__alloca_probe";
6479
6480   func_chunk_alloc = 32;
6481   func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
6482   my_assert_not(func_chunks, NULL);
6483
6484   memset(words, 0, sizeof(words));
6485
6486   for (; arg < argc; arg++) {
6487     frlist = fopen(argv[arg], "r");
6488     my_assert_not(frlist, NULL);
6489
6490     while (my_fgets(line, sizeof(line), frlist)) {
6491       p = sskip(line);
6492       if (*p == 0 || *p == ';')
6493         continue;
6494       if (*p == '#') {
6495         if (IS_START(p, "#if 0")
6496          || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
6497         {
6498           skip_func = 1;
6499         }
6500         else if (IS_START(p, "#endif"))
6501           skip_func = 0;
6502         continue;
6503       }
6504       if (skip_func)
6505         continue;
6506
6507       p = next_word(words[0], sizeof(words[0]), p);
6508       if (words[0][0] == 0)
6509         continue;
6510
6511       if (rlist_len >= rlist_alloc) {
6512         rlist_alloc = rlist_alloc * 2 + 64;
6513         rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
6514         my_assert_not(rlist, NULL);
6515       }
6516       rlist[rlist_len++] = strdup(words[0]);
6517     }
6518     skip_func = 0;
6519
6520     fclose(frlist);
6521     frlist = NULL;
6522   }
6523
6524   if (rlist_len > 0)
6525     qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
6526
6527   fout = fopen(argv[arg_out], "w");
6528   my_assert_not(fout, NULL);
6529
6530   eq_alloc = 128;
6531   g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
6532   my_assert_not(g_eqs, NULL);
6533
6534   for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
6535     g_label_refs[i].i = -1;
6536     g_label_refs[i].next = NULL;
6537   }
6538
6539   if (g_header_mode)
6540     scan_variables(fasm);
6541
6542   while (my_fgets(line, sizeof(line), fasm))
6543   {
6544     wordc = 0;
6545     asmln++;
6546
6547     p = sskip(line);
6548     if (*p == 0)
6549       continue;
6550
6551     // get rid of random tabs
6552     for (i = 0; line[i] != 0; i++)
6553       if (line[i] == '\t')
6554         line[i] = ' ';
6555
6556     if (*p == ';')
6557     {
6558       if (p[2] == '=' && IS_START(p, "; =============== S U B"))
6559         goto do_pending_endp; // eww..
6560
6561       if (p[2] == 'A' && IS_START(p, "; Attributes:"))
6562       {
6563         static const char *attrs[] = {
6564           "bp-based frame",
6565           "library function",
6566           "static",
6567           "noreturn",
6568           "thunk",
6569           "fpd=",
6570         };
6571
6572         // parse IDA's attribute-list comment
6573         g_ida_func_attr = 0;
6574         p = sskip(p + 13);
6575
6576         for (; *p != 0; p = sskip(p)) {
6577           for (i = 0; i < ARRAY_SIZE(attrs); i++) {
6578             if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
6579               g_ida_func_attr |= 1 << i;
6580               p += strlen(attrs[i]);
6581               break;
6582             }
6583           }
6584           if (i == ARRAY_SIZE(attrs)) {
6585             anote("unparsed IDA attr: %s\n", p);
6586             break;
6587           }
6588           if (IS(attrs[i], "fpd=")) {
6589             p = next_word(words[0], sizeof(words[0]), p);
6590             // ignore for now..
6591           }
6592         }
6593       }
6594       else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6595       {
6596         p += 30;
6597         next_word(words[0], sizeof(words[0]), p);
6598         if (words[0][0] == 0)
6599           aerr("missing name for func chunk?\n");
6600
6601         if (!scanned_ahead) {
6602           add_func_chunk(fasm, words[0], asmln);
6603           func_chunks_sorted = 0;
6604         }
6605       }
6606       else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
6607       {
6608         if (func_chunk_i >= 0) {
6609           if (func_chunk_i < func_chunk_cnt
6610             && IS(func_chunks[func_chunk_i].name, g_func))
6611           {
6612             // move on to next chunk
6613             ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
6614             if (ret)
6615               aerr("seek failed for '%s' chunk #%d\n",
6616                 g_func, func_chunk_i);
6617             asmln = func_chunks[func_chunk_i].asmln;
6618             func_chunk_i++;
6619           }
6620           else {
6621             if (func_chunk_ret == 0)
6622               aerr("no return from chunk?\n");
6623             fseek(fasm, func_chunk_ret, SEEK_SET);
6624             asmln = func_chunk_ret_ln;
6625             func_chunk_ret = 0;
6626             pending_endp = 1;
6627           }
6628         }
6629       }
6630       else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
6631         func_chunks_used = 1;
6632         p += 20;
6633         if (IS_START(g_func, "sub_")) {
6634           unsigned long addr = strtoul(p, NULL, 16);
6635           unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
6636           if (addr > f_addr && !scanned_ahead) {
6637             anote("scan_ahead caused by '%s', addr %lx\n",
6638               g_func, addr);
6639             scan_ahead(fasm);
6640             scanned_ahead = 1;
6641             func_chunks_sorted = 0;
6642           }
6643         }
6644       }
6645       continue;
6646     } // *p == ';'
6647
6648 parse_words:
6649     for (i = wordc; i < ARRAY_SIZE(words); i++)
6650       words[i][0] = 0;
6651     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6652       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6653       if (*p == 0 || *p == ';') {
6654         wordc++;
6655         break;
6656       }
6657     }
6658     if (*p != 0 && *p != ';')
6659       aerr("too many words\n");
6660
6661     // alow asm patches in comments
6662     if (*p == ';') {
6663       if (IS_START(p, "; sctpatch:")) {
6664         p = sskip(p + 11);
6665         if (*p == 0 || *p == ';')
6666           continue;
6667         goto parse_words; // lame
6668       }
6669       if (IS_START(p, "; sctproto:")) {
6670         sctproto = strdup(p + 11);
6671       }
6672       else if (IS_START(p, "; sctend")) {
6673         end = 1;
6674         if (!pending_endp)
6675           break;
6676       }
6677     }
6678
6679     if (wordc == 0) {
6680       // shouldn't happen
6681       awarn("wordc == 0?\n");
6682       continue;
6683     }
6684
6685     // don't care about this:
6686     if (words[0][0] == '.'
6687         || IS(words[0], "include")
6688         || IS(words[0], "assume") || IS(words[1], "segment")
6689         || IS(words[0], "align"))
6690     {
6691       continue;
6692     }
6693
6694 do_pending_endp:
6695     // do delayed endp processing to collect switch jumptables
6696     if (pending_endp) {
6697       if (in_func && !skip_func && !end && wordc >= 2
6698           && ((words[0][0] == 'd' && words[0][2] == 0)
6699               || (words[1][0] == 'd' && words[1][2] == 0)))
6700       {
6701         i = 1;
6702         if (words[1][0] == 'd' && words[1][2] == 0) {
6703           // label
6704           if (g_func_pd_cnt >= pd_alloc) {
6705             pd_alloc = pd_alloc * 2 + 16;
6706             g_func_pd = realloc(g_func_pd,
6707               sizeof(g_func_pd[0]) * pd_alloc);
6708             my_assert_not(g_func_pd, NULL);
6709           }
6710           pd = &g_func_pd[g_func_pd_cnt];
6711           g_func_pd_cnt++;
6712           memset(pd, 0, sizeof(*pd));
6713           strcpy(pd->label, words[0]);
6714           pd->type = OPT_CONST;
6715           pd->lmod = lmod_from_directive(words[1]);
6716           i = 2;
6717         }
6718         else {
6719           if (pd == NULL) {
6720             if (verbose)
6721               anote("skipping alignment byte?\n");
6722             continue;
6723           }
6724           lmod = lmod_from_directive(words[0]);
6725           if (lmod != pd->lmod)
6726             aerr("lmod change? %d->%d\n", pd->lmod, lmod);
6727         }
6728
6729         if (pd->count_alloc < pd->count + wordc) {
6730           pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
6731           pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
6732           my_assert_not(pd->d, NULL);
6733         }
6734         for (; i < wordc; i++) {
6735           if (IS(words[i], "offset")) {
6736             pd->type = OPT_OFFSET;
6737             i++;
6738           }
6739           p = strchr(words[i], ',');
6740           if (p != NULL)
6741             *p = 0;
6742           if (pd->type == OPT_OFFSET)
6743             pd->d[pd->count].u.label = strdup(words[i]);
6744           else
6745             pd->d[pd->count].u.val = parse_number(words[i]);
6746           pd->d[pd->count].bt_i = -1;
6747           pd->count++;
6748         }
6749         continue;
6750       }
6751
6752       if (in_func && !skip_func) {
6753         if (g_header_mode)
6754           gen_hdr(g_func, pi);
6755         else
6756           gen_func(fout, g_fhdr, g_func, pi);
6757       }
6758
6759       pending_endp = 0;
6760       in_func = 0;
6761       g_ida_func_attr = 0;
6762       skip_warned = 0;
6763       skip_func = 0;
6764       g_func[0] = 0;
6765       func_chunks_used = 0;
6766       func_chunk_i = -1;
6767       if (pi != 0) {
6768         memset(&ops, 0, pi * sizeof(ops[0]));
6769         clear_labels(pi);
6770         pi = 0;
6771       }
6772       g_eqcnt = 0;
6773       for (i = 0; i < g_func_pd_cnt; i++) {
6774         pd = &g_func_pd[i];
6775         if (pd->type == OPT_OFFSET) {
6776           for (j = 0; j < pd->count; j++)
6777             free(pd->d[j].u.label);
6778         }
6779         free(pd->d);
6780         pd->d = NULL;
6781       }
6782       g_func_pd_cnt = 0;
6783       pd = NULL;
6784
6785       if (end)
6786         break;
6787       if (wordc == 0)
6788         continue;
6789     }
6790
6791     if (IS(words[1], "proc")) {
6792       if (in_func)
6793         aerr("proc '%s' while in_func '%s'?\n",
6794           words[0], g_func);
6795       p = words[0];
6796       if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
6797         skip_func = 1;
6798       strcpy(g_func, words[0]);
6799       set_label(0, words[0]);
6800       in_func = 1;
6801       continue;
6802     }
6803
6804     if (IS(words[1], "endp"))
6805     {
6806       if (!in_func)
6807         aerr("endp '%s' while not in_func?\n", words[0]);
6808       if (!IS(g_func, words[0]))
6809         aerr("endp '%s' while in_func '%s'?\n",
6810           words[0], g_func);
6811
6812       if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
6813         && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
6814       {
6815         // import jump
6816         skip_func = 1;
6817       }
6818
6819       if (!skip_func && func_chunks_used) {
6820         // start processing chunks
6821         struct chunk_item *ci, key = { g_func, 0 };
6822
6823         func_chunk_ret = ftell(fasm);
6824         func_chunk_ret_ln = asmln;
6825         if (!func_chunks_sorted) {
6826           qsort(func_chunks, func_chunk_cnt,
6827             sizeof(func_chunks[0]), cmp_chunks);
6828           func_chunks_sorted = 1;
6829         }
6830         ci = bsearch(&key, func_chunks, func_chunk_cnt,
6831                sizeof(func_chunks[0]), cmp_chunks);
6832         if (ci == NULL)
6833           aerr("'%s' needs chunks, but none found\n", g_func);
6834         func_chunk_i = ci - func_chunks;
6835         for (; func_chunk_i > 0; func_chunk_i--)
6836           if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
6837             break;
6838
6839         ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
6840         if (ret)
6841           aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
6842         asmln = func_chunks[func_chunk_i].asmln;
6843         func_chunk_i++;
6844         continue;
6845       }
6846       pending_endp = 1;
6847       continue;
6848     }
6849
6850     if (wordc == 2 && IS(words[1], "ends")) {
6851       if (!multi_seg) {
6852         end = 1;
6853         if (pending_endp)
6854           goto do_pending_endp;
6855         break;
6856       }
6857
6858       // scan for next text segment
6859       while (my_fgets(line, sizeof(line), fasm)) {
6860         asmln++;
6861         p = sskip(line);
6862         if (*p == 0 || *p == ';')
6863           continue;
6864
6865         if (strstr(p, "segment para public 'CODE' use32"))
6866           break;
6867       }
6868
6869       continue;
6870     }
6871
6872     p = strchr(words[0], ':');
6873     if (p != NULL) {
6874       set_label(pi, words[0]);
6875       continue;
6876     }
6877
6878     if (!in_func || skip_func) {
6879       if (!skip_warned && !skip_func && g_labels[pi] != NULL) {
6880         if (verbose)
6881           anote("skipping from '%s'\n", g_labels[pi]);
6882         skip_warned = 1;
6883       }
6884       free(g_labels[pi]);
6885       g_labels[pi] = NULL;
6886       continue;
6887     }
6888
6889     if (wordc > 1 && IS(words[1], "="))
6890     {
6891       if (wordc != 5)
6892         aerr("unhandled equ, wc=%d\n", wordc);
6893       if (g_eqcnt >= eq_alloc) {
6894         eq_alloc *= 2;
6895         g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
6896         my_assert_not(g_eqs, NULL);
6897       }
6898
6899       len = strlen(words[0]);
6900       if (len > sizeof(g_eqs[0].name) - 1)
6901         aerr("equ name too long: %d\n", len);
6902       strcpy(g_eqs[g_eqcnt].name, words[0]);
6903
6904       if (!IS(words[3], "ptr"))
6905         aerr("unhandled equ\n");
6906       if (IS(words[2], "dword"))
6907         g_eqs[g_eqcnt].lmod = OPLM_DWORD;
6908       else if (IS(words[2], "word"))
6909         g_eqs[g_eqcnt].lmod = OPLM_WORD;
6910       else if (IS(words[2], "byte"))
6911         g_eqs[g_eqcnt].lmod = OPLM_BYTE;
6912       else if (IS(words[2], "qword"))
6913         g_eqs[g_eqcnt].lmod = OPLM_QWORD;
6914       else
6915         aerr("bad lmod: '%s'\n", words[2]);
6916
6917       g_eqs[g_eqcnt].offset = parse_number(words[4]);
6918       g_eqcnt++;
6919       continue;
6920     }
6921
6922     if (pi >= ARRAY_SIZE(ops))
6923       aerr("too many ops\n");
6924
6925     parse_op(&ops[pi], words, wordc);
6926
6927     if (sctproto != NULL) {
6928       if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
6929         ops[pi].datap = sctproto;
6930       sctproto = NULL;
6931     }
6932     pi++;
6933   }
6934
6935   if (g_header_mode)
6936     output_hdr(fout);
6937
6938   fclose(fout);
6939   fclose(fasm);
6940   fclose(g_fhdr);
6941
6942   return 0;
6943 }
6944
6945 // vim:ts=2:shiftwidth=2:expandtab