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