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