fixes, standalone version builds
[ia32rtools.git] / tools / translate.c
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6 #include "my_assert.h"
7 #include "my_str.h"
8
9 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
10 #define IS(w, y) !strcmp(w, y)
11 #define IS_START(w, y) !strncmp(w, y, strlen(y))
12
13 #include "protoparse.h"
14
15 static const char *asmfn;
16 static int asmln;
17 static FILE *g_fhdr;
18
19 #define anote(fmt, ...) \
20         printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
21 #define awarn(fmt, ...) \
22         printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
23 #define aerr(fmt, ...) do { \
24         printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
25   fcloseall(); \
26         exit(1); \
27 } while (0)
28
29 #include "masm_tools.h"
30
31 enum op_flags {
32   OPF_RMD    = (1 << 0), /* removed or optimized out */
33   OPF_DATA   = (1 << 1), /* data processing - writes to dst opr */
34   OPF_FLAGS  = (1 << 2), /* sets flags */
35   OPF_JMP    = (1 << 3), /* branches, ret and call */
36   OPF_CC     = (1 << 4), /* uses flags */
37   OPF_TAIL   = (1 << 5), /* ret or tail call */
38   OPF_RSAVE  = (1 << 6), /* push/pop is local reg save/load */
39   OPF_REP    = (1 << 7), /* prefixed by rep */
40   OPF_REPZ   = (1 << 8), /* rep is repe/repz */
41   OPF_REPNZ  = (1 << 9), /* rep is repne/repnz */
42   OPF_FARG   = (1 << 10), /* push collected as func arg (no reuse) */
43   OPF_EBP_S  = (1 << 11), /* ebp used as scratch here, not BP */
44 };
45
46 enum op_op {
47         OP_INVAL,
48         OP_NOP,
49         OP_PUSH,
50         OP_POP,
51         OP_MOV,
52         OP_LEA,
53         OP_MOVZX,
54         OP_MOVSX,
55         OP_NOT,
56         OP_CDQ,
57         OP_STOS,
58         OP_MOVS,
59         OP_CMPS,
60         OP_RET,
61         OP_ADD,
62         OP_SUB,
63         OP_AND,
64         OP_OR,
65         OP_XOR,
66         OP_SHL,
67         OP_SHR,
68         OP_SAR,
69         OP_ROL,
70         OP_ROR,
71         OP_ADC,
72         OP_SBB,
73         OP_INC,
74         OP_DEC,
75         OP_NEG,
76         OP_MUL,
77         OP_IMUL,
78         OP_DIV,
79         OP_IDIV,
80         OP_TEST,
81         OP_CMP,
82         OP_CALL,
83         OP_JMP,
84         OP_JO,
85         OP_JNO,
86         OP_JC,
87         OP_JNC,
88         OP_JZ,
89         OP_JNZ,
90         OP_JBE,
91         OP_JA,
92         OP_JS,
93         OP_JNS,
94         OP_JP,
95         OP_JNP,
96         OP_JL,
97         OP_JGE,
98         OP_JLE,
99         OP_JG,
100 };
101
102 enum opr_type {
103   OPT_UNSPEC,
104   OPT_REG,
105   OPT_REGMEM,
106   OPT_LABEL,
107   OPT_OFFSET,
108   OPT_CONST,
109 };
110
111 // must be sorted (larger len must be further in enum)
112 enum opr_lenmod {
113         OPLM_UNSPEC,
114         OPLM_BYTE,
115         OPLM_WORD,
116         OPLM_DWORD,
117 };
118
119 #define MAX_OPERANDS 3
120
121 struct parsed_opr {
122   enum opr_type type;
123   enum opr_lenmod lmod;
124   unsigned int is_ptr:1;   // pointer in C
125   unsigned int is_array:1; // array in C
126   unsigned int type_from_var:1; // .. in header, sometimes wrong
127   unsigned int size_mismatch:1; // type override differs from C
128   unsigned int size_lt:1;  // type override is larger than C
129   unsigned int had_ds:1;   // had ds: prefix
130   int reg;
131   unsigned int val;
132   char name[256];
133 };
134
135 struct parsed_op {
136   enum op_op op;
137   struct parsed_opr operand[MAX_OPERANDS];
138   unsigned int flags;
139   int operand_cnt;
140   int regmask_src;        // all referensed regs
141   int regmask_dst;
142   int pfomask;            // flagop: parsed_flag_op that can't be delayed
143   int argnum;             // push: altered before call arg #
144   int cc_scratch;         // scratch storage during analysis
145   int bt_i;               // branch target for branches
146   struct parsed_data *btj;// branch targets for jumptables
147   void *datap;
148 };
149
150 // datap:
151 // OP_CALL - parser proto hint (str), ptr to struct parsed_proto
152 // (OPF_CC) - point to one of (OPF_FLAGS) that affects cc op
153
154 struct parsed_equ {
155   char name[64];
156   enum opr_lenmod lmod;
157   int offset;
158 };
159
160 struct parsed_data {
161   char label[256];
162   enum opr_type type;
163   enum opr_lenmod lmod;
164   int count;
165   int count_alloc;
166   struct {
167     union {
168       char *label;
169       unsigned int val;
170     } u;
171     int bt_i;
172   } *d;
173 };
174
175 struct label_ref {
176   int i;
177   struct label_ref *next;
178 };
179
180 enum ida_func_attr {
181   IDAFA_BP_FRAME = (1 << 0),
182   IDAFA_LIB_FUNC = (1 << 1),
183   IDAFA_STATIC   = (1 << 2),
184   IDAFA_NORETURN = (1 << 3),
185   IDAFA_THUNK    = (1 << 4),
186   IDAFA_FPD      = (1 << 5),
187 };
188
189 #define MAX_OPS 4096
190
191 static struct parsed_op ops[MAX_OPS];
192 static struct parsed_equ *g_eqs;
193 static int g_eqcnt;
194 static char g_labels[MAX_OPS][32];
195 static struct label_ref g_label_refs[MAX_OPS];
196 static const struct parsed_proto *g_func_pp;
197 static struct parsed_data *g_func_pd;
198 static int g_func_pd_cnt;
199 static char g_func[256];
200 static char g_comment[256];
201 static int g_bp_frame;
202 static int g_sp_frame;
203 static int g_stack_frame_used;
204 static int g_stack_fsz;
205 static int g_ida_func_attr;
206 static int g_allow_regfunc;
207 #define ferr(op_, fmt, ...) do { \
208   printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
209     dump_op(op_), ##__VA_ARGS__); \
210   fcloseall(); \
211   exit(1); \
212 } while (0)
213 #define fnote(op_, fmt, ...) \
214   printf("error:%s:#%zd: '%s': " fmt, g_func, (op_) - ops, \
215     dump_op(op_), ##__VA_ARGS__)
216
217 #define MAX_REGS 8
218
219 const char *regs_r32[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp" };
220 const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
221 const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
222 const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
223
224 enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
225
226 // possible basic comparison types (without inversion)
227 enum parsed_flag_op {
228   PFO_O,  // 0 OF=1
229   PFO_C,  // 2 CF=1
230   PFO_Z,  // 4 ZF=1
231   PFO_BE, // 6 CF=1||ZF=1
232   PFO_S,  // 8 SF=1
233   PFO_P,  // a PF=1
234   PFO_L,  // c SF!=OF
235   PFO_LE, // e ZF=1||SF!=OF
236 };
237
238 static const char *parsed_flag_op_names[] = {
239   "o", "c", "z", "be", "s", "p", "l", "le"
240 };
241
242 static int char_array_i(const char *array[], size_t len, const char *s)
243 {
244   int i;
245
246   for (i = 0; i < len; i++)
247     if (IS(s, array[i]))
248       return i;
249
250   return -1;
251 }
252
253 static void printf_number(char *buf, size_t buf_size,
254   unsigned long number)
255 {
256   // output in C-friendly form
257   snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
258 }
259
260 static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
261 {
262   int reg;
263
264   reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
265   if (reg >= 0) {
266     *reg_lmod = OPLM_DWORD;
267     return reg;
268   }
269   reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
270   if (reg >= 0) {
271     *reg_lmod = OPLM_WORD;
272     return reg;
273   }
274   reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
275   if (reg >= 0) {
276     *reg_lmod = OPLM_BYTE;
277     return reg;
278   }
279   reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
280   if (reg >= 0) {
281     *reg_lmod = OPLM_BYTE;
282     return reg;
283   }
284
285   return -1;
286 }
287
288 static int parse_indmode(char *name, int *regmask, int need_c_cvt)
289 {
290   enum opr_lenmod lmod;
291   char cvtbuf[256];
292   char *d = cvtbuf;
293   char *s = name;
294   char w[64];
295   long number;
296   int reg;
297   int c = 0;
298
299   *d = 0;
300
301   while (*s != 0) {
302     d += strlen(d);
303     while (my_isblank(*s))
304       s++;
305     for (; my_issep(*s); d++, s++)
306       *d = *s;
307     while (my_isblank(*s))
308       s++;
309     *d = 0;
310
311     // skip 'ds:' prefix
312     if (IS_START(s, "ds:"))
313       s += 3;
314
315     s = next_idt(w, sizeof(w), s);
316     if (w[0] == 0)
317       break;
318     c++;
319
320     reg = parse_reg(&lmod, w);
321     if (reg >= 0) {
322       *regmask |= 1 << reg;
323       goto pass;
324     }
325
326     if ('0' <= w[0] && w[0] <= '9') {
327       number = parse_number(w);
328       printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
329       continue;
330     }
331
332     // probably some label/identifier - pass
333
334 pass:
335     snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
336   }
337
338   if (need_c_cvt)
339     strcpy(name, cvtbuf);
340
341   return c;
342 }
343
344 static int is_reg_in_str(const char *s)
345 {
346   int i;
347
348   if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
349     return 0;
350
351   for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
352     if (!strncmp(s, regs_r32[i], 3))
353       return 1;
354
355   return 0;
356 }
357
358 static const char *parse_stack_el(const char *name, char *extra_reg)
359 {
360   const char *p, *p2, *s;
361   char *endp = NULL;
362   char buf[32];
363   long val;
364   int len;
365
366   p = name;
367   if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
368     p += 4;
369     if (extra_reg != NULL) {
370       strncpy(extra_reg, name, 3);
371       extra_reg[4] = 0;
372     }
373   }
374
375   if (IS_START(p, "ebp+")) {
376     p += 4;
377
378     p2 = strchr(p, '+');
379     if (p2 != NULL && is_reg_in_str(p)) {
380       if (extra_reg != NULL) {
381         strncpy(extra_reg, p, p2 - p);
382         extra_reg[p2 - p] = 0;
383       }
384       p = p2 + 1;
385     }
386
387     if (!('0' <= *p && *p <= '9'))
388       return p;
389
390     return NULL;
391   }
392
393   if (!IS_START(name, "esp+"))
394     return NULL;
395
396   p = strchr(name + 4, '+');
397   if (p) {
398     // must be a number after esp+, already converted to 0x..
399     s = name + 4;
400     if (!('0' <= *s && *s <= '9')) {
401                   aerr("%s nan?\n", __func__);
402       return NULL;
403     }
404     if (s[0] == '0' && s[1] == 'x')
405       s += 2;
406     len = p - s;
407     if (len < sizeof(buf) - 1) {
408       strncpy(buf, s, len);
409       buf[len] = 0;
410       val = strtol(buf, &endp, 16);
411       if (val == 0 || *endp != 0) {
412         aerr("%s num parse fail for '%s'\n", __func__, buf);
413         return NULL;
414       }
415     }
416     p++;
417   }
418   else
419     p = name + 4;
420
421   if ('0' <= *p && *p <= '9')
422     return NULL;
423
424   return p;
425 }
426
427 static int guess_lmod_from_name(struct parsed_opr *opr)
428 {
429   if (!strncmp(opr->name, "dword_", 6)) {
430     opr->lmod = OPLM_DWORD;
431     return 1;
432   }
433   if (!strncmp(opr->name, "word_", 5)) {
434     opr->lmod = OPLM_WORD;
435     return 1;
436   }
437   if (!strncmp(opr->name, "byte_", 5)) {
438     opr->lmod = OPLM_BYTE;
439     return 1;
440   }
441   return 0;
442 }
443
444 static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
445   const struct parsed_type *c_type)
446 {
447   static const char *dword_types[] = {
448     "int", "_DWORD", "UINT_PTR", "DWORD",
449     "WPARAM", "LPARAM", "UINT",
450     "HIMC",
451   };
452   static const char *word_types[] = {
453     "uint16_t", "int16_t", "_WORD",
454     "unsigned __int16", "__int16",
455   };
456   static const char *byte_types[] = {
457     "uint8_t", "int8_t", "char",
458     "unsigned __int8", "__int8", "BYTE", "_BYTE",
459     "_UNKNOWN",
460   };
461   const char *n;
462   int i;
463
464   if (c_type->is_ptr) {
465     *lmod = OPLM_DWORD;
466     return 1;
467   }
468
469   n = skip_type_mod(c_type->name);
470
471   for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
472     if (IS(n, dword_types[i])) {
473       *lmod = OPLM_DWORD;
474       return 1;
475     }
476   }
477
478   for (i = 0; i < ARRAY_SIZE(word_types); i++) {
479     if (IS(n, word_types[i])) {
480       *lmod = OPLM_WORD;
481       return 1;
482     }
483   }
484
485   for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
486     if (IS(n, byte_types[i])) {
487       *lmod = OPLM_BYTE;
488       return 1;
489     }
490   }
491
492   return 0;
493 }
494
495 static enum opr_type lmod_from_directive(const char *d)
496 {
497   if (IS(d, "dd"))
498     return OPLM_DWORD;
499   else if (IS(d, "dw"))
500     return OPLM_WORD;
501   else if (IS(d, "db"))
502     return OPLM_BYTE;
503
504   aerr("unhandled directive: '%s'\n", d);
505   return OPLM_UNSPEC;
506 }
507
508 static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
509   int *regmask)
510 {
511   opr->type = OPT_REG;
512   opr->reg = reg;
513   opr->lmod = lmod;
514   *regmask |= 1 << reg;
515 }
516
517 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
518   int *extra_offs);
519
520 static int parse_operand(struct parsed_opr *opr,
521   int *regmask, int *regmask_indirect,
522   char words[16][256], int wordc, int w, unsigned int op_flags)
523 {
524   const struct parsed_proto *pp;
525   enum opr_lenmod tmplmod;
526   unsigned long number;
527   char buf[256];
528   int ret, len;
529   int wordc_in;
530   char *p;
531   int i;
532
533   if (w >= wordc)
534     aerr("parse_operand w %d, wordc %d\n", w, wordc);
535
536   opr->reg = xUNSPEC;
537
538   for (i = w; i < wordc; i++) {
539     len = strlen(words[i]);
540     if (words[i][len - 1] == ',') {
541       words[i][len - 1] = 0;
542       wordc = i + 1;
543       break;
544     }
545   }
546
547   wordc_in = wordc - w;
548
549   if ((op_flags & OPF_JMP) && wordc_in > 0
550       && !('0' <= words[w][0] && words[w][0] <= '9'))
551   {
552     const char *label = NULL;
553
554     if (wordc_in == 3 && !strncmp(words[w], "near", 4)
555      && IS(words[w + 1], "ptr"))
556       label = words[w + 2];
557     else if (wordc_in == 2 && IS(words[w], "short"))
558       label = words[w + 1];
559     else if (wordc_in == 1
560           && strchr(words[w], '[') == NULL
561           && parse_reg(&tmplmod, words[w]) < 0)
562       label = words[w];
563
564     if (label != NULL) {
565       opr->type = OPT_LABEL;
566       if (IS_START(label, "ds:")) {
567         opr->had_ds = 1;
568         label += 3;
569       }
570       strcpy(opr->name, label);
571       return wordc;
572     }
573   }
574
575   if (wordc_in >= 3) {
576     if (IS(words[w + 1], "ptr")) {
577       if (IS(words[w], "dword"))
578         opr->lmod = OPLM_DWORD;
579       else if (IS(words[w], "word"))
580         opr->lmod = OPLM_WORD;
581       else if (IS(words[w], "byte"))
582         opr->lmod = OPLM_BYTE;
583       else
584         aerr("type parsing failed\n");
585       w += 2;
586       wordc_in = wordc - w;
587     }
588   }
589
590   if (wordc_in == 2) {
591     if (IS(words[w], "offset")) {
592       opr->type = OPT_OFFSET;
593       strcpy(opr->name, words[w + 1]);
594       return wordc;
595     }
596     if (IS(words[w], "(offset")) {
597       p = strchr(words[w + 1], ')');
598       if (p == NULL)
599         aerr("parse of bracketed offset failed\n");
600       *p = 0;
601       opr->type = OPT_OFFSET;
602       strcpy(opr->name, words[w + 1]);
603       return wordc;
604     }
605   }
606
607   if (wordc_in != 1)
608     aerr("parse_operand 1 word expected\n");
609
610   if (IS_START(words[w], "ds:")) {
611     opr->had_ds = 1;
612     memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
613   }
614   strcpy(opr->name, words[w]);
615
616   if (words[w][0] == '[') {
617     opr->type = OPT_REGMEM;
618     ret = sscanf(words[w], "[%[^]]]", opr->name);
619     if (ret != 1)
620       aerr("[] parse failure\n");
621
622     parse_indmode(opr->name, regmask_indirect, 1);
623     if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL)) {
624       // might be an equ
625       struct parsed_equ *eq =
626         equ_find(NULL, parse_stack_el(opr->name, NULL), &i);
627       if (eq)
628         opr->lmod = eq->lmod;
629     }
630     return wordc;
631   }
632   else if (strchr(words[w], '[')) {
633     // label[reg] form
634     p = strchr(words[w], '[');
635     opr->type = OPT_REGMEM;
636     parse_indmode(p, regmask_indirect, 0);
637     strncpy(buf, words[w], p - words[w]);
638     buf[p - words[w]] = 0;
639     pp = proto_parse(g_fhdr, buf, 1);
640     goto do_label;
641   }
642   else if (('0' <= words[w][0] && words[w][0] <= '9')
643     || words[w][0] == '-')
644   {
645     number = parse_number(words[w]);
646     opr->type = OPT_CONST;
647     opr->val = number;
648     printf_number(opr->name, sizeof(opr->name), number);
649     return wordc;
650   }
651
652   ret = parse_reg(&tmplmod, opr->name);
653   if (ret >= 0) {
654     setup_reg_opr(opr, ret, tmplmod, regmask);
655     return wordc;
656   }
657
658   // most likely var in data segment
659   opr->type = OPT_LABEL;
660   pp = proto_parse(g_fhdr, opr->name, 0);
661
662 do_label:
663   if (pp != NULL) {
664     if (pp->is_fptr || pp->is_func) {
665       opr->lmod = OPLM_DWORD;
666       opr->is_ptr = 1;
667     }
668     else {
669       tmplmod = OPLM_UNSPEC;
670       if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
671         anote("unhandled C type '%s' for '%s'\n",
672           pp->type.name, opr->name);
673       
674       if (opr->lmod == OPLM_UNSPEC) {
675         opr->lmod = tmplmod;
676         opr->type_from_var = 1;
677       }
678       else if (opr->lmod != tmplmod) {
679         opr->size_mismatch = 1;
680         if (tmplmod < opr->lmod)
681           opr->size_lt = 1;
682       }
683       opr->is_ptr = pp->type.is_ptr;
684     }
685     opr->is_array = pp->type.is_array;
686   }
687
688   if (opr->lmod == OPLM_UNSPEC)
689     guess_lmod_from_name(opr);
690   return wordc;
691 }
692
693 static const struct {
694   const char *name;
695   unsigned int flags;
696 } pref_table[] = {
697   { "rep",    OPF_REP },
698   { "repe",   OPF_REP|OPF_REPZ },
699   { "repz",   OPF_REP|OPF_REPZ },
700   { "repne",  OPF_REP|OPF_REPNZ },
701   { "repnz",  OPF_REP|OPF_REPNZ },
702 };
703
704 static const struct {
705   const char *name;
706   enum op_op op;
707   unsigned int minopr;
708   unsigned int maxopr;
709   unsigned int flags;
710 } op_table[] = {
711   { "nop",  OP_NOP,    0, 0, 0 },
712   { "push", OP_PUSH,   1, 1, 0 },
713   { "pop",  OP_POP,    1, 1, OPF_DATA },
714   { "mov" , OP_MOV,    2, 2, OPF_DATA },
715   { "lea",  OP_LEA,    2, 2, OPF_DATA },
716   { "movzx",OP_MOVZX,  2, 2, OPF_DATA },
717   { "movsx",OP_MOVSX,  2, 2, OPF_DATA },
718   { "not",  OP_NOT,    1, 1, OPF_DATA },
719   { "cdq",  OP_CDQ,    0, 0, OPF_DATA },
720   { "stosb",OP_STOS,   0, 0, OPF_DATA },
721   { "stosw",OP_STOS,   0, 0, OPF_DATA },
722   { "stosd",OP_STOS,   0, 0, OPF_DATA },
723   { "movsb",OP_MOVS,   0, 0, OPF_DATA },
724   { "movsw",OP_MOVS,   0, 0, OPF_DATA },
725   { "movsd",OP_MOVS,   0, 0, OPF_DATA },
726   { "cmpsb",OP_CMPS,   0, 0, OPF_DATA|OPF_FLAGS },
727   { "cmpsw",OP_CMPS,   0, 0, OPF_DATA|OPF_FLAGS },
728   { "cmpsd",OP_CMPS,   0, 0, OPF_DATA|OPF_FLAGS },
729   { "add",  OP_ADD,    2, 2, OPF_DATA|OPF_FLAGS },
730   { "sub",  OP_SUB,    2, 2, OPF_DATA|OPF_FLAGS },
731   { "and",  OP_AND,    2, 2, OPF_DATA|OPF_FLAGS },
732   { "or",   OP_OR,     2, 2, OPF_DATA|OPF_FLAGS },
733   { "xor",  OP_XOR,    2, 2, OPF_DATA|OPF_FLAGS },
734   { "shl",  OP_SHL,    2, 2, OPF_DATA|OPF_FLAGS },
735   { "shr",  OP_SHR,    2, 2, OPF_DATA|OPF_FLAGS },
736   { "sal",  OP_SHL,    2, 2, OPF_DATA|OPF_FLAGS },
737   { "sar",  OP_SAR,    2, 2, OPF_DATA|OPF_FLAGS },
738   { "rol",  OP_ROL,    2, 2, OPF_DATA|OPF_FLAGS },
739   { "ror",  OP_ROR,    2, 2, OPF_DATA|OPF_FLAGS },
740   { "adc",  OP_ADC,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
741   { "sbb",  OP_SBB,    2, 2, OPF_DATA|OPF_FLAGS|OPF_CC },
742   { "inc",  OP_INC,    1, 1, OPF_DATA|OPF_FLAGS },
743   { "dec",  OP_DEC,    1, 1, OPF_DATA|OPF_FLAGS },
744   { "neg",  OP_NEG,    1, 1, OPF_DATA|OPF_FLAGS },
745   { "mul",  OP_MUL,    1, 1, OPF_DATA|OPF_FLAGS },
746   { "imul", OP_IMUL,   1, 3, OPF_DATA|OPF_FLAGS },
747   { "div",  OP_DIV,    1, 1, OPF_DATA|OPF_FLAGS },
748   { "idiv", OP_IDIV,   1, 1, OPF_DATA|OPF_FLAGS },
749   { "test", OP_TEST,   2, 2, OPF_FLAGS },
750   { "cmp",  OP_CMP,    2, 2, OPF_FLAGS },
751   { "retn", OP_RET,    0, 1, OPF_TAIL },
752   { "call", OP_CALL,   1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
753   { "jmp",  OP_JMP,    1, 1, OPF_JMP },
754   { "jo",   OP_JO,     1, 1, OPF_JMP|OPF_CC }, // 70 OF=1
755   { "jno",  OP_JNO,    1, 1, OPF_JMP|OPF_CC }, // 71 OF=0
756   { "jc",   OP_JC,     1, 1, OPF_JMP|OPF_CC }, // 72 CF=1
757   { "jb",   OP_JC,     1, 1, OPF_JMP|OPF_CC }, // 72
758   { "jnc",  OP_JNC,    1, 1, OPF_JMP|OPF_CC }, // 73 CF=0
759   { "jnb",  OP_JNC,    1, 1, OPF_JMP|OPF_CC }, // 73
760   { "jae",  OP_JNC,    1, 1, OPF_JMP|OPF_CC }, // 73
761   { "jz",   OP_JZ,     1, 1, OPF_JMP|OPF_CC }, // 74 ZF=1
762   { "je",   OP_JZ,     1, 1, OPF_JMP|OPF_CC }, // 74
763   { "jnz",  OP_JNZ,    1, 1, OPF_JMP|OPF_CC }, // 75 ZF=0
764   { "jne",  OP_JNZ,    1, 1, OPF_JMP|OPF_CC }, // 75
765   { "jbe",  OP_JBE,    1, 1, OPF_JMP|OPF_CC }, // 76 CF=1 || ZF=1
766   { "jna",  OP_JBE,    1, 1, OPF_JMP|OPF_CC }, // 76
767   { "ja",   OP_JA,     1, 1, OPF_JMP|OPF_CC }, // 77 CF=0 && ZF=0
768   { "jnbe", OP_JA,     1, 1, OPF_JMP|OPF_CC }, // 77
769   { "js",   OP_JS,     1, 1, OPF_JMP|OPF_CC }, // 78 SF=1
770   { "jns",  OP_JNS,    1, 1, OPF_JMP|OPF_CC }, // 79 SF=0
771   { "jp",   OP_JP,     1, 1, OPF_JMP|OPF_CC }, // 7a PF=1
772   { "jpe",  OP_JP,     1, 1, OPF_JMP|OPF_CC }, // 7a
773   { "jnp",  OP_JNP,    1, 1, OPF_JMP|OPF_CC }, // 7b PF=0
774   { "jpo",  OP_JNP,    1, 1, OPF_JMP|OPF_CC }, // 7b
775   { "jl",   OP_JL,     1, 1, OPF_JMP|OPF_CC }, // 7c SF!=OF
776   { "jnge", OP_JL,     1, 1, OPF_JMP|OPF_CC }, // 7c
777   { "jge",  OP_JGE,    1, 1, OPF_JMP|OPF_CC }, // 7d SF=OF
778   { "jnl",  OP_JGE,    1, 1, OPF_JMP|OPF_CC }, // 7d
779   { "jle",  OP_JLE,    1, 1, OPF_JMP|OPF_CC }, // 7e ZF=1 || SF!=OF
780   { "jng",  OP_JLE,    1, 1, OPF_JMP|OPF_CC }, // 7e
781   { "jg",   OP_JG,     1, 1, OPF_JMP|OPF_CC }, // 7f ZF=0 && SF=OF
782   { "jnle", OP_JG,     1, 1, OPF_JMP|OPF_CC }, // 7f
783   { "seto",   OP_JO,   1, 1, OPF_DATA|OPF_CC },
784   { "setno",  OP_JNO,  1, 1, OPF_DATA|OPF_CC },
785   { "setc",   OP_JC,   1, 1, OPF_DATA|OPF_CC },
786   { "setb",   OP_JC,   1, 1, OPF_DATA|OPF_CC },
787   { "setnc",  OP_JNC,  1, 1, OPF_DATA|OPF_CC },
788   { "setae",  OP_JNC,  1, 1, OPF_DATA|OPF_CC },
789   { "setz",   OP_JZ,   1, 1, OPF_DATA|OPF_CC },
790   { "sete",   OP_JZ,   1, 1, OPF_DATA|OPF_CC },
791   { "setnz",  OP_JNZ,  1, 1, OPF_DATA|OPF_CC },
792   { "setne",  OP_JNZ,  1, 1, OPF_DATA|OPF_CC },
793   { "setbe",  OP_JBE,  1, 1, OPF_DATA|OPF_CC },
794   { "setna",  OP_JBE,  1, 1, OPF_DATA|OPF_CC },
795   { "seta",   OP_JA,   1, 1, OPF_DATA|OPF_CC },
796   { "setnbe", OP_JA,   1, 1, OPF_DATA|OPF_CC },
797   { "sets",   OP_JS,   1, 1, OPF_DATA|OPF_CC },
798   { "setns",  OP_JNS,  1, 1, OPF_DATA|OPF_CC },
799   { "setp",   OP_JP,   1, 1, OPF_DATA|OPF_CC },
800   { "setpe",  OP_JP,   1, 1, OPF_DATA|OPF_CC },
801   { "setnp",  OP_JNP,  1, 1, OPF_DATA|OPF_CC },
802   { "setpo",  OP_JNP,  1, 1, OPF_DATA|OPF_CC },
803   { "setl",   OP_JL,   1, 1, OPF_DATA|OPF_CC },
804   { "setnge", OP_JL,   1, 1, OPF_DATA|OPF_CC },
805   { "setge",  OP_JGE,  1, 1, OPF_DATA|OPF_CC },
806   { "setnl",  OP_JGE,  1, 1, OPF_DATA|OPF_CC },
807   { "setle",  OP_JLE,  1, 1, OPF_DATA|OPF_CC },
808   { "setng",  OP_JLE,  1, 1, OPF_DATA|OPF_CC },
809   { "setg",   OP_JG,   1, 1, OPF_DATA|OPF_CC },
810   { "setnle", OP_JG,   1, 1, OPF_DATA|OPF_CC },
811 };
812
813 static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
814 {
815   enum opr_lenmod lmod = OPLM_UNSPEC;
816   int prefix_flags = 0;
817   int regmask_ind;
818   int regmask;
819   int op_w = 0;
820   int opr = 0;
821   int w = 0;
822   int i;
823
824   for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
825     if (IS(words[w], pref_table[i].name)) {
826       prefix_flags = pref_table[i].flags;
827       break;
828     }
829   }
830
831   if (prefix_flags) {
832     if (wordc <= 1)
833       aerr("lone prefix: '%s'\n", words[0]);
834     w++;
835   }
836
837   op_w = w;
838   for (i = 0; i < ARRAY_SIZE(op_table); i++) {
839     if (IS(words[w], op_table[i].name))
840       break;
841   }
842
843   if (i == ARRAY_SIZE(op_table))
844     aerr("unhandled op: '%s'\n", words[0]);
845   w++;
846
847   op->op = op_table[i].op;
848   op->flags = op_table[i].flags | prefix_flags;
849   op->regmask_src = op->regmask_dst = 0;
850
851   for (opr = 0; opr < op_table[i].minopr; opr++) {
852     regmask = regmask_ind = 0;
853     w = parse_operand(&op->operand[opr], &regmask, &regmask_ind,
854       words, wordc, w, op->flags);
855
856     if (opr == 0 && (op->flags & OPF_DATA))
857       op->regmask_dst = regmask;
858     // for now, mark dst as src too
859     op->regmask_src |= regmask | regmask_ind;
860   }
861
862   for (; w < wordc && opr < op_table[i].maxopr; opr++) {
863     w = parse_operand(&op->operand[opr],
864       &op->regmask_src, &op->regmask_src,
865       words, wordc, w, op->flags);
866   }
867
868   if (w < wordc)
869     aerr("parse_op %s incomplete: %d/%d\n",
870       words[0], w, wordc);
871
872   // special cases
873   op->operand_cnt = opr;
874   if (!strncmp(op_table[i].name, "set", 3))
875     op->operand[0].lmod = OPLM_BYTE;
876
877   // ops with implicit argumets
878   switch (op->op) {
879   case OP_CDQ:
880     op->operand_cnt = 2;
881     setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
882     setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
883     break;
884
885   case OP_STOS:
886     if (op->operand_cnt != 0)
887       break;
888     if      (IS(words[op_w], "stosb"))
889       lmod = OPLM_BYTE;
890     else if (IS(words[op_w], "stosw"))
891       lmod = OPLM_WORD;
892     else if (IS(words[op_w], "stosd"))
893       lmod = OPLM_DWORD;
894     op->operand_cnt = 3;
895     setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
896     setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
897     op->regmask_dst = op->regmask_src;
898     setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD, &op->regmask_src);
899     break;
900
901   case OP_MOVS:
902   case OP_CMPS:
903     if (op->operand_cnt != 0)
904       break;
905     if      (words[op_w][4] == 'b')
906       lmod = OPLM_BYTE;
907     else if (words[op_w][4] == 'w')
908       lmod = OPLM_WORD;
909     else if (words[op_w][4] == 'd')
910       lmod = OPLM_DWORD;
911     op->operand_cnt = 3;
912     setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
913     setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
914     setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
915     op->regmask_dst = op->regmask_src;
916     break;
917
918   case OP_IMUL:
919     if (op->operand_cnt != 1)
920       break;
921     // fallthrough
922   case OP_MUL:
923     // singleop mul
924     op->regmask_dst = (1 << xDX) | (1 << xAX);
925     op->regmask_src |= (1 << xAX);
926     if (op->operand[0].lmod == OPLM_UNSPEC)
927       op->operand[0].lmod = OPLM_DWORD;
928     break;
929
930   case OP_DIV:
931   case OP_IDIV:
932     // we could set up operands for edx:eax, but there is no real need to
933     // (see is_opr_modified())
934     regmask = (1 << xDX) | (1 << xAX);
935     op->regmask_dst = regmask;
936     op->regmask_src |= regmask;
937     if (op->operand[0].lmod == OPLM_UNSPEC)
938       op->operand[0].lmod = OPLM_DWORD;
939     break;
940
941   case OP_SHL:
942   case OP_SHR:
943   case OP_SAR:
944   case OP_ROL:
945   case OP_ROR:
946     if (op->operand[1].lmod == OPLM_UNSPEC)
947       op->operand[1].lmod = OPLM_BYTE;
948     break;
949
950   case OP_PUSH:
951     if (op->operand[0].lmod == OPLM_UNSPEC
952         && (op->operand[0].type == OPT_CONST
953          || op->operand[0].type == OPT_OFFSET
954          || op->operand[0].type == OPT_LABEL))
955       op->operand[0].lmod = OPLM_DWORD;
956     break;
957
958   // alignment
959   case OP_MOV:
960     if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
961      && op->operand[0].reg == xDI && op->operand[1].reg == xDI)
962     {
963       op->flags |= OPF_RMD;
964     }
965     break;
966
967   case OP_LEA:
968     if (op->operand[0].type == OPT_REG
969      && op->operand[1].type == OPT_REGMEM)
970     {
971       char buf[16];
972       snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
973       if (IS(buf, op->operand[1].name))
974         op->flags |= OPF_RMD;
975     }
976     break;
977
978   case OP_CALL:
979     // trashed regs must be explicitly detected later
980     op->regmask_dst = 0;
981     break;
982
983   default:
984     break;
985   }
986 }
987
988 static const char *op_name(enum op_op op)
989 {
990   int i;
991
992   for (i = 0; i < ARRAY_SIZE(op_table); i++)
993     if (op_table[i].op == op)
994       return op_table[i].name;
995
996   return "???";
997 }
998
999 // debug
1000 static const char *dump_op(struct parsed_op *po)
1001 {
1002   static char out[128];
1003   char *p = out;
1004   int i;
1005
1006   if (po == NULL)
1007     return "???";
1008
1009   snprintf(out, sizeof(out), "%s", op_name(po->op));
1010   for (i = 0; i < po->operand_cnt; i++) {
1011     p += strlen(p);
1012     if (i > 0)
1013       *p++ = ',';
1014     snprintf(p, sizeof(out) - (p - out),
1015       po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1016       po->operand[i].name);
1017   }
1018
1019   return out;
1020 }
1021
1022 static const char *lmod_type_u(struct parsed_op *po,
1023   enum opr_lenmod lmod)
1024 {
1025   switch (lmod) {
1026   case OPLM_DWORD:
1027     return "u32";
1028   case OPLM_WORD:
1029     return "u16";
1030   case OPLM_BYTE:
1031     return "u8";
1032   default:
1033     ferr(po, "invalid lmod: %d\n", lmod);
1034     return "(_invalid_)";
1035   }
1036 }
1037
1038 static const char *lmod_cast_u(struct parsed_op *po,
1039   enum opr_lenmod lmod)
1040 {
1041   switch (lmod) {
1042   case OPLM_DWORD:
1043     return "";
1044   case OPLM_WORD:
1045     return "(u16)";
1046   case OPLM_BYTE:
1047     return "(u8)";
1048   default:
1049     ferr(po, "invalid lmod: %d\n", lmod);
1050     return "(_invalid_)";
1051   }
1052 }
1053
1054 static const char *lmod_cast_u_ptr(struct parsed_op *po,
1055   enum opr_lenmod lmod)
1056 {
1057   switch (lmod) {
1058   case OPLM_DWORD:
1059     return "*(u32 *)";
1060   case OPLM_WORD:
1061     return "*(u16 *)";
1062   case OPLM_BYTE:
1063     return "*(u8 *)";
1064   default:
1065     ferr(po, "invalid lmod: %d\n", lmod);
1066     return "(_invalid_)";
1067   }
1068 }
1069
1070 static const char *lmod_cast_s(struct parsed_op *po,
1071   enum opr_lenmod lmod)
1072 {
1073   switch (lmod) {
1074   case OPLM_DWORD:
1075     return "(s32)";
1076   case OPLM_WORD:
1077     return "(s16)";
1078   case OPLM_BYTE:
1079     return "(s8)";
1080   default:
1081     ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1082     return "(_invalid_)";
1083   }
1084 }
1085
1086 static const char *lmod_cast(struct parsed_op *po,
1087   enum opr_lenmod lmod, int is_signed)
1088 {
1089   return is_signed ?
1090     lmod_cast_s(po, lmod) :
1091     lmod_cast_u(po, lmod);
1092 }
1093
1094 static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1095 {
1096   switch (lmod) {
1097   case OPLM_DWORD:
1098     return 4;
1099   case OPLM_WORD:
1100     return 2;
1101   case OPLM_BYTE:
1102     return 1;
1103   default:
1104     ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1105     return 0;
1106   }
1107 }
1108
1109 static const char *opr_name(struct parsed_op *po, int opr_num)
1110 {
1111   if (opr_num >= po->operand_cnt)
1112     ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1113   return po->operand[opr_num].name;
1114 }
1115
1116 static unsigned int opr_const(struct parsed_op *po, int opr_num)
1117 {
1118   if (opr_num >= po->operand_cnt)
1119     ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1120   if (po->operand[opr_num].type != OPT_CONST)
1121     ferr(po, "opr %d: const expected\n", opr_num);
1122   return po->operand[opr_num].val;
1123 }
1124
1125 static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1126 {
1127   if ((unsigned int)popr->reg >= MAX_REGS)
1128     ferr(po, "invalid reg: %d\n", popr->reg);
1129   return regs_r32[popr->reg];
1130 }
1131
1132 // cast1 is the "final" cast
1133 static const char *simplify_cast(const char *cast1, const char *cast2)
1134 {
1135   static char buf[256];
1136
1137   if (cast1[0] == 0)
1138     return cast2;
1139   if (cast2[0] == 0)
1140     return cast1;
1141   if (IS(cast1, cast2))
1142     return cast1;
1143   if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1144     return cast1;
1145   if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1146     return cast1;
1147   if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1148     return cast2;
1149   if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1150     return cast2;
1151   if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1152     return cast1;
1153
1154   snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1155   return buf;
1156 }
1157
1158 static const char *simplify_cast_num(const char *cast, unsigned int val)
1159 {
1160   if (IS(cast, "(u8)") && val < 0x100)
1161     return "";
1162   if (IS(cast, "(s8)") && val < 0x80)
1163     return "";
1164   if (IS(cast, "(u16)") && val < 0x10000)
1165     return "";
1166   if (IS(cast, "(s16)") && val < 0x8000)
1167     return "";
1168   if (IS(cast, "(s32)") && val < 0x80000000)
1169     return "";
1170
1171   return cast;
1172 }
1173
1174 static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1175   int *extra_offs)
1176 {
1177   const char *p;
1178   char *endp;
1179   int namelen;
1180   int i;
1181
1182   *extra_offs = 0;
1183   namelen = strlen(name);
1184
1185   p = strchr(name, '+');
1186   if (p != NULL) {
1187     namelen = p - name;
1188     if (namelen <= 0)
1189       ferr(po, "equ parse failed for '%s'\n", name);
1190
1191     if (IS_START(p, "0x"))
1192       p += 2;
1193     *extra_offs = strtol(p, &endp, 16);
1194     if (*endp != 0)
1195       ferr(po, "equ parse failed for '%s'\n", name);
1196   }
1197
1198   for (i = 0; i < g_eqcnt; i++)
1199     if (strncmp(g_eqs[i].name, name, namelen) == 0
1200      && g_eqs[i].name[namelen] == 0)
1201       break;
1202   if (i >= g_eqcnt) {
1203     if (po != NULL)
1204       ferr(po, "unresolved equ name: '%s'\n", name);
1205     return NULL;
1206   }
1207
1208   return &g_eqs[i];
1209 }
1210
1211 static int is_stack_access(struct parsed_op *po,
1212   const struct parsed_opr *popr)
1213 {
1214   return (parse_stack_el(popr->name, NULL)
1215     || (g_bp_frame && !(po->flags & OPF_EBP_S)
1216         && IS_START(popr->name, "ebp")));
1217 }
1218
1219 static void parse_stack_access(struct parsed_op *po,
1220   const char *name, char *ofs_reg, int *offset_out,
1221   int *stack_ra_out, const char **bp_arg_out)
1222 {
1223   const char *bp_arg = "";
1224   const char *p = NULL;
1225   struct parsed_equ *eq;
1226   char *endp = NULL;
1227   int stack_ra = 0;
1228   int offset = 0;
1229
1230   ofs_reg[0] = 0;
1231
1232   if (IS_START(name, "ebp-")
1233    || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1234   {
1235     p = name + 4;
1236     if (IS_START(p, "0x"))
1237       p += 2;
1238     offset = strtoul(p, &endp, 16);
1239     if (name[3] == '-')
1240       offset = -offset;
1241     if (*endp != 0)
1242       ferr(po, "ebp- parse of '%s' failed\n", name);
1243   }
1244   else {
1245     bp_arg = parse_stack_el(name, ofs_reg);
1246     snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1247     eq = equ_find(po, bp_arg, &offset);
1248     if (eq == NULL)
1249       ferr(po, "detected but missing eq\n");
1250     offset += eq->offset;
1251   }
1252
1253   if (!strncmp(name, "ebp", 3))
1254     stack_ra = 4;
1255
1256   if (ofs_reg[0] == 0 && stack_ra <= offset && offset < stack_ra + 4)
1257     ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
1258
1259   *offset_out = offset;
1260   *stack_ra_out = stack_ra;
1261   if (bp_arg_out)
1262     *bp_arg_out = bp_arg;
1263 }
1264
1265 static void stack_frame_access(struct parsed_op *po,
1266   struct parsed_opr *popr, char *buf, size_t buf_size,
1267   const char *name, const char *cast, int is_src, int is_lea)
1268 {
1269   enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1270   const char *prefix = "";
1271   const char *bp_arg = NULL;
1272   char ofs_reg[16] = { 0, };
1273   int i, arg_i, arg_s;
1274   int unaligned = 0;
1275   int stack_ra = 0;
1276   int offset = 0;
1277   int sf_ofs;
1278   int lim;
1279
1280   if (po->flags & OPF_EBP_S)
1281     ferr(po, "stack_frame_access while ebp is scratch\n");
1282
1283   parse_stack_access(po, name, ofs_reg, &offset, &stack_ra, &bp_arg);
1284
1285   if (offset > stack_ra)
1286   {
1287     arg_i = (offset - stack_ra - 4) / 4;
1288     if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
1289     {
1290       if (g_func_pp->is_vararg
1291           && arg_i == g_func_pp->argc_stack && is_lea)
1292       {
1293         // should be va_list
1294         if (cast[0] == 0)
1295           cast = "(u32)";
1296         snprintf(buf, buf_size, "%sap", cast);
1297         return;
1298       }
1299       ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1300         offset, bp_arg, arg_i);
1301     }
1302     if (ofs_reg[0] != 0)
1303       ferr(po, "offset reg on arg access?\n");
1304
1305     for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1306       if (g_func_pp->arg[i].reg != NULL)
1307         continue;
1308       if (arg_s == arg_i)
1309         break;
1310       arg_s++;
1311     }
1312     if (i == g_func_pp->argc)
1313       ferr(po, "arg %d not in prototype?\n", arg_i);
1314
1315     popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
1316
1317     switch (popr->lmod)
1318     {
1319     case OPLM_BYTE:
1320       if (is_lea)
1321         ferr(po, "lea/byte to arg?\n");
1322       if (is_src && (offset & 3) == 0)
1323         snprintf(buf, buf_size, "%sa%d",
1324           simplify_cast(cast, "(u8)"), i + 1);
1325       else
1326         snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1327           cast, offset & 3, i + 1);
1328       break;
1329
1330     case OPLM_WORD:
1331       if (is_lea)
1332         ferr(po, "lea/word to arg?\n");
1333       if (offset & 1) {
1334         unaligned = 1;
1335         if (!is_src) {
1336           if (offset & 2)
1337             ferr(po, "problematic arg store\n");
1338           snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1339             simplify_cast(cast, "*(u16 *)"), i + 1);
1340         }
1341         else
1342           ferr(po, "unaligned arg word load\n");
1343       }
1344       else if (is_src && (offset & 2) == 0)
1345         snprintf(buf, buf_size, "%sa%d",
1346           simplify_cast(cast, "(u16)"), i + 1);
1347       else
1348         snprintf(buf, buf_size, "%s%sWORD(a%d)",
1349           cast, (offset & 2) ? "HI" : "LO", i + 1);
1350       break;
1351
1352     case OPLM_DWORD:
1353       if (cast[0])
1354         prefix = cast;
1355       else if (is_src)
1356         prefix = "(u32)";
1357
1358       if (offset & 3) {
1359         unaligned = 1;
1360         if (is_lea)
1361           snprintf(buf, buf_size, "(u32)&a%d + %d",
1362             i + 1, offset & 3);
1363         else if (!is_src)
1364           ferr(po, "unaligned arg store\n");
1365         else {
1366           // mov edx, [ebp+arg_4+2]; movsx ecx, dx
1367           snprintf(buf, buf_size, "%s(a%d >> %d)",
1368             prefix, i + 1, (offset & 3) * 8);
1369         }
1370       }
1371       else {
1372         snprintf(buf, buf_size, "%s%sa%d",
1373           prefix, is_lea ? "&" : "", i + 1);
1374       }
1375       break;
1376
1377     default:
1378       ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
1379     }
1380
1381     if (unaligned)
1382       snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1383
1384     // common problem
1385     guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
1386     if (tmp_lmod != OPLM_DWORD
1387       && (unaligned || (!is_src && tmp_lmod < popr->lmod)))
1388     {
1389       ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1390         i + 1, offset, g_func_pp->arg[i].type.name);
1391     }
1392     if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1393       ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1394   }
1395   else
1396   {
1397     if (g_stack_fsz == 0)
1398       ferr(po, "stack var access without stackframe\n");
1399     g_stack_frame_used = 1;
1400
1401     sf_ofs = g_stack_fsz + offset;
1402     lim = (ofs_reg[0] != 0) ? -4 : 0;
1403     if (offset > 0 || sf_ofs < lim)
1404       ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1405
1406     if (is_lea)
1407       prefix = "(u32)&";
1408     else
1409       prefix = cast;
1410
1411     switch (popr->lmod)
1412     {
1413     case OPLM_BYTE:
1414       snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1415         prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1416       break;
1417
1418     case OPLM_WORD:
1419       if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1420         // known unaligned or possibly unaligned
1421         strcat(g_comment, " unaligned");
1422         if (prefix[0] == 0)
1423           prefix = "*(u16 *)&";
1424         snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1425           prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1426         break;
1427       }
1428       snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1429       break;
1430
1431     case OPLM_DWORD:
1432       if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1433         // known unaligned or possibly unaligned
1434         strcat(g_comment, " unaligned");
1435         if (prefix[0] == 0)
1436           prefix = "*(u32 *)&";
1437         snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1438           prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1439         break;
1440       }
1441       snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1442       break;
1443
1444     default:
1445       ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1446     }
1447   }
1448 }
1449
1450 static void check_func_pp(struct parsed_op *po,
1451   const struct parsed_proto *pp, const char *pfx)
1452 {
1453   if (pp->argc_reg != 0) {
1454     if (!g_allow_regfunc)
1455       ferr(po, "%s: reg arg in arg-call unhandled yet\n", pfx);
1456     if (pp->argc_stack > 0 && pp->argc_reg != 2)
1457       ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1458         pfx, pp->argc_reg, pp->argc_stack);
1459   }
1460 }
1461
1462 static void check_label_read_ref(struct parsed_op *po, const char *name)
1463 {
1464   const struct parsed_proto *pp;
1465
1466   pp = proto_parse(g_fhdr, name, 0);
1467   if (pp == NULL)
1468     ferr(po, "proto_parse failed for ref '%s'\n", name);
1469
1470   if (pp->is_func)
1471     check_func_pp(po, pp, "ref");
1472 }
1473
1474 static char *out_src_opr(char *buf, size_t buf_size,
1475         struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1476   int is_lea)
1477 {
1478   char tmp1[256], tmp2[256];
1479   char expr[256];
1480   char *p;
1481   int ret;
1482
1483   if (cast == NULL)
1484     cast = "";
1485
1486   switch (popr->type) {
1487   case OPT_REG:
1488     if (is_lea)
1489       ferr(po, "lea from reg?\n");
1490
1491     switch (popr->lmod) {
1492     case OPLM_DWORD:
1493       snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1494       break;
1495     case OPLM_WORD:
1496       snprintf(buf, buf_size, "%s%s",
1497         simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1498       break;
1499     case OPLM_BYTE:
1500       if (popr->name[1] == 'h') // XXX..
1501         snprintf(buf, buf_size, "%s(%s >> 8)",
1502           simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1503       else
1504         snprintf(buf, buf_size, "%s%s",
1505           simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1506       break;
1507     default:
1508       ferr(po, "invalid src lmod: %d\n", popr->lmod);
1509     }
1510     break;
1511
1512   case OPT_REGMEM:
1513     if (is_stack_access(po, popr)) {
1514       stack_frame_access(po, popr, buf, buf_size,
1515         popr->name, cast, 1, is_lea);
1516       break;
1517     }
1518
1519     strcpy(expr, popr->name);
1520     if (strchr(expr, '[')) {
1521       // special case: '[' can only be left for label[reg] form
1522       ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1523       if (ret != 2)
1524         ferr(po, "parse failure for '%s'\n", expr);
1525       if (tmp1[0] == '(') {
1526         // (off_4FFF50+3)[eax]
1527         p = strchr(tmp1 + 1, ')');
1528         if (p == NULL || p[1] != 0)
1529           ferr(po, "parse failure (2) for '%s'\n", expr);
1530         *p = 0;
1531         memmove(tmp1, tmp1 + 1, strlen(tmp1));
1532       }
1533       snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1534     }
1535
1536     // XXX: do we need more parsing?
1537     if (is_lea) {
1538       snprintf(buf, buf_size, "%s", expr);
1539       break;
1540     }
1541
1542     snprintf(buf, buf_size, "%s(%s)",
1543       simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1544     break;
1545
1546   case OPT_LABEL:
1547     check_label_read_ref(po, popr->name);
1548     if (cast[0] == 0 && popr->is_ptr)
1549       cast = "(u32)";
1550
1551     if (is_lea)
1552       snprintf(buf, buf_size, "(u32)&%s", popr->name);
1553     else if (popr->size_lt)
1554       snprintf(buf, buf_size, "%s%s%s%s", cast,
1555         lmod_cast_u_ptr(po, popr->lmod),
1556         popr->is_array ? "" : "&",
1557         popr->name);
1558     else
1559       snprintf(buf, buf_size, "%s%s%s", cast, popr->name,
1560         popr->is_array ? "[0]" : "");
1561     break;
1562
1563   case OPT_OFFSET:
1564     check_label_read_ref(po, popr->name);
1565     if (cast[0] == 0)
1566       cast = "(u32)";
1567     if (is_lea)
1568       ferr(po, "lea an offset?\n");
1569     snprintf(buf, buf_size, "%s&%s", cast, popr->name);
1570     break;
1571
1572   case OPT_CONST:
1573     if (is_lea)
1574       ferr(po, "lea from const?\n");
1575
1576     printf_number(tmp1, sizeof(tmp1), popr->val);
1577     if (popr->val == 0 && strchr(cast, '*'))
1578       snprintf(buf, buf_size, "NULL");
1579     else
1580       snprintf(buf, buf_size, "%s%s",
1581         simplify_cast_num(cast, popr->val), tmp1);
1582     break;
1583
1584   default:
1585     ferr(po, "invalid src type: %d\n", popr->type);
1586   }
1587
1588   return buf;
1589 }
1590
1591 // note: may set is_ptr (we find that out late for ebp frame..)
1592 static char *out_dst_opr(char *buf, size_t buf_size,
1593         struct parsed_op *po, struct parsed_opr *popr)
1594 {
1595   switch (popr->type) {
1596   case OPT_REG:
1597     switch (popr->lmod) {
1598     case OPLM_DWORD:
1599       snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1600       break;
1601     case OPLM_WORD:
1602       // ugh..
1603       snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1604       break;
1605     case OPLM_BYTE:
1606       // ugh..
1607       if (popr->name[1] == 'h') // XXX..
1608         snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1609       else
1610         snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1611       break;
1612     default:
1613       ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1614     }
1615     break;
1616
1617   case OPT_REGMEM:
1618     if (is_stack_access(po, popr)) {
1619       stack_frame_access(po, popr, buf, buf_size,
1620         popr->name, "", 0, 0);
1621       break;
1622     }
1623
1624     return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1625
1626   case OPT_LABEL:
1627     if (popr->size_mismatch)
1628       snprintf(buf, buf_size, "%s%s%s",
1629         lmod_cast_u_ptr(po, popr->lmod),
1630         popr->is_array ? "" : "&", popr->name);
1631     else
1632       snprintf(buf, buf_size, "%s%s", popr->name,
1633         popr->is_array ? "[0]" : "");
1634     break;
1635
1636   default:
1637     ferr(po, "invalid dst type: %d\n", popr->type);
1638   }
1639
1640   return buf;
1641 }
1642
1643 static char *out_src_opr_u32(char *buf, size_t buf_size,
1644         struct parsed_op *po, struct parsed_opr *popr)
1645 {
1646   return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1647 }
1648
1649 static enum parsed_flag_op split_cond(struct parsed_op *po,
1650   enum op_op op, int *is_inv)
1651 {
1652   *is_inv = 0;
1653
1654   switch (op) {
1655   case OP_JO:
1656     return PFO_O;
1657   case OP_JC:
1658     return PFO_C;
1659   case OP_JZ:
1660     return PFO_Z;
1661   case OP_JBE:
1662     return PFO_BE;
1663   case OP_JS:
1664     return PFO_S;
1665   case OP_JP:
1666     return PFO_P;
1667   case OP_JL:
1668     return PFO_L;
1669   case OP_JLE:
1670     return PFO_LE;
1671
1672   case OP_JNO:
1673     *is_inv = 1;
1674     return PFO_O;
1675   case OP_JNC:
1676     *is_inv = 1;
1677     return PFO_C;
1678   case OP_JNZ:
1679     *is_inv = 1;
1680     return PFO_Z;
1681   case OP_JA:
1682     *is_inv = 1;
1683     return PFO_BE;
1684   case OP_JNS:
1685     *is_inv = 1;
1686     return PFO_S;
1687   case OP_JNP:
1688     *is_inv = 1;
1689     return PFO_P;
1690   case OP_JGE:
1691     *is_inv = 1;
1692     return PFO_L;
1693   case OP_JG:
1694     *is_inv = 1;
1695     return PFO_LE;
1696
1697   case OP_ADC:
1698   case OP_SBB:
1699     return PFO_C;
1700
1701   default:
1702     ferr(po, "split_cond: bad op %d\n", op);
1703     return -1;
1704   }
1705 }
1706
1707 static void out_test_for_cc(char *buf, size_t buf_size,
1708   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1709   enum opr_lenmod lmod, const char *expr)
1710 {
1711   const char *cast, *scast;
1712
1713   cast = lmod_cast_u(po, lmod);
1714   scast = lmod_cast_s(po, lmod);
1715
1716   switch (pfo) {
1717   case PFO_Z:
1718   case PFO_BE: // CF=1||ZF=1; CF=0
1719     snprintf(buf, buf_size, "(%s%s %s 0)",
1720       cast, expr, is_inv ? "!=" : "==");
1721     break;
1722
1723   case PFO_S:
1724   case PFO_L: // SF!=OF; OF=0
1725     snprintf(buf, buf_size, "(%s%s %s 0)",
1726       scast, expr, is_inv ? ">=" : "<");
1727     break;
1728
1729   case PFO_LE: // ZF=1||SF!=OF; OF=0
1730     snprintf(buf, buf_size, "(%s%s %s 0)",
1731       scast, expr, is_inv ? ">" : "<=");
1732     break;
1733
1734   default:
1735     ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1736   }
1737 }
1738
1739 static void out_cmp_for_cc(char *buf, size_t buf_size,
1740   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1741 {
1742   const char *cast, *scast, *cast_use;
1743   char buf1[256], buf2[256];
1744   enum opr_lenmod lmod;
1745
1746   if (po->operand[0].lmod != po->operand[1].lmod)
1747     ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1748       po->operand[0].lmod, po->operand[1].lmod);
1749   lmod = po->operand[0].lmod;
1750
1751   cast = lmod_cast_u(po, lmod);
1752   scast = lmod_cast_s(po, lmod);
1753
1754   switch (pfo) {
1755   case PFO_C:
1756   case PFO_Z:
1757   case PFO_BE: // !a
1758     cast_use = cast;
1759     break;
1760
1761   case PFO_S:
1762   case PFO_L: // !ge
1763   case PFO_LE:
1764     cast_use = scast;
1765     break;
1766
1767   default:
1768     ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1769   }
1770
1771   out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1772   out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1773
1774   switch (pfo) {
1775   case PFO_C:
1776     // note: must be unsigned compare
1777     snprintf(buf, buf_size, "(%s %s %s)",
1778       buf1, is_inv ? ">=" : "<", buf2);
1779     break;
1780
1781   case PFO_Z:
1782     snprintf(buf, buf_size, "(%s %s %s)",
1783       buf1, is_inv ? "!=" : "==", buf2);
1784     break;
1785
1786   case PFO_BE: // !a
1787     // note: must be unsigned compare
1788     snprintf(buf, buf_size, "(%s %s %s)",
1789       buf1, is_inv ? ">" : "<=", buf2);
1790
1791     // annoying case
1792     if (is_inv && lmod == OPLM_BYTE
1793       && po->operand[1].type == OPT_CONST
1794       && po->operand[1].val == 0xff)
1795     {
1796       snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1797       snprintf(buf, buf_size, "(0)");
1798     }
1799     break;
1800
1801   // note: must be signed compare
1802   case PFO_S:
1803     snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1804       scast, buf1, buf2, is_inv ? ">=" : "<");
1805     break;
1806
1807   case PFO_L: // !ge
1808     snprintf(buf, buf_size, "(%s %s %s)",
1809       buf1, is_inv ? ">=" : "<", buf2);
1810     break;
1811
1812   case PFO_LE:
1813     snprintf(buf, buf_size, "(%s %s %s)",
1814       buf1, is_inv ? ">" : "<=", buf2);
1815     break;
1816
1817   default:
1818     break;
1819   }
1820 }
1821
1822 static void out_cmp_test(char *buf, size_t buf_size,
1823   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1824 {
1825   char buf1[256], buf2[256], buf3[256];
1826
1827   if (po->op == OP_TEST) {
1828     if (IS(opr_name(po, 0), opr_name(po, 1))) {
1829       out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1830     }
1831     else {
1832       out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1833       out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1834       snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1835     }
1836     out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1837       po->operand[0].lmod, buf3);
1838   }
1839   else if (po->op == OP_CMP) {
1840     out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1841   }
1842   else
1843     ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1844 }
1845
1846 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1847         struct parsed_opr *popr2)
1848 {
1849   if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1850     ferr(po, "missing lmod for both operands\n");
1851
1852   if (popr1->lmod == OPLM_UNSPEC)
1853     popr1->lmod = popr2->lmod;
1854   else if (popr2->lmod == OPLM_UNSPEC)
1855     popr2->lmod = popr1->lmod;
1856   else if (popr1->lmod != popr2->lmod) {
1857     if (popr1->type_from_var) {
1858       popr1->size_mismatch = 1;
1859       if (popr1->lmod < popr2->lmod)
1860         popr1->size_lt = 1;
1861       popr1->lmod = popr2->lmod;
1862     }
1863     else if (popr2->type_from_var) {
1864       popr2->size_mismatch = 1;
1865       if (popr2->lmod < popr1->lmod)
1866         popr2->size_lt = 1;
1867       popr2->lmod = popr1->lmod;
1868     }
1869     else
1870       ferr(po, "conflicting lmods: %d vs %d\n",
1871         popr1->lmod, popr2->lmod);
1872   }
1873 }
1874
1875 static const char *op_to_c(struct parsed_op *po)
1876 {
1877   switch (po->op)
1878   {
1879     case OP_ADD:
1880     case OP_ADC:
1881       return "+";
1882     case OP_SUB:
1883     case OP_SBB:
1884       return "-";
1885     case OP_AND:
1886       return "&";
1887     case OP_OR:
1888       return "|";
1889     case OP_XOR:
1890       return "^";
1891     case OP_SHL:
1892       return "<<";
1893     case OP_SHR:
1894       return ">>";
1895     case OP_MUL:
1896     case OP_IMUL:
1897       return "*";
1898     default:
1899       ferr(po, "op_to_c was supplied with %d\n", po->op);
1900   }
1901 }
1902
1903 static void op_set_clear_flag(struct parsed_op *po,
1904   enum op_flags flag_set, enum op_flags flag_clear)
1905 {
1906   po->flags |= flag_set;
1907   po->flags &= ~flag_clear;
1908 }
1909
1910 // last op in stream - unconditional branch or ret
1911 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1912   || (ops[_i].flags & (OPF_JMP|OPF_CC)) == OPF_JMP)
1913
1914 static int scan_for_pop(int i, int opcnt, const char *reg,
1915   int magic, int depth, int *maxdepth, int do_flags)
1916 {
1917   const struct parsed_proto *pp;
1918   struct parsed_op *po;
1919   int ret = 0;
1920   int j;
1921
1922   for (; i < opcnt; i++) {
1923     po = &ops[i];
1924     if (po->cc_scratch == magic)
1925       break; // already checked
1926     po->cc_scratch = magic;
1927
1928     if (po->flags & OPF_TAIL) {
1929       if (po->op == OP_CALL) {
1930         pp = proto_parse(g_fhdr, po->operand[0].name, 0);
1931         if (pp != NULL && pp->is_noreturn)
1932           // no stack cleanup for noreturn
1933           return ret;
1934       }
1935       return -1; // deadend
1936     }
1937
1938     if ((po->flags & OPF_RMD)
1939         || (po->op == OP_PUSH && po->argnum != 0)) // arg push
1940       continue;
1941
1942     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1943       if (po->btj != NULL) {
1944         // jumptable
1945         for (j = 0; j < po->btj->count; j++) {
1946           ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
1947                    depth, maxdepth, do_flags);
1948           if (ret < 0)
1949             return ret; // dead end
1950         }
1951         return ret;
1952       }
1953
1954       if (po->bt_i < 0) {
1955         ferr(po, "dead branch\n");
1956         return -1;
1957       }
1958
1959       if (po->flags & OPF_CC) {
1960         ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1961                  depth, maxdepth, do_flags);
1962         if (ret < 0)
1963           return ret; // dead end
1964       }
1965       else {
1966         i = po->bt_i - 1;
1967       }
1968       continue;
1969     }
1970
1971     if ((po->op == OP_POP || po->op == OP_PUSH)
1972         && po->operand[0].type == OPT_REG
1973         && IS(po->operand[0].name, reg))
1974     {
1975       if (po->op == OP_PUSH && !(po->flags & OPF_FARG)) {
1976         depth++;
1977         if (depth > *maxdepth)
1978           *maxdepth = depth;
1979         if (do_flags)
1980           op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1981       }
1982       else if (po->op == OP_POP) {
1983         if (depth == 0) {
1984           if (do_flags)
1985             op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
1986           return 1;
1987         }
1988         else {
1989           depth--;
1990           if (depth < 0) // should not happen
1991             ferr(po, "fail with depth\n");
1992           if (do_flags)
1993             op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1994         }
1995       }
1996     }
1997   }
1998
1999   return ret;
2000 }
2001
2002 // scan for pop starting from 'ret' op (all paths)
2003 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2004   int flag_set)
2005 {
2006   int found = 0;
2007   int j;
2008
2009   for (; i < opcnt; i++) {
2010     if (!(ops[i].flags & OPF_TAIL))
2011       continue;
2012
2013     for (j = i - 1; j >= 0; j--) {
2014       if (ops[j].flags & OPF_RMD)
2015         continue;
2016       if (ops[j].flags & OPF_JMP)
2017         return -1;
2018
2019       if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2020           && IS(ops[j].operand[0].name, reg))
2021       {
2022         found = 1;
2023         ops[j].flags |= flag_set;
2024         break;
2025       }
2026
2027       if (g_labels[j][0] != 0)
2028         return -1;
2029     }
2030   }
2031
2032   return found ? 0 : -1;
2033 }
2034
2035 // is operand 'opr' modified by parsed_op 'po'?
2036 static int is_opr_modified(const struct parsed_opr *opr,
2037   const struct parsed_op *po)
2038 {
2039   int mask;
2040
2041   if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2042     return 0;
2043
2044   if (opr->type == OPT_REG) {
2045     if (po->op == OP_CALL) {
2046       mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2047       if ((1 << opr->reg) & mask)
2048         return 1;
2049       else
2050         return 0;
2051     }
2052
2053     if (po->operand[0].type == OPT_REG) {
2054       if (po->regmask_dst & (1 << opr->reg))
2055         return 1;
2056       else
2057         return 0;
2058     }
2059   }
2060
2061   return IS(po->operand[0].name, opr->name);
2062 }
2063
2064 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2065 static int is_any_opr_modified(const struct parsed_op *po_test,
2066   const struct parsed_op *po, int c_mode)
2067 {
2068   int mask;
2069   int i;
2070
2071   if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2072     return 0;
2073
2074   if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2075     return 0;
2076
2077   if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2078     return 1;
2079
2080   // in reality, it can wreck any register, but in decompiled C
2081   // version it can only overwrite eax or edx:eax
2082   mask = (1 << xAX) | (1 << xDX);
2083   if (!c_mode)
2084     mask |= 1 << xCX;
2085
2086   if (po->op == OP_CALL
2087    && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2088     return 1;
2089
2090   for (i = 0; i < po_test->operand_cnt; i++)
2091     if (IS(po_test->operand[i].name, po->operand[0].name))
2092       return 1;
2093
2094   return 0;
2095 }
2096
2097 // scan for any po_test operand modification in range given
2098 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2099   int c_mode)
2100 {
2101   if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2102     return -1;
2103
2104   for (; i < opcnt; i++) {
2105     if (is_any_opr_modified(po_test, &ops[i], c_mode))
2106       return i;
2107   }
2108
2109   return -1;
2110 }
2111
2112 // scan for po_test operand[0] modification in range given
2113 static int scan_for_mod_opr0(struct parsed_op *po_test,
2114   int i, int opcnt)
2115 {
2116   for (; i < opcnt; i++) {
2117     if (is_opr_modified(&po_test->operand[0], &ops[i]))
2118       return i;
2119   }
2120
2121   return -1;
2122 }
2123
2124 static int scan_for_flag_set(int i, int magic, int *branched,
2125   int *setters, int *setter_cnt)
2126 {
2127   struct label_ref *lr;
2128   int ret;
2129
2130   while (i >= 0) {
2131     if (ops[i].cc_scratch == magic) {
2132       ferr(&ops[i], "%s looped\n", __func__);
2133       return -1;
2134     }
2135     ops[i].cc_scratch = magic;
2136
2137     if (g_labels[i][0] != 0) {
2138       *branched = 1;
2139
2140       lr = &g_label_refs[i];
2141       for (; lr->next; lr = lr->next) {
2142         ret = scan_for_flag_set(lr->i, magic,
2143                 branched, setters, setter_cnt);
2144         if (ret < 0)
2145           return ret;
2146       }
2147
2148       if (i > 0 && LAST_OP(i - 1)) {
2149         i = lr->i;
2150         continue;
2151       }
2152       ret = scan_for_flag_set(lr->i, magic,
2153               branched, setters, setter_cnt);
2154       if (ret < 0)
2155         return ret;
2156     }
2157     i--;
2158
2159     if (ops[i].flags & OPF_FLAGS) {
2160       setters[*setter_cnt] = i;
2161       (*setter_cnt)++;
2162       return 0;
2163     }
2164
2165     if ((ops[i].flags & OPF_JMP) && !(ops[i].flags & OPF_CC))
2166       return -1;
2167   }
2168
2169   return -1;
2170 }
2171
2172 // scan back for cdq, if anything modifies edx, fail
2173 static int scan_for_cdq_edx(int i)
2174 {
2175   while (i >= 0) {
2176     if (g_labels[i][0] != 0) {
2177       if (g_label_refs[i].next != NULL)
2178         return -1;
2179       if (i > 0 && LAST_OP(i - 1)) {
2180         i = g_label_refs[i].i;
2181         continue;
2182       }
2183       return -1;
2184     }
2185     i--;
2186
2187     if (ops[i].op == OP_CDQ)
2188       return i;
2189
2190     if (ops[i].regmask_dst & (1 << xDX))
2191       return -1;
2192   }
2193
2194   return -1;
2195 }
2196
2197 static int scan_for_reg_clear(int i, int reg)
2198 {
2199   while (i >= 0) {
2200     if (g_labels[i][0] != 0) {
2201       if (g_label_refs[i].next != NULL)
2202         return -1;
2203       if (i > 0 && LAST_OP(i - 1)) {
2204         i = g_label_refs[i].i;
2205         continue;
2206       }
2207       return -1;
2208     }
2209     i--;
2210
2211     if (ops[i].op == OP_XOR
2212      && ops[i].operand[0].lmod == OPLM_DWORD
2213      && ops[i].operand[0].reg == ops[i].operand[1].reg
2214      && ops[i].operand[0].reg == reg)
2215       return i;
2216
2217     if (ops[i].regmask_dst & (1 << reg))
2218       return -1;
2219   }
2220
2221   return -1;
2222 }
2223
2224 // scan for positive, constant esp adjust
2225 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2226 {
2227   const struct parsed_proto *pp;
2228   struct parsed_op *po;
2229   int first_pop = -1;
2230   *adj = 0;
2231
2232   for (; i < opcnt; i++) {
2233     po = &ops[i];
2234
2235     if (g_labels[i][0] != 0)
2236       break;
2237
2238     if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2239       if (po->operand[1].type != OPT_CONST)
2240         ferr(&ops[i], "non-const esp adjust?\n");
2241       *adj += po->operand[1].val;
2242       if (*adj & 3)
2243         ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2244       return i;
2245     }
2246     else if (po->op == OP_PUSH) {
2247       if (first_pop == -1)
2248         first_pop = -2; // none
2249       *adj -= lmod_bytes(po, po->operand[0].lmod);
2250     }
2251     else if (po->op == OP_POP) {
2252       if (first_pop == -1)
2253         first_pop = i;
2254       *adj += lmod_bytes(po, po->operand[0].lmod);
2255     }
2256     else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2257       if (po->op != OP_CALL)
2258         break;
2259       if (po->operand[0].type != OPT_LABEL)
2260         break;
2261       pp = po->datap;
2262       if (pp != NULL && pp->is_stdcall)
2263         break;
2264     }
2265   }
2266
2267   if (*adj == 4 && first_pop >= 0 && ops[first_pop].op == OP_POP
2268     && ops[first_pop].operand[0].type == OPT_REG
2269     && ops[first_pop].operand[0].reg == xCX)
2270   {
2271     // probably 'pop ecx' was used..
2272     return first_pop;
2273   }
2274
2275   return -1;
2276 }
2277
2278 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2279 {
2280   struct parsed_op *po;
2281   int j;
2282
2283   if (i < 0)
2284     ferr(ops, "%s: followed bad branch?\n", __func__);
2285
2286   for (; i < opcnt; i++) {
2287     po = &ops[i];
2288     if (po->cc_scratch == magic)
2289       return;
2290     po->cc_scratch = magic;
2291     po->flags |= flags;
2292
2293     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2294       if (po->btj != NULL) {
2295         // jumptable
2296         for (j = 0; j < po->btj->count; j++)
2297           scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2298         return;
2299       }
2300
2301       scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2302       if (!(po->flags & OPF_CC))
2303         return;
2304     }
2305     if (po->flags & OPF_TAIL)
2306       return;
2307   }
2308 }
2309
2310 static const struct parsed_proto *try_recover_pp(
2311   struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2312 {
2313   const struct parsed_proto *pp = NULL;
2314   char buf[256];
2315   char *p;
2316
2317   // maybe an arg of g_func?
2318   if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2319   {
2320     char ofs_reg[16] = { 0, };
2321     int arg, arg_s, arg_i;
2322     int stack_ra = 0;
2323     int offset = 0;
2324
2325     parse_stack_access(po, opr->name, ofs_reg,
2326       &offset, &stack_ra, NULL);
2327     if (ofs_reg[0] != 0)
2328       ferr(po, "offset reg on arg access?\n");
2329     if (offset <= stack_ra) {
2330       // search who set the stack var instead
2331       if (search_instead != NULL)
2332         *search_instead = 1;
2333       return NULL;
2334     }
2335
2336     arg_i = (offset - stack_ra - 4) / 4;
2337     for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2338       if (g_func_pp->arg[arg].reg != NULL)
2339         continue;
2340       if (arg_s == arg_i)
2341         break;
2342       arg_s++;
2343     }
2344     if (arg == g_func_pp->argc)
2345       ferr(po, "stack arg %d not in prototype?\n", arg_i);
2346
2347     pp = g_func_pp->arg[arg].fptr;
2348     if (pp == NULL)
2349       ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2350     check_func_pp(po, pp, "icall arg");
2351   }
2352   else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2353     // label[index]
2354     p = strchr(opr->name + 1, '[');
2355     memcpy(buf, opr->name, p - opr->name);
2356     buf[p - opr->name] = 0;
2357     pp = proto_parse(g_fhdr, buf, 0);
2358   }
2359   else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2360     pp = proto_parse(g_fhdr, opr->name, 0);
2361     if (pp == NULL)
2362       ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2363     check_func_pp(po, pp, "reg-fptr ref");
2364   }
2365
2366   return pp;
2367 }
2368
2369 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2370   int magic, const struct parsed_proto **pp_found, int *multi)
2371 {
2372   const struct parsed_proto *pp = NULL;
2373   struct parsed_op *po;
2374   struct label_ref *lr;
2375
2376   while (i >= 0) {
2377     if (ops[i].cc_scratch == magic)
2378       return;
2379     ops[i].cc_scratch = magic;
2380
2381     if (g_labels[i][0] != 0) {
2382       lr = &g_label_refs[i];
2383       for (; lr != NULL; lr = lr->next)
2384         scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2385       if (i > 0 && LAST_OP(i - 1))
2386         return;
2387     }
2388     i--;
2389
2390     if (!(ops[i].flags & OPF_DATA))
2391       continue;
2392     if (!is_opr_modified(opr, &ops[i]))
2393       continue;
2394     if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2395       // most probably trashed by some processing
2396       *pp_found = NULL;
2397       return;
2398     }
2399
2400     opr = &ops[i].operand[1];
2401     if (opr->type != OPT_REG)
2402       break;
2403   }
2404
2405   po = (i >= 0) ? &ops[i] : ops;
2406
2407   if (i < 0) {
2408     // reached the top - can only be an arg-reg
2409     if (opr->type != OPT_REG)
2410       return;
2411
2412     for (i = 0; i < g_func_pp->argc; i++) {
2413       if (g_func_pp->arg[i].reg == NULL)
2414         continue;
2415       if (IS(opr->name, g_func_pp->arg[i].reg))
2416         break;
2417     }
2418     if (i == g_func_pp->argc)
2419       return;
2420     pp = g_func_pp->arg[i].fptr;
2421     if (pp == NULL)
2422       ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2423         i + 1, g_func_pp->arg[i].reg);
2424     check_func_pp(po, pp, "icall reg-arg");
2425   }
2426   else
2427     pp = try_recover_pp(po, opr, NULL);
2428
2429   if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2430     if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2431       || (*pp_found)->is_stdcall != pp->is_stdcall
2432       || (*pp_found)->is_fptr != pp->is_fptr
2433       || (*pp_found)->argc != pp->argc
2434       || (*pp_found)->argc_reg != pp->argc_reg
2435       || (*pp_found)->argc_stack != pp->argc_stack)
2436     {
2437       ferr(po, "icall: parsed_proto mismatch\n");
2438     }
2439     *multi = 1;
2440   }
2441   if (pp != NULL)
2442     *pp_found = pp;
2443 }
2444
2445 static const struct parsed_proto *resolve_icall(int i, int opcnt,
2446   int *multi_src)
2447 {
2448   const struct parsed_proto *pp = NULL;
2449   int search_advice = 0;
2450
2451   *multi_src = 0;
2452
2453   switch (ops[i].operand[0].type) {
2454   case OPT_REGMEM:
2455   case OPT_LABEL:
2456   case OPT_OFFSET:
2457     pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
2458     if (!search_advice)
2459       break;
2460     // fallthrough
2461   default:
2462     scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
2463       multi_src);
2464     break;
2465   }
2466
2467   return pp;
2468 }
2469
2470 static int collect_call_args_r(struct parsed_op *po, int i,
2471   struct parsed_proto *pp, int *regmask, int *save_arg_vars, int arg,
2472   int magic, int need_op_saving, int may_reuse)
2473 {
2474   struct parsed_proto *pp_tmp;
2475   struct label_ref *lr;
2476   int need_to_save_current;
2477   int ret = 0;
2478   int j;
2479
2480   if (i < 0) {
2481     ferr(po, "dead label encountered\n");
2482     return -1;
2483   }
2484
2485   for (; arg < pp->argc; arg++)
2486     if (pp->arg[arg].reg == NULL)
2487       break;
2488   magic = (magic & 0xffffff) | (arg << 24);
2489
2490   for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
2491   {
2492     if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2493       if (ops[j].cc_scratch != magic) {
2494         ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2495            pp->name);
2496         return -1;
2497       }
2498       // ok: have already been here
2499       return 0;
2500     }
2501     ops[j].cc_scratch = magic;
2502
2503     if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2504       lr = &g_label_refs[j];
2505       if (lr->next != NULL)
2506         need_op_saving = 1;
2507       for (; lr->next; lr = lr->next) {
2508         if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2509           may_reuse = 1;
2510         ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2511                 arg, magic, need_op_saving, may_reuse);
2512         if (ret < 0)
2513           return ret;
2514       }
2515
2516       if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2517         may_reuse = 1;
2518       if (j > 0 && LAST_OP(j - 1)) {
2519         // follow last branch in reverse
2520         j = lr->i;
2521         continue;
2522       }
2523       need_op_saving = 1;
2524       ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2525                arg, magic, need_op_saving, may_reuse);
2526       if (ret < 0)
2527         return ret;
2528     }
2529     j--;
2530
2531     if (ops[j].op == OP_CALL)
2532     {
2533       if (pp->is_unresolved)
2534         break;
2535
2536       pp_tmp = ops[j].datap;
2537       if (pp_tmp == NULL)
2538         ferr(po, "arg collect hit unparsed call '%s'\n",
2539           ops[j].operand[0].name);
2540       if (may_reuse && pp_tmp->argc_stack > 0)
2541         ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2542           arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2543     }
2544     else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2545       if (pp->is_unresolved)
2546         break;
2547
2548       ferr(po, "arg collect %d/%d hit esp adjust\n",
2549         arg, pp->argc);
2550     }
2551     else if (ops[j].op == OP_POP) {
2552       if (pp->is_unresolved)
2553         break;
2554
2555       ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2556     }
2557     else if ((ops[j].flags & (OPF_JMP|OPF_CC)) == (OPF_JMP|OPF_CC))
2558     {
2559       if (pp->is_unresolved)
2560         break;
2561
2562       may_reuse = 1;
2563     }
2564     else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2565     {
2566       if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
2567         break;
2568
2569       pp->arg[arg].datap = &ops[j];
2570       need_to_save_current = 0;
2571       if (!need_op_saving) {
2572         ret = scan_for_mod(&ops[j], j + 1, i, 1);
2573         need_to_save_current = (ret >= 0);
2574       }
2575       if (need_op_saving || need_to_save_current) {
2576         // mark this push as one that needs operand saving
2577         ops[j].flags &= ~OPF_RMD;
2578         if (ops[j].argnum == 0) {
2579           ops[j].argnum = arg + 1;
2580           *save_arg_vars |= 1 << arg;
2581         }
2582         else if (ops[j].argnum < arg + 1)
2583           ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2584             ops[j].argnum, arg + 1, pp->name);
2585       }
2586       else if (ops[j].argnum == 0)
2587         ops[j].flags |= OPF_RMD;
2588
2589       // some PUSHes are reused by different calls on other branches,
2590       // but that can't happen if we didn't branch, so they
2591       // can be removed from future searches (handles nested calls)
2592       if (!may_reuse)
2593         ops[j].flags |= OPF_FARG;
2594
2595       ops[j].flags &= ~OPF_RSAVE;
2596
2597       arg++;
2598       if (!pp->is_unresolved) {
2599         // next arg
2600         for (; arg < pp->argc; arg++)
2601           if (pp->arg[arg].reg == NULL)
2602             break;
2603       }
2604       magic = (magic & 0xffffff) | (arg << 24);
2605
2606       // tracking reg usage
2607       if (ops[j].operand[0].type == OPT_REG)
2608         *regmask |= 1 << ops[j].operand[0].reg;
2609     }
2610   }
2611
2612   if (arg < pp->argc) {
2613     ferr(po, "arg collect failed for '%s': %d/%d\n",
2614       pp->name, arg, pp->argc);
2615     return -1;
2616   }
2617
2618   return arg;
2619 }
2620
2621 static int collect_call_args(struct parsed_op *po, int i,
2622   struct parsed_proto *pp, int *regmask, int *save_arg_vars,
2623   int magic)
2624 {
2625   int ret;
2626   int a;
2627
2628   ret = collect_call_args_r(po, i, pp, regmask, save_arg_vars,
2629           0, magic, 0, 0);
2630   if (ret < 0)
2631     return ret;
2632
2633   if (pp->is_unresolved) {
2634     pp->argc += ret;
2635     pp->argc_stack += ret;
2636     for (a = 0; a < pp->argc; a++)
2637       if (pp->arg[a].type.name == NULL)
2638         pp->arg[a].type.name = strdup("int");
2639   }
2640
2641   return ret;
2642 }
2643
2644 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
2645 {
2646   int i;
2647
2648   for (i = 0; i < pp->argc; i++)
2649     if (pp->arg[i].reg == NULL)
2650       break;
2651
2652   if (pp->argc_stack)
2653     memmove(&pp->arg[i + 1], &pp->arg[i],
2654       sizeof(pp->arg[0]) * pp->argc_stack);
2655   memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
2656   pp->arg[i].reg = strdup(reg);
2657   pp->arg[i].type.name = strdup("int");
2658   pp->argc++;
2659   pp->argc_reg++;
2660 }
2661
2662 static void add_label_ref(struct label_ref *lr, int op_i)
2663 {
2664   struct label_ref *lr_new;
2665
2666   if (lr->i == -1) {
2667     lr->i = op_i;
2668     return;
2669   }
2670
2671   lr_new = calloc(1, sizeof(*lr_new));
2672   lr_new->i = op_i;
2673   lr_new->next = lr->next;
2674   lr->next = lr_new;
2675 }
2676
2677 static void output_std_flags(FILE *fout, struct parsed_op *po,
2678   int *pfomask, const char *dst_opr_text)
2679 {
2680   if (*pfomask & (1 << PFO_Z)) {
2681     fprintf(fout, "\n  cond_z = (%s%s == 0);",
2682       lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2683     *pfomask &= ~(1 << PFO_Z);
2684   }
2685   if (*pfomask & (1 << PFO_S)) {
2686     fprintf(fout, "\n  cond_s = (%s%s < 0);",
2687       lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2688     *pfomask &= ~(1 << PFO_S);
2689   }
2690 }
2691
2692 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2693 {
2694   struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2695   struct parsed_opr *last_arith_dst = NULL;
2696   char buf1[256], buf2[256], buf3[256], cast[64];
2697   const struct parsed_proto *pp_c;
2698   struct parsed_proto *pp, *pp_tmp;
2699   struct parsed_data *pd;
2700   const char *tmpname;
2701   enum parsed_flag_op pfo;
2702   int save_arg_vars = 0;
2703   int cmp_result_vars = 0;
2704   int need_mul_var = 0;
2705   int had_decl = 0;
2706   int label_pending = 0;
2707   int regmask_save = 0;
2708   int regmask_arg = 0;
2709   int regmask_now = 0;
2710   int regmask_init = 0;
2711   int regmask = 0;
2712   int pfomask = 0;
2713   int found = 0;
2714   int depth = 0;
2715   int no_output;
2716   int i, j, l;
2717   int dummy;
2718   int arg;
2719   int reg;
2720   int ret;
2721
2722   g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2723   g_stack_frame_used = 0;
2724
2725   g_func_pp = proto_parse(fhdr, funcn, 0);
2726   if (g_func_pp == NULL)
2727     ferr(ops, "proto_parse failed for '%s'\n", funcn);
2728
2729   fprintf(fout, "%s ", g_func_pp->ret_type.name);
2730   if (g_func_pp->is_stdcall && g_func_pp->argc_reg == 0)
2731     fprintf(fout, "__stdcall ");
2732   if (g_ida_func_attr & IDAFA_NORETURN)
2733     fprintf(fout, "noreturn ");
2734   fprintf(fout, "%s(", funcn);
2735
2736   for (i = 0; i < g_func_pp->argc; i++) {
2737     if (i > 0)
2738       fprintf(fout, ", ");
2739     if (g_func_pp->arg[i].fptr != NULL) {
2740       // func pointer..
2741       pp = g_func_pp->arg[i].fptr;
2742       fprintf(fout, "%s (", pp->ret_type.name);
2743       if (pp->is_stdcall && pp->argc_reg == 0)
2744         fprintf(fout, "__stdcall ");
2745       fprintf(fout, "*a%d)(", i + 1);
2746       for (j = 0; j < pp->argc; j++) {
2747         if (j > 0)
2748           fprintf(fout, ", ");
2749         if (pp->arg[j].fptr)
2750           ferr(ops, "nested fptr\n");
2751         fprintf(fout, "%s", pp->arg[j].type.name);
2752       }
2753       fprintf(fout, ")");
2754     }
2755     else {
2756       fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2757     }
2758     if (g_func_pp->arg[i].reg != NULL) {
2759       reg = char_array_i(regs_r32,
2760               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2761       if (reg < 0)
2762         ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2763       regmask_arg |= 1 << reg;
2764     }
2765   }
2766   if (g_func_pp->is_vararg) {
2767     if (i > 0)
2768       fprintf(fout, ", ");
2769     fprintf(fout, "...");
2770   }
2771
2772   fprintf(fout, ")\n{\n");
2773
2774   // pass1:
2775   // - handle ebp/esp frame, remove ops related to it
2776   if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2777       && ops[1].op == OP_MOV
2778       && IS(opr_name(&ops[1], 0), "ebp")
2779       && IS(opr_name(&ops[1], 1), "esp"))
2780   {
2781     int ecx_push = 0;
2782
2783     g_bp_frame = 1;
2784     ops[0].flags |= OPF_RMD;
2785     ops[1].flags |= OPF_RMD;
2786     i = 2;
2787
2788     if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2789       g_stack_fsz = opr_const(&ops[2], 1);
2790       ops[2].flags |= OPF_RMD;
2791       i++;
2792     }
2793     else {
2794       // another way msvc builds stack frame..
2795       i = 2;
2796       while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2797         g_stack_fsz += 4;
2798         ops[i].flags |= OPF_RMD;
2799         ecx_push++;
2800         i++;
2801       }
2802       // and another way..
2803       if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2804           && ops[i].operand[1].type == OPT_CONST
2805           && ops[i + 1].op == OP_CALL
2806           && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2807       {
2808         g_stack_fsz += ops[i].operand[1].val;
2809         ops[i].flags |= OPF_RMD;
2810         i++;
2811         ops[i].flags |= OPF_RMD;
2812         i++;
2813       }
2814     }
2815
2816     found = 0;
2817     do {
2818       for (; i < opcnt; i++)
2819         if (ops[i].op == OP_RET)
2820           break;
2821       if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2822         break;
2823
2824       if (ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2825         ops[i - 1].flags |= OPF_RMD;
2826       else if (!(g_ida_func_attr & IDAFA_NORETURN))
2827         ferr(&ops[i - 1], "'pop ebp' expected\n");
2828
2829       if (g_stack_fsz != 0) {
2830         if (ops[i - 2].op == OP_MOV
2831             && IS(opr_name(&ops[i - 2], 0), "esp")
2832             && IS(opr_name(&ops[i - 2], 1), "ebp"))
2833         {
2834           ops[i - 2].flags |= OPF_RMD;
2835         }
2836         else if (!(g_ida_func_attr & IDAFA_NORETURN))
2837           ferr(&ops[i - 2], "esp restore expected\n");
2838
2839         if (ecx_push && ops[i - 3].op == OP_POP
2840           && IS(opr_name(&ops[i - 3], 0), "ecx"))
2841         {
2842           ferr(&ops[i - 3], "unexpected ecx pop\n");
2843         }
2844       }
2845
2846       found = 1;
2847       i++;
2848     } while (i < opcnt);
2849   }
2850   else {
2851     for (i = 0; i < opcnt; i++) {
2852       if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2853         break;
2854       if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2855         && ops[i].operand[1].type == OPT_CONST)
2856       {
2857         g_sp_frame = 1;
2858         break;
2859       }
2860     }
2861
2862     if (g_sp_frame)
2863     {
2864       g_stack_fsz = ops[i].operand[1].val;
2865       ops[i].flags |= OPF_RMD;
2866
2867       i++;
2868       do {
2869         for (; i < opcnt; i++)
2870           if (ops[i].op == OP_RET)
2871             break;
2872         if (ops[i - 1].op != OP_ADD
2873             || !IS(opr_name(&ops[i - 1], 0), "esp")
2874             || ops[i - 1].operand[1].type != OPT_CONST
2875             || ops[i - 1].operand[1].val != g_stack_fsz)
2876           ferr(&ops[i - 1], "'add esp' expected\n");
2877         ops[i - 1].flags |= OPF_RMD;
2878
2879         i++;
2880       } while (i < opcnt);
2881     }
2882   }
2883
2884   // pass2:
2885   // - parse calls with labels
2886   // - resolve all branches
2887   for (i = 0; i < opcnt; i++)
2888   {
2889     po = &ops[i];
2890     po->bt_i = -1;
2891     po->btj = NULL;
2892
2893     if (po->flags & OPF_RMD)
2894       continue;
2895
2896     if (po->op == OP_CALL) {
2897       pp = NULL;
2898
2899       if (po->operand[0].type == OPT_LABEL) {
2900         tmpname = opr_name(po, 0);
2901         if (IS_START(tmpname, "loc_"))
2902           ferr(po, "call to loc_*\n");
2903         pp_c = proto_parse(fhdr, tmpname, 0);
2904         if (pp_c == NULL)
2905           ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2906
2907         pp = proto_clone(pp_c);
2908         my_assert_not(pp, NULL);
2909       }
2910       else if (po->datap != NULL) {
2911         pp = calloc(1, sizeof(*pp));
2912         my_assert_not(pp, NULL);
2913
2914         ret = parse_protostr(po->datap, pp);
2915         if (ret < 0)
2916           ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
2917         free(po->datap);
2918         po->datap = NULL;
2919       }
2920
2921       if (pp != NULL) {
2922         if (pp->is_fptr)
2923           check_func_pp(po, pp, "fptr var call");
2924         if (pp->is_noreturn)
2925           po->flags |= OPF_TAIL;
2926         po->datap = pp;
2927       }
2928       continue;
2929     }
2930
2931     if (!(po->flags & OPF_JMP) || po->op == OP_RET)
2932       continue;
2933
2934     if (po->operand[0].type == OPT_REGMEM) {
2935       char *p = strchr(po->operand[0].name, '[');
2936       if (p == NULL)
2937         goto tailcall;
2938       ret = p - po->operand[0].name;
2939       strncpy(buf1, po->operand[0].name, ret);
2940       buf1[ret] = 0;
2941
2942       for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2943         if (IS(g_func_pd[j].label, buf1)) {
2944           pd = &g_func_pd[j];
2945           break;
2946         }
2947       }
2948       if (pd == NULL)
2949         //ferr(po, "label '%s' not parsed?\n", buf1);
2950         goto tailcall;
2951       if (pd->type != OPT_OFFSET)
2952         ferr(po, "label '%s' with non-offset data?\n", buf1);
2953
2954       // find all labels, link
2955       for (j = 0; j < pd->count; j++) {
2956         for (l = 0; l < opcnt; l++) {
2957           if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
2958             add_label_ref(&g_label_refs[l], i);
2959             pd->d[j].bt_i = l;
2960             break;
2961           }
2962         }
2963       }
2964
2965       po->btj = pd;
2966       continue;
2967     }
2968
2969     for (l = 0; l < opcnt; l++) {
2970       if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
2971         add_label_ref(&g_label_refs[l], i);
2972         po->bt_i = l;
2973         break;
2974       }
2975     }
2976
2977     if (po->bt_i != -1)
2978       continue;
2979
2980     if (po->operand[0].type == OPT_LABEL)
2981       // assume tail call
2982       goto tailcall;
2983
2984     ferr(po, "unhandled branch\n");
2985
2986 tailcall:
2987     po->op = OP_CALL;
2988     po->flags |= OPF_TAIL;
2989     i--; // reprocess
2990   }
2991
2992   // pass3:
2993   // - remove dead labels
2994   // - process calls
2995   for (i = 0; i < opcnt; i++)
2996   {
2997     if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
2998       g_labels[i][0] = 0;
2999
3000     po = &ops[i];
3001     if (po->flags & OPF_RMD)
3002       continue;
3003
3004     if (po->op == OP_CALL)
3005     {
3006       tmpname = opr_name(po, 0);
3007       pp = po->datap;
3008       if (pp == NULL)
3009       {
3010         // indirect call
3011         pp_c = resolve_icall(i, opcnt, &l);
3012         if (pp_c != NULL) {
3013           pp = proto_clone(pp_c);
3014           my_assert_not(pp, NULL);
3015           if (l)
3016             // not resolved just to single func
3017             pp->is_fptr = 1;
3018         }
3019         if (pp == NULL) {
3020           pp = calloc(1, sizeof(*pp));
3021           my_assert_not(pp, NULL);
3022           pp->is_fptr = 1;
3023           ret = scan_for_esp_adjust(i + 1, opcnt, &j);
3024           if (ret < 0) {
3025             if (!g_allow_regfunc)
3026               ferr(po, "non-__cdecl indirect call unhandled yet\n");
3027             pp->is_unresolved = 1;
3028             j = 0;
3029           }
3030           j /= 4;
3031           if (j > ARRAY_SIZE(pp->arg))
3032             ferr(po, "esp adjust too large: %d\n", j);
3033           pp->ret_type.name = strdup("int");
3034           pp->argc = pp->argc_stack = j;
3035           for (arg = 0; arg < pp->argc; arg++)
3036             pp->arg[arg].type.name = strdup("int");
3037         }
3038         po->datap = pp;
3039       }
3040
3041       // look for and make use of esp adjust
3042       ret = -1;
3043       if (!pp->is_stdcall && pp->argc_stack > 0)
3044         ret = scan_for_esp_adjust(i + 1, opcnt, &j);
3045       if (ret >= 0) {
3046         if (pp->is_vararg) {
3047           if (j / 4 < pp->argc_stack)
3048             ferr(po, "esp adjust is too small: %x < %x\n",
3049               j, pp->argc_stack * 4);
3050           // modify pp to make it have varargs as normal args
3051           arg = pp->argc;
3052           pp->argc += j / 4 - pp->argc_stack;
3053           for (; arg < pp->argc; arg++) {
3054             pp->arg[arg].type.name = strdup("int");
3055             pp->argc_stack++;
3056           }
3057           if (pp->argc > ARRAY_SIZE(pp->arg))
3058             ferr(po, "too many args for '%s'\n", tmpname);
3059         }
3060         if (pp->argc_stack != j / 4)
3061           ferr(po, "stack tracking failed for '%s': %x %x\n",
3062             tmpname, pp->argc_stack * 4, j);
3063
3064         ops[ret].flags |= OPF_RMD;
3065         // a bit of a hack, but deals with use of
3066         // single adj for multiple calls
3067         ops[ret].operand[1].val -= j;
3068       }
3069       else if (pp->is_vararg)
3070         ferr(po, "missing esp_adjust for vararg func '%s'\n",
3071           pp->name);
3072
3073       if (!pp->is_unresolved) {
3074         // since we know the args, collect them
3075         collect_call_args(po, i, pp, &regmask, &save_arg_vars,
3076           i + opcnt * 2);
3077       }
3078
3079       if (strstr(pp->ret_type.name, "int64"))
3080         need_mul_var = 1;
3081     }
3082   }
3083
3084   // pass4:
3085   // - find POPs for PUSHes, rm both
3086   // - scan for all used registers
3087   // - find flag set ops for their users
3088   // - do unreselved calls
3089   // - declare indirect functions
3090   for (i = 0; i < opcnt; i++) {
3091     po = &ops[i];
3092     if (po->flags & OPF_RMD)
3093       continue;
3094
3095     if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3096       reg = po->operand[0].reg;
3097       if (!(regmask & (1 << reg)))
3098         // not a reg save after all, rerun scan_for_pop
3099         po->flags &= ~OPF_RSAVE;
3100       else
3101         regmask_save |= 1 << reg;
3102     }
3103
3104     if (po->op == OP_PUSH
3105         && po->argnum == 0 && !(po->flags & OPF_RSAVE)
3106         && po->operand[0].type == OPT_REG)
3107     {
3108       reg = po->operand[0].reg;
3109       if (reg < 0)
3110         ferr(po, "reg not set for push?\n");
3111
3112       depth = 0;
3113       ret = scan_for_pop(i + 1, opcnt,
3114               po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3115       if (ret == 1) {
3116         if (depth > 1)
3117           ferr(po, "too much depth: %d\n", depth);
3118
3119         po->flags |= OPF_RMD;
3120         scan_for_pop(i + 1, opcnt, po->operand[0].name,
3121           i + opcnt * 4, 0, &depth, 1);
3122         continue;
3123       }
3124       ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3125       if (ret == 0) {
3126         arg = OPF_RMD;
3127         if (regmask & (1 << reg)) {
3128           if (regmask_save & (1 << reg))
3129             ferr(po, "%s already saved?\n", po->operand[0].name);
3130           arg = OPF_RSAVE;
3131         }
3132         po->flags |= arg;
3133         scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3134         continue;
3135       }
3136     }
3137
3138     regmask_now = po->regmask_src | po->regmask_dst;
3139     if (regmask_now & (1 << xBP)) {
3140       if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3141         if (po->regmask_dst & (1 << xBP))
3142           // compiler decided to drop bp frame and use ebp as scratch
3143           scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
3144         else
3145           regmask_now &= ~(1 << xBP);
3146       }
3147     }
3148
3149     regmask |= regmask_now;
3150
3151     if (po->flags & OPF_CC)
3152     {
3153       int setters[16], cnt = 0, branched = 0;
3154
3155       ret = scan_for_flag_set(i, i + opcnt * 6,
3156               &branched, setters, &cnt);
3157       if (ret < 0 || cnt <= 0)
3158         ferr(po, "unable to trace flag setter(s)\n");
3159       if (cnt > ARRAY_SIZE(setters))
3160         ferr(po, "too many flag setters\n");
3161
3162       pfo = split_cond(po, po->op, &dummy);
3163       for (j = 0; j < cnt; j++)
3164       {
3165         tmp_op = &ops[setters[j]]; // flag setter
3166         pfomask = 0;
3167
3168         // to get nicer code, we try to delay test and cmp;
3169         // if we can't because of operand modification, or if we
3170         // have math op, or branch, make it calculate flags explicitly
3171         if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
3172           if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
3173             pfomask = 1 << pfo;
3174         }
3175         else if (tmp_op->op == OP_CMPS) {
3176           pfomask = 1 << PFO_Z;
3177         }
3178         else {
3179           // see if we'll be able to handle based on op result
3180           if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3181                && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3182               || branched
3183               || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3184             pfomask = 1 << pfo;
3185         }
3186         if (pfomask) {
3187           tmp_op->pfomask |= pfomask;
3188           cmp_result_vars |= pfomask;
3189         }
3190         // note: may overwrite, currently not a problem
3191         po->datap = tmp_op;
3192       }
3193
3194       if (po->op == OP_ADC || po->op == OP_SBB)
3195         cmp_result_vars |= 1 << PFO_C;
3196     }
3197     else if (po->op == OP_MUL
3198       || (po->op == OP_IMUL && po->operand_cnt == 1))
3199     {
3200       need_mul_var = 1;
3201     }
3202     else if (po->op == OP_CALL) {
3203       pp = po->datap;
3204       if (pp == NULL)
3205         ferr(po, "NULL pp\n");
3206
3207       if (pp->is_unresolved) {
3208         int regmask_stack = 0;
3209         collect_call_args(po, i, pp, &regmask_stack, &save_arg_vars,
3210           i + opcnt * 2);
3211
3212         if (!((regmask_stack & (1 << xCX))
3213           && (regmask_stack & (1 << xDX))))
3214         {
3215           if (pp->argc_stack != 0
3216            || ((regmask | regmask_arg) & (1 << xCX)))
3217           {
3218             pp_insert_reg_arg(pp, "ecx");
3219             regmask_init |= 1 << xCX;
3220             regmask |= 1 << xCX;
3221           }
3222           if (pp->argc_stack != 0
3223            || ((regmask | regmask_arg) & (1 << xDX)))
3224           {
3225             pp_insert_reg_arg(pp, "edx");
3226             regmask_init |= 1 << xDX;
3227             regmask |= 1 << xDX;
3228           }
3229         }
3230         regmask |= regmask_stack;
3231       }
3232
3233       for (arg = 0; arg < pp->argc; arg++) {
3234         if (pp->arg[arg].reg != NULL) {
3235           reg = char_array_i(regs_r32,
3236                   ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
3237           if (reg < 0)
3238             ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
3239           if (!(regmask & (1 << reg))) {
3240             regmask_init |= 1 << reg;
3241             regmask |= 1 << reg;
3242           }
3243         }
3244       }
3245
3246       if (pp->is_fptr) {
3247         if (pp->name[0] != 0) {
3248           memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
3249           memcpy(pp->name, "i_", 2);
3250
3251           // might be declared already
3252           found = 0;
3253           for (j = 0; j < i; j++) {
3254             if (ops[j].op == OP_CALL && (pp_tmp = ops[j].datap)) {
3255               if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
3256                 found = 1;
3257                 break;
3258               }
3259             }
3260           }
3261           if (found)
3262             continue;
3263         }
3264         else
3265           snprintf(pp->name, sizeof(pp->name), "icall%d", i);
3266
3267         fprintf(fout, "  %s (", pp->ret_type.name);
3268         if (pp->is_stdcall && pp->argc_reg == 0)
3269           fprintf(fout, "__stdcall ");
3270         fprintf(fout, "*%s)(", pp->name);
3271         for (j = 0; j < pp->argc; j++) {
3272           if (j > 0)
3273             fprintf(fout, ", ");
3274           fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3275         }
3276         fprintf(fout, ");\n");
3277       }
3278     }
3279     else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3280       regmask |= 1 << xAX;
3281   }
3282
3283   // pass4:
3284   // - confirm regmask_save, it might have been reduced
3285   if (regmask_save != 0)
3286   {
3287     regmask_save = 0;
3288     for (i = 0; i < opcnt; i++) {
3289       po = &ops[i];
3290       if (po->flags & OPF_RMD)
3291         continue;
3292
3293       if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
3294         regmask_save |= 1 << po->operand[0].reg;
3295     }
3296   }
3297
3298
3299   // output LUTs/jumptables
3300   for (i = 0; i < g_func_pd_cnt; i++) {
3301     pd = &g_func_pd[i];
3302     fprintf(fout, "  static const ");
3303     if (pd->type == OPT_OFFSET) {
3304       fprintf(fout, "void *jt_%s[] =\n    { ", pd->label);
3305
3306       for (j = 0; j < pd->count; j++) {
3307         if (j > 0)
3308           fprintf(fout, ", ");
3309         fprintf(fout, "&&%s", pd->d[j].u.label);
3310       }
3311     }
3312     else {
3313       fprintf(fout, "%s %s[] =\n    { ",
3314         lmod_type_u(ops, pd->lmod), pd->label);
3315
3316       for (j = 0; j < pd->count; j++) {
3317         if (j > 0)
3318           fprintf(fout, ", ");
3319         fprintf(fout, "%u", pd->d[j].u.val);
3320       }
3321     }
3322     fprintf(fout, " };\n");
3323   }
3324
3325   // declare stack frame, va_arg
3326   if (g_stack_fsz)
3327     fprintf(fout, "  union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3328       (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3329
3330   if (g_func_pp->is_vararg)
3331     fprintf(fout, "  va_list ap;\n");
3332
3333   // declare arg-registers
3334   for (i = 0; i < g_func_pp->argc; i++) {
3335     if (g_func_pp->arg[i].reg != NULL) {
3336       reg = char_array_i(regs_r32,
3337               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3338       if (regmask & (1 << reg)) {
3339         fprintf(fout, "  u32 %s = (u32)a%d;\n",
3340           g_func_pp->arg[i].reg, i + 1);
3341       }
3342       else
3343         fprintf(fout, "  // %s = a%d; // unused\n",
3344           g_func_pp->arg[i].reg, i + 1);
3345       had_decl = 1;
3346     }
3347   }
3348
3349   regmask_now = regmask & ~regmask_arg;
3350   regmask_now &= ~(1 << xSP);
3351   if (regmask_now) {
3352     for (reg = 0; reg < 8; reg++) {
3353       if (regmask_now & (1 << reg)) {
3354         fprintf(fout, "  u32 %s", regs_r32[reg]);
3355         if (regmask_init & (1 << reg))
3356           fprintf(fout, " = 0");
3357         fprintf(fout, ";\n");
3358         had_decl = 1;
3359       }
3360     }
3361   }
3362
3363   if (regmask_save) {
3364     for (reg = 0; reg < 8; reg++) {
3365       if (regmask_save & (1 << reg)) {
3366         fprintf(fout, "  u32 s_%s;\n", regs_r32[reg]);
3367         had_decl = 1;
3368       }
3369     }
3370   }
3371
3372   if (save_arg_vars) {
3373     for (reg = 0; reg < 32; reg++) {
3374       if (save_arg_vars & (1 << reg)) {
3375         fprintf(fout, "  u32 s_a%d;\n", reg + 1);
3376         had_decl = 1;
3377       }
3378     }
3379   }
3380
3381   if (cmp_result_vars) {
3382     for (i = 0; i < 8; i++) {
3383       if (cmp_result_vars & (1 << i)) {
3384         fprintf(fout, "  u32 cond_%s;\n", parsed_flag_op_names[i]);
3385         had_decl = 1;
3386       }
3387     }
3388   }
3389
3390   if (need_mul_var) {
3391     fprintf(fout, "  u64 mul_tmp;\n");
3392     had_decl = 1;
3393   }
3394
3395   if (had_decl)
3396     fprintf(fout, "\n");
3397
3398   if (g_func_pp->is_vararg) {
3399     if (g_func_pp->argc_stack == 0)
3400       ferr(ops, "vararg func without stack args?\n");
3401     fprintf(fout, "  va_start(ap, a%d);\n", g_func_pp->argc);
3402   }
3403
3404   // output ops
3405   for (i = 0; i < opcnt; i++)
3406   {
3407     if (g_labels[i][0] != 0) {
3408       fprintf(fout, "\n%s:\n", g_labels[i]);
3409       label_pending = 1;
3410
3411       delayed_flag_op = NULL;
3412       last_arith_dst = NULL;
3413     }
3414
3415     po = &ops[i];
3416     if (po->flags & OPF_RMD)
3417       continue;
3418
3419     no_output = 0;
3420
3421     #define assert_operand_cnt(n_) \
3422       if (po->operand_cnt != n_) \
3423         ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3424
3425     // conditional/flag using op?
3426     if (po->flags & OPF_CC)
3427     {
3428       int is_delayed = 0;
3429       int is_inv = 0;
3430
3431       pfo = split_cond(po, po->op, &is_inv);
3432       tmp_op = po->datap;
3433
3434       // we go through all this trouble to avoid using parsed_flag_op,
3435       // which makes generated code much nicer
3436       if (delayed_flag_op != NULL)
3437       {
3438         out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3439         is_delayed = 1;
3440       }
3441       else if (last_arith_dst != NULL
3442         && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3443            || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3444            ))
3445       {
3446         out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3447         out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3448           last_arith_dst->lmod, buf3);
3449         is_delayed = 1;
3450       }
3451       else if (tmp_op != NULL) {
3452         // use preprocessed flag calc results
3453         if (!(tmp_op->pfomask & (1 << pfo)))
3454           ferr(po, "not prepared for pfo %d\n", pfo);
3455
3456         // note: is_inv was not yet applied
3457         snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3458           is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3459       }
3460       else {
3461         ferr(po, "all methods of finding comparison failed\n");
3462       }
3463  
3464       if (po->flags & OPF_JMP) {
3465         fprintf(fout, "  if %s\n", buf1);
3466       }
3467       else if (po->op == OP_ADC || po->op == OP_SBB) {
3468         if (is_delayed)
3469           fprintf(fout, "  cond_%s = %s;\n",
3470             parsed_flag_op_names[pfo], buf1);
3471       }
3472       else if (po->flags & OPF_DATA) { // SETcc
3473         out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3474         fprintf(fout, "  %s = %s;", buf2, buf1);
3475       }
3476       else {
3477         ferr(po, "unhandled conditional op\n");
3478       }
3479     }
3480
3481     pfomask = po->pfomask;
3482
3483     switch (po->op)
3484     {
3485       case OP_MOV:
3486         assert_operand_cnt(2);
3487         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3488         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3489         fprintf(fout, "  %s = %s;", buf1,
3490             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3491               po->operand[0].is_ptr ? "(void *)" : "", 0));
3492         break;
3493
3494       case OP_LEA:
3495         assert_operand_cnt(2);
3496         po->operand[1].lmod = OPLM_DWORD; // always
3497         fprintf(fout, "  %s = %s;",
3498             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3499             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3500               NULL, 1));
3501         break;
3502
3503       case OP_MOVZX:
3504         assert_operand_cnt(2);
3505         fprintf(fout, "  %s = %s;",
3506             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3507             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3508         break;
3509
3510       case OP_MOVSX:
3511         assert_operand_cnt(2);
3512         switch (po->operand[1].lmod) {
3513         case OPLM_BYTE:
3514           strcpy(buf3, "(s8)");
3515           break;
3516         case OPLM_WORD:
3517           strcpy(buf3, "(s16)");
3518           break;
3519         default:
3520           ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3521         }
3522         fprintf(fout, "  %s = %s;",
3523             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3524             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3525               buf3, 0));
3526         break;
3527
3528       case OP_NOT:
3529         assert_operand_cnt(1);
3530         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3531         fprintf(fout, "  %s = ~%s;", buf1, buf1);
3532         break;
3533
3534       case OP_CDQ:
3535         assert_operand_cnt(2);
3536         fprintf(fout, "  %s = (s32)%s >> 31;",
3537             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3538             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3539         strcpy(g_comment, "cdq");
3540         break;
3541
3542       case OP_STOS:
3543         // assumes DF=0
3544         assert_operand_cnt(3);
3545         if (po->flags & OPF_REP) {
3546           fprintf(fout, "  for (; ecx != 0; ecx--, edi += %d)\n",
3547             lmod_bytes(po, po->operand[0].lmod));
3548           fprintf(fout, "    %sedi = eax;",
3549             lmod_cast_u_ptr(po, po->operand[0].lmod));
3550           strcpy(g_comment, "rep stos");
3551         }
3552         else {
3553           fprintf(fout, "    %sedi = eax; edi += %d;",
3554             lmod_cast_u_ptr(po, po->operand[0].lmod),
3555             lmod_bytes(po, po->operand[0].lmod));
3556           strcpy(g_comment, "stos");
3557         }
3558         break;
3559
3560       case OP_MOVS:
3561         // assumes DF=0
3562         assert_operand_cnt(3);
3563         j = lmod_bytes(po, po->operand[0].lmod);
3564         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3565         if (po->flags & OPF_REP) {
3566           fprintf(fout,
3567             "  for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3568             j, j);
3569           fprintf(fout,
3570             "    %sedi = %sesi;", buf1, buf1);
3571           strcpy(g_comment, "rep movs");
3572         }
3573         else {
3574           fprintf(fout, "    %sedi = %sesi; edi += %d; esi += %d;",
3575             buf1, buf1, j, j);
3576           strcpy(g_comment, "movs");
3577         }
3578         break;
3579
3580       case OP_CMPS:
3581         // assumes DF=0
3582         // repe ~ repeat while ZF=1
3583         assert_operand_cnt(3);
3584         j = lmod_bytes(po, po->operand[0].lmod);
3585         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3586         if (po->flags & OPF_REP) {
3587           fprintf(fout,
3588             "  for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3589             j, j);
3590           fprintf(fout,
3591             "    if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3592               buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3593           fprintf(fout,
3594             "      break;");
3595           snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3596             (po->flags & OPF_REPZ) ? "e" : "ne");
3597         }
3598         else {
3599           fprintf(fout,
3600             "    cond_z = (%sedi = %sesi); edi += %d; esi += %d;",
3601             buf1, buf1, j, j);
3602           strcpy(g_comment, "cmps");
3603         }
3604         pfomask &= ~(1 << PFO_Z);
3605         last_arith_dst = NULL;
3606         delayed_flag_op = NULL;
3607         break;
3608
3609       // arithmetic w/flags
3610       case OP_ADD:
3611       case OP_SUB:
3612       case OP_AND:
3613       case OP_OR:
3614         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3615         // fallthrough
3616       dualop_arith:
3617         assert_operand_cnt(2);
3618         fprintf(fout, "  %s %s= %s;",
3619             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3620             op_to_c(po),
3621             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3622         output_std_flags(fout, po, &pfomask, buf1);
3623         last_arith_dst = &po->operand[0];
3624         delayed_flag_op = NULL;
3625         break;
3626
3627       case OP_SHL:
3628       case OP_SHR:
3629         assert_operand_cnt(2);
3630         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3631         if (pfomask & (1 << PFO_C)) {
3632           if (po->operand[1].type == OPT_CONST) {
3633             l = lmod_bytes(po, po->operand[0].lmod) * 8;
3634             j = po->operand[1].val;
3635             j %= l;
3636             if (j != 0) {
3637               if (po->op == OP_SHL)
3638                 j = l - j;
3639               else
3640                 j -= 1;
3641               fprintf(fout, "  cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3642                 buf1, 1 << j);
3643             }
3644             else
3645               ferr(po, "zero shift?\n");
3646           }
3647           else
3648             ferr(po, "TODO\n");
3649           pfomask &= ~(1 << PFO_C);
3650         }
3651         fprintf(fout, "  %s %s= %s;", buf1, op_to_c(po),
3652             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3653         output_std_flags(fout, po, &pfomask, buf1);
3654         last_arith_dst = &po->operand[0];
3655         delayed_flag_op = NULL;
3656         break;
3657
3658       case OP_SAR:
3659         assert_operand_cnt(2);
3660         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3661         fprintf(fout, "  %s = %s%s >> %s;", buf1,
3662           lmod_cast_s(po, po->operand[0].lmod), buf1,
3663           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3664         output_std_flags(fout, po, &pfomask, buf1);
3665         last_arith_dst = &po->operand[0];
3666         delayed_flag_op = NULL;
3667         break;
3668
3669       case OP_ROL:
3670       case OP_ROR:
3671         assert_operand_cnt(2);
3672         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3673         if (po->operand[1].type == OPT_CONST) {
3674           j = po->operand[1].val;
3675           j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3676           fprintf(fout, po->op == OP_ROL ?
3677             "  %s = (%s << %d) | (%s >> %d);" :
3678             "  %s = (%s >> %d) | (%s << %d);",
3679             buf1, buf1, j, buf1,
3680             lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3681         }
3682         else
3683           ferr(po, "TODO\n");
3684         output_std_flags(fout, po, &pfomask, buf1);
3685         last_arith_dst = &po->operand[0];
3686         delayed_flag_op = NULL;
3687         break;
3688
3689       case OP_XOR:
3690         assert_operand_cnt(2);
3691         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3692         if (IS(opr_name(po, 0), opr_name(po, 1))) {
3693           // special case for XOR
3694           fprintf(fout, "  %s = 0;",
3695             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3696           last_arith_dst = &po->operand[0];
3697           delayed_flag_op = NULL;
3698           break;
3699         }
3700         goto dualop_arith;
3701
3702       case OP_ADC:
3703       case OP_SBB:
3704         assert_operand_cnt(2);
3705         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3706         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3707         if (po->op == OP_SBB
3708           && IS(po->operand[0].name, po->operand[1].name))
3709         {
3710           // avoid use of unitialized var
3711           fprintf(fout, "  %s = -cond_c;", buf1);
3712           // carry remains what it was
3713           pfomask &= ~(1 << PFO_C);
3714         }
3715         else {
3716           fprintf(fout, "  %s %s= %s + cond_c;", buf1, op_to_c(po),
3717             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3718         }
3719         output_std_flags(fout, po, &pfomask, buf1);
3720         last_arith_dst = &po->operand[0];
3721         delayed_flag_op = NULL;
3722         break;
3723
3724       case OP_INC:
3725       case OP_DEC:
3726         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3727         if (po->operand[0].type == OPT_REG) {
3728           strcpy(buf2, po->op == OP_INC ? "++" : "--");
3729           fprintf(fout, "  %s%s;", buf1, buf2);
3730         }
3731         else {
3732           strcpy(buf2, po->op == OP_INC ? "+" : "-");
3733           fprintf(fout, "  %s %s= 1;", buf1, buf2);
3734         }
3735         output_std_flags(fout, po, &pfomask, buf1);
3736         last_arith_dst = &po->operand[0];
3737         delayed_flag_op = NULL;
3738         break;
3739
3740       case OP_NEG:
3741         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3742         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3743         fprintf(fout, "  %s = -%s%s;", buf1,
3744           lmod_cast_s(po, po->operand[0].lmod), buf2);
3745         last_arith_dst = &po->operand[0];
3746         delayed_flag_op = NULL;
3747         if (pfomask & (1 << PFO_C)) {
3748           fprintf(fout, "\n  cond_c = (%s != 0);", buf1);
3749           pfomask &= ~(1 << PFO_C);
3750         }
3751         break;
3752
3753       case OP_IMUL:
3754         if (po->operand_cnt == 2) {
3755           propagate_lmod(po, &po->operand[0], &po->operand[1]);
3756           goto dualop_arith;
3757         }
3758         if (po->operand_cnt == 3)
3759           ferr(po, "TODO imul3\n");
3760         // fallthrough
3761       case OP_MUL:
3762         assert_operand_cnt(1);
3763         strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3764         fprintf(fout, "  mul_tmp = %seax * %s%s;\n", buf1, buf1,
3765           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3766         fprintf(fout, "  edx = mul_tmp >> 32;\n");
3767         fprintf(fout, "  eax = mul_tmp;");
3768         last_arith_dst = NULL;
3769         delayed_flag_op = NULL;
3770         break;
3771
3772       case OP_DIV:
3773       case OP_IDIV:
3774         assert_operand_cnt(1);
3775         if (po->operand[0].lmod != OPLM_DWORD)
3776           ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3777
3778         // 32bit division is common, look for it
3779         if (po->op == OP_DIV)
3780           ret = scan_for_reg_clear(i, xDX);
3781         else
3782           ret = scan_for_cdq_edx(i);
3783         if (ret >= 0) {
3784           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3785           strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3786             po->op == OP_IDIV));
3787           fprintf(fout, "  edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3788           fprintf(fout, "  eax = %seax / %s%s;", buf2, buf2, buf1);
3789         }
3790         else
3791           ferr(po, "TODO 64bit divident\n");
3792         last_arith_dst = NULL;
3793         delayed_flag_op = NULL;
3794         break;
3795
3796       case OP_TEST:
3797       case OP_CMP:
3798         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3799         if (pfomask != 0) {
3800           for (j = 0; j < 8; j++) {
3801             if (pfomask & (1 << j)) {
3802               out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3803               fprintf(fout, "  cond_%s = %s;",
3804                 parsed_flag_op_names[j], buf1);
3805             }
3806           }
3807           pfomask = 0;
3808         }
3809         else
3810           no_output = 1;
3811         last_arith_dst = NULL;
3812         delayed_flag_op = po;
3813         break;
3814
3815       // note: we reuse OP_Jcc for SETcc, only flags differ
3816       case OP_JO ... OP_JG:
3817         if (po->flags & OPF_JMP)
3818           fprintf(fout, "    goto %s;", po->operand[0].name);
3819         // else SETcc - should already be handled
3820         break;
3821
3822       case OP_JMP:
3823         assert_operand_cnt(1);
3824         last_arith_dst = NULL;
3825         delayed_flag_op = NULL;
3826
3827         if (po->operand[0].type == OPT_REGMEM) {
3828           ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
3829                   buf1, buf2);
3830           if (ret != 2)
3831             ferr(po, "parse failure for jmp '%s'\n",
3832               po->operand[0].name);
3833           fprintf(fout, "  goto *jt_%s[%s];", buf1, buf2);
3834           break;
3835         }
3836         else if (po->operand[0].type != OPT_LABEL)
3837           ferr(po, "unhandled jmp type\n");
3838
3839         fprintf(fout, "  goto %s;", po->operand[0].name);
3840         break;
3841
3842       case OP_CALL:
3843         assert_operand_cnt(1);
3844         pp = po->datap;
3845         my_assert_not(pp, NULL);
3846
3847         if (pp->is_fptr)
3848           fprintf(fout, "  %s = %s;\n", pp->name,
3849             out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
3850               "(void *)", 0));
3851
3852         fprintf(fout, "  ");
3853         if (strstr(pp->ret_type.name, "int64")) {
3854           if (po->flags & OPF_TAIL)
3855             ferr(po, "int64 and tail?\n");
3856           fprintf(fout, "mul_tmp = ");
3857         }
3858         else if (!IS(pp->ret_type.name, "void")) {
3859           if (po->flags & OPF_TAIL) {
3860             if (!IS(g_func_pp->ret_type.name, "void")) {
3861               fprintf(fout, "return ");
3862               if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
3863                 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
3864             }
3865           }
3866           else if (regmask & (1 << xAX)) {
3867             fprintf(fout, "eax = ");
3868             if (pp->ret_type.is_ptr)
3869               fprintf(fout, "(u32)");
3870           }
3871         }
3872
3873         if (pp->name[0] == 0)
3874           ferr(po, "missing pp->name\n");
3875         fprintf(fout, "%s%s(", pp->name,
3876           pp->has_structarg ? "_sa" : "");
3877
3878         for (arg = 0; arg < pp->argc; arg++) {
3879           if (arg > 0)
3880             fprintf(fout, ", ");
3881
3882           cast[0] = 0;
3883           if (pp->arg[arg].type.is_ptr)
3884             snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
3885
3886           if (pp->arg[arg].reg != NULL) {
3887             fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
3888             continue;
3889           }
3890
3891           // stack arg
3892           tmp_op = pp->arg[arg].datap;
3893           if (tmp_op == NULL)
3894             ferr(po, "parsed_op missing for arg%d\n", arg);
3895           if (tmp_op->argnum != 0) {
3896             fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
3897           }
3898           else {
3899             fprintf(fout, "%s",
3900               out_src_opr(buf1, sizeof(buf1),
3901                 tmp_op, &tmp_op->operand[0], cast, 0));
3902           }
3903         }
3904         fprintf(fout, ");");
3905
3906         if (strstr(pp->ret_type.name, "int64")) {
3907           fprintf(fout, "\n");
3908           fprintf(fout, "  edx = mul_tmp >> 32;\n");
3909           fprintf(fout, "  eax = mul_tmp;");
3910         }
3911
3912         if (pp->is_unresolved) {
3913           snprintf(buf3, sizeof(buf3), " unresoved %dreg",
3914             pp->argc_reg);
3915           strcat(g_comment, buf3);
3916         }
3917
3918         if (po->flags & OPF_TAIL) {
3919           ret = 0;
3920           if (i == opcnt - 1 || pp->is_noreturn)
3921             ret = 0;
3922           else if (IS(pp->ret_type.name, "void"))
3923             ret = 1;
3924           else if (IS(g_func_pp->ret_type.name, "void"))
3925             ret = 1;
3926           // else already handled as 'return f()'
3927
3928           if (ret) {
3929             if (!IS(g_func_pp->ret_type.name, "void")) {
3930               ferr(po, "int func -> void func tailcall?\n");
3931             }
3932             else {
3933               fprintf(fout, "\n  return;");
3934               strcat(g_comment, " ^ tailcall");
3935             }
3936           }
3937           else
3938             strcat(g_comment, " tailcall");
3939         }
3940         if (pp->is_noreturn)
3941           strcat(g_comment, " noreturn");
3942         delayed_flag_op = NULL;
3943         last_arith_dst = NULL;
3944         break;
3945
3946       case OP_RET:
3947         if (g_func_pp->is_vararg)
3948           fprintf(fout, "  va_end(ap);\n");
3949  
3950         if (IS(g_func_pp->ret_type.name, "void")) {
3951           if (i != opcnt - 1 || label_pending)
3952             fprintf(fout, "  return;");
3953         }
3954         else if (g_func_pp->ret_type.is_ptr) {
3955           fprintf(fout, "  return (%s)eax;",
3956             g_func_pp->ret_type.name);
3957         }
3958         else
3959           fprintf(fout, "  return eax;");
3960
3961         last_arith_dst = NULL;
3962         delayed_flag_op = NULL;
3963         break;
3964
3965       case OP_PUSH:
3966         if (po->argnum != 0) {
3967           // special case - saved func arg
3968           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3969           fprintf(fout, "  s_a%d = %s;", po->argnum, buf1);
3970           break;
3971         }
3972         else if (po->flags & OPF_RSAVE) {
3973           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3974           fprintf(fout, "  s_%s = %s;", buf1, buf1);
3975           break;
3976         }
3977         if (!(g_ida_func_attr & IDAFA_NORETURN))
3978           ferr(po, "stray push encountered\n");
3979         no_output = 1;
3980         break;
3981
3982       case OP_POP:
3983         if (po->flags & OPF_RSAVE) {
3984           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3985           fprintf(fout, "  %s = s_%s;", buf1, buf1);
3986           break;
3987         }
3988         ferr(po, "stray pop encountered\n");
3989         break;
3990
3991       case OP_NOP:
3992         no_output = 1;
3993         break;
3994
3995       default:
3996         no_output = 1;
3997         ferr(po, "unhandled op type %d, flags %x\n",
3998           po->op, po->flags);
3999         break;
4000     }
4001
4002     if (g_comment[0] != 0) {
4003       char *p = g_comment;
4004       while (my_isblank(*p))
4005         p++;
4006       fprintf(fout, "  // %s", p);
4007       g_comment[0] = 0;
4008       no_output = 0;
4009     }
4010     if (!no_output)
4011       fprintf(fout, "\n");
4012
4013     // some sanity checking
4014     if ((po->flags & OPF_REP) && po->op != OP_STOS
4015         && po->op != OP_MOVS && po->op != OP_CMPS)
4016       ferr(po, "unexpected rep\n");
4017     if ((po->flags & (OPF_REPZ|OPF_REPNZ)) && po->op != OP_CMPS)
4018       ferr(po, "unexpected repz/repnz\n");
4019
4020     if (pfomask != 0)
4021       ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
4022
4023     // see is delayed flag stuff is still valid
4024     if (delayed_flag_op != NULL && delayed_flag_op != po) {
4025       if (is_any_opr_modified(delayed_flag_op, po, 0))
4026         delayed_flag_op = NULL;
4027     }
4028
4029     if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
4030       if (is_opr_modified(last_arith_dst, po))
4031         last_arith_dst = NULL;
4032     }
4033
4034     label_pending = 0;
4035   }
4036
4037   if (g_stack_fsz && !g_stack_frame_used)
4038     fprintf(fout, "  (void)sf;\n");
4039
4040   fprintf(fout, "}\n\n");
4041
4042   // cleanup
4043   for (i = 0; i < opcnt; i++) {
4044     struct label_ref *lr, *lr_del;
4045
4046     lr = g_label_refs[i].next;
4047     while (lr != NULL) {
4048       lr_del = lr;
4049       lr = lr->next;
4050       free(lr_del);
4051     }
4052     g_label_refs[i].i = -1;
4053     g_label_refs[i].next = NULL;
4054
4055     if (ops[i].op == OP_CALL) {
4056       pp = ops[i].datap;
4057       if (pp)
4058         proto_release(pp);
4059     }
4060   }
4061   g_func_pp = NULL;
4062 }
4063
4064 static void set_label(int i, const char *name)
4065 {
4066   const char *p;
4067   int len;
4068
4069   len = strlen(name);
4070   p = strchr(name, ':');
4071   if (p != NULL)
4072     len = p - name;
4073
4074   if (len > sizeof(g_labels[0]) - 1)
4075     aerr("label '%s' too long: %d\n", name, len);
4076   if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
4077     aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
4078   memcpy(g_labels[i], name, len);
4079   g_labels[i][len] = 0;
4080 }
4081
4082 // '=' needs special treatment..
4083 static char *next_word_s(char *w, size_t wsize, char *s)
4084 {
4085         size_t i;
4086
4087         s = sskip(s);
4088
4089         for (i = 0; i < wsize - 1; i++) {
4090                 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
4091                         break;
4092                 w[i] = s[i];
4093         }
4094         w[i] = 0;
4095
4096         if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
4097                 printf("warning: '%s' truncated\n", w);
4098
4099         return s + i;
4100 }
4101
4102 struct chunk_item {
4103   char *name;
4104   long fptr;
4105   int asmln;
4106 };
4107
4108 static struct chunk_item *func_chunks;
4109 static int func_chunk_cnt;
4110 static int func_chunk_alloc;
4111
4112 static void add_func_chunk(FILE *fasm, const char *name, int line)
4113 {
4114   if (func_chunk_cnt >= func_chunk_alloc) {
4115     func_chunk_alloc *= 2;
4116     func_chunks = realloc(func_chunks,
4117       func_chunk_alloc * sizeof(func_chunks[0]));
4118     my_assert_not(func_chunks, NULL);
4119   }
4120   func_chunks[func_chunk_cnt].fptr = ftell(fasm);
4121   func_chunks[func_chunk_cnt].name = strdup(name);
4122   func_chunks[func_chunk_cnt].asmln = line;
4123   func_chunk_cnt++;
4124 }
4125
4126 static int cmp_chunks(const void *p1, const void *p2)
4127 {
4128   const struct chunk_item *c1 = p1, *c2 = p2;
4129   return strcmp(c1->name, c2->name);
4130 }
4131
4132 static int cmpstringp(const void *p1, const void *p2)
4133 {
4134   return strcmp(*(char * const *)p1, *(char * const *)p2);
4135 }
4136
4137 static void scan_ahead(FILE *fasm)
4138 {
4139   char words[2][256];
4140   char line[256];
4141   long oldpos;
4142   int oldasmln;
4143   int wordc;
4144   char *p;
4145   int i;
4146
4147   oldpos = ftell(fasm);
4148   oldasmln = asmln;
4149
4150   while (fgets(line, sizeof(line), fasm))
4151   {
4152     wordc = 0;
4153     asmln++;
4154
4155     p = sskip(line);
4156     if (*p == 0)
4157       continue;
4158
4159     if (*p == ';')
4160     {
4161       // get rid of random tabs
4162       for (i = 0; line[i] != 0; i++)
4163         if (line[i] == '\t')
4164           line[i] = ' ';
4165
4166       if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4167       {
4168         p += 30;
4169         next_word(words[0], sizeof(words[0]), p);
4170         if (words[0][0] == 0)
4171           aerr("missing name for func chunk?\n");
4172
4173         add_func_chunk(fasm, words[0], asmln);
4174       }
4175       continue;
4176     } // *p == ';'
4177
4178     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4179       words[wordc][0] = 0;
4180       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4181       if (*p == 0 || *p == ';') {
4182         wordc++;
4183         break;
4184       }
4185     }
4186
4187     if (wordc == 2 && IS(words[1], "ends"))
4188       break;
4189   }
4190
4191   fseek(fasm, oldpos, SEEK_SET);
4192   asmln = oldasmln;
4193 }
4194
4195 int main(int argc, char *argv[])
4196 {
4197   FILE *fout, *fasm, *frlist;
4198   struct parsed_data *pd = NULL;
4199   int pd_alloc = 0;
4200   char **rlist = NULL;
4201   int rlist_len = 0;
4202   int rlist_alloc = 0;
4203   int func_chunks_used = 0;
4204   int func_chunks_sorted = 0;
4205   int func_chunk_i = -1;
4206   long func_chunk_ret = 0;
4207   int func_chunk_ret_ln = 0;
4208   int scanned_ahead = 0;
4209   char line[256];
4210   char words[20][256];
4211   enum opr_lenmod lmod;
4212   char *sctproto = NULL;
4213   int in_func = 0;
4214   int pending_endp = 0;
4215   int skip_func = 0;
4216   int skip_warned = 0;
4217   int eq_alloc;
4218   int verbose = 0;
4219   int arg_out;
4220   int arg;
4221   int pi = 0;
4222   int i, j;
4223   int ret, len;
4224   char *p;
4225   int wordc;
4226
4227   for (arg = 1; arg < argc; arg++) {
4228     if (IS(argv[arg], "-v"))
4229       verbose = 1;
4230     else if (IS(argv[arg], "-rf"))
4231       g_allow_regfunc = 1;
4232     else
4233       break;
4234   }
4235
4236   if (argc < arg + 3) {
4237     printf("usage:\n%s [-v] [-rf] <.c> <.asm> <hdrf> [rlist]*\n",
4238       argv[0]);
4239     return 1;
4240   }
4241
4242   arg_out = arg++;
4243
4244   asmfn = argv[arg++];
4245   fasm = fopen(asmfn, "r");
4246   my_assert_not(fasm, NULL);
4247
4248   hdrfn = argv[arg++];
4249   g_fhdr = fopen(hdrfn, "r");
4250   my_assert_not(g_fhdr, NULL);
4251
4252   rlist_alloc = 64;
4253   rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4254   my_assert_not(rlist, NULL);
4255   // needs special handling..
4256   rlist[rlist_len++] = "__alloca_probe";
4257
4258   func_chunk_alloc = 32;
4259   func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4260   my_assert_not(func_chunks, NULL);
4261
4262   memset(words, 0, sizeof(words));
4263
4264   for (; arg < argc; arg++) {
4265     frlist = fopen(argv[arg], "r");
4266     my_assert_not(frlist, NULL);
4267
4268     while (fgets(line, sizeof(line), frlist)) {
4269       p = sskip(line);
4270       if (*p == 0 || *p == ';')
4271         continue;
4272       if (*p == '#') {
4273         if (IS_START(p, "#if 0")
4274          || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
4275         {
4276           skip_func = 1;
4277         }
4278         else if (IS_START(p, "#endif"))
4279           skip_func = 0;
4280         continue;
4281       }
4282       if (skip_func)
4283         continue;
4284
4285       p = next_word(words[0], sizeof(words[0]), p);
4286       if (words[0][0] == 0)
4287         continue;
4288
4289       if (rlist_len >= rlist_alloc) {
4290         rlist_alloc = rlist_alloc * 2 + 64;
4291         rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4292         my_assert_not(rlist, NULL);
4293       }
4294       rlist[rlist_len++] = strdup(words[0]);
4295     }
4296     skip_func = 0;
4297
4298     fclose(frlist);
4299     frlist = NULL;
4300   }
4301
4302   if (rlist_len > 0)
4303     qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4304
4305   fout = fopen(argv[arg_out], "w");
4306   my_assert_not(fout, NULL);
4307
4308   eq_alloc = 128;
4309   g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4310   my_assert_not(g_eqs, NULL);
4311
4312   for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4313     g_label_refs[i].i = -1;
4314     g_label_refs[i].next = NULL;
4315   }
4316
4317   while (fgets(line, sizeof(line), fasm))
4318   {
4319     wordc = 0;
4320     asmln++;
4321
4322     p = sskip(line);
4323     if (*p == 0)
4324       continue;
4325
4326     // get rid of random tabs
4327     for (i = 0; line[i] != 0; i++)
4328       if (line[i] == '\t')
4329         line[i] = ' ';
4330
4331     if (*p == ';')
4332     {
4333       if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4334         goto do_pending_endp; // eww..
4335
4336       if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4337       {
4338         static const char *attrs[] = {
4339           "bp-based frame",
4340           "library function",
4341           "static",
4342           "noreturn",
4343           "thunk",
4344           "fpd=",
4345         };
4346
4347         // parse IDA's attribute-list comment
4348         g_ida_func_attr = 0;
4349         p = sskip(p + 13);
4350
4351         for (; *p != 0; p = sskip(p)) {
4352           for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4353             if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4354               g_ida_func_attr |= 1 << i;
4355               p += strlen(attrs[i]);
4356               break;
4357             }
4358           }
4359           if (i == ARRAY_SIZE(attrs)) {
4360             anote("unparsed IDA attr: %s\n", p);
4361             break;
4362           }
4363           if (IS(attrs[i], "fpd=")) {
4364             p = next_word(words[0], sizeof(words[0]), p);
4365             // ignore for now..
4366           }
4367         }
4368       }
4369       else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4370       {
4371         p += 30;
4372         next_word(words[0], sizeof(words[0]), p);
4373         if (words[0][0] == 0)
4374           aerr("missing name for func chunk?\n");
4375
4376         if (!scanned_ahead) {
4377           add_func_chunk(fasm, words[0], asmln);
4378           func_chunks_sorted = 0;
4379         }
4380       }
4381       else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4382       {
4383         if (func_chunk_i >= 0) {
4384           if (func_chunk_i < func_chunk_cnt
4385             && IS(func_chunks[func_chunk_i].name, g_func))
4386           {
4387             // move on to next chunk
4388             ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4389             if (ret)
4390               aerr("seek failed for '%s' chunk #%d\n",
4391                 g_func, func_chunk_i);
4392             asmln = func_chunks[func_chunk_i].asmln;
4393             func_chunk_i++;
4394           }
4395           else {
4396             if (func_chunk_ret == 0)
4397               aerr("no return from chunk?\n");
4398             fseek(fasm, func_chunk_ret, SEEK_SET);
4399             asmln = func_chunk_ret_ln;
4400             func_chunk_ret = 0;
4401             pending_endp = 1;
4402           }
4403         }
4404       }
4405       else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4406         func_chunks_used = 1;
4407         p += 20;
4408         if (IS_START(g_func, "sub_")) {
4409           unsigned long addr = strtoul(p, NULL, 16);
4410           unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4411           if (addr > f_addr && !scanned_ahead) {
4412             anote("scan_ahead caused by '%s', addr %lx\n",
4413               g_func, addr);
4414             scan_ahead(fasm);
4415             scanned_ahead = 1;
4416             func_chunks_sorted = 0;
4417           }
4418         }
4419       }
4420       continue;
4421     } // *p == ';'
4422
4423 parse_words:
4424     for (i = wordc; i < ARRAY_SIZE(words); i++)
4425       words[i][0] = 0;
4426     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4427       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4428       if (*p == 0 || *p == ';') {
4429         wordc++;
4430         break;
4431       }
4432     }
4433     if (*p != 0 && *p != ';')
4434       aerr("too many words\n");
4435
4436     // alow asm patches in comments
4437     if (*p == ';') {
4438       if (IS_START(p, "; sctpatch:")) {
4439         p = sskip(p + 11);
4440         if (*p == 0 || *p == ';')
4441           continue;
4442         goto parse_words; // lame
4443       }
4444       if (IS_START(p, "; sctproto:")) {
4445         sctproto = strdup(p + 11);
4446       }
4447     }
4448
4449     if (wordc == 0) {
4450       // shouldn't happen
4451       awarn("wordc == 0?\n");
4452       continue;
4453     }
4454
4455     // don't care about this:
4456     if (words[0][0] == '.'
4457         || IS(words[0], "include")
4458         || IS(words[0], "assume") || IS(words[1], "segment")
4459         || IS(words[0], "align"))
4460     {
4461       continue;
4462     }
4463
4464 do_pending_endp:
4465     // do delayed endp processing to collect switch jumptables
4466     if (pending_endp) {
4467       if (in_func && !skip_func && wordc >= 2
4468           && ((words[0][0] == 'd' && words[0][2] == 0)
4469               || (words[1][0] == 'd' && words[1][2] == 0)))
4470       {
4471         i = 1;
4472         if (words[1][0] == 'd' && words[1][2] == 0) {
4473           // label
4474           if (g_func_pd_cnt >= pd_alloc) {
4475             pd_alloc = pd_alloc * 2 + 16;
4476             g_func_pd = realloc(g_func_pd,
4477               sizeof(g_func_pd[0]) * pd_alloc);
4478             my_assert_not(g_func_pd, NULL);
4479           }
4480           pd = &g_func_pd[g_func_pd_cnt];
4481           g_func_pd_cnt++;
4482           memset(pd, 0, sizeof(*pd));
4483           strcpy(pd->label, words[0]);
4484           pd->type = OPT_CONST;
4485           pd->lmod = lmod_from_directive(words[1]);
4486           i = 2;
4487         }
4488         else {
4489           if (pd == NULL) {
4490             if (verbose)
4491               anote("skipping alignment byte?\n");
4492             continue;
4493           }
4494           lmod = lmod_from_directive(words[0]);
4495           if (lmod != pd->lmod)
4496             aerr("lmod change? %d->%d\n", pd->lmod, lmod);
4497         }
4498
4499         if (pd->count_alloc < pd->count + wordc) {
4500           pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
4501           pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
4502           my_assert_not(pd->d, NULL);
4503         }
4504         for (; i < wordc; i++) {
4505           if (IS(words[i], "offset")) {
4506             pd->type = OPT_OFFSET;
4507             i++;
4508           }
4509           p = strchr(words[i], ',');
4510           if (p != NULL)
4511             *p = 0;
4512           if (pd->type == OPT_OFFSET)
4513             pd->d[pd->count].u.label = strdup(words[i]);
4514           else
4515             pd->d[pd->count].u.val = parse_number(words[i]);
4516           pd->d[pd->count].bt_i = -1;
4517           pd->count++;
4518         }
4519         continue;
4520       }
4521
4522       if (in_func && !skip_func)
4523         gen_func(fout, g_fhdr, g_func, pi);
4524
4525       pending_endp = 0;
4526       in_func = 0;
4527       g_ida_func_attr = 0;
4528       skip_warned = 0;
4529       skip_func = 0;
4530       g_func[0] = 0;
4531       func_chunks_used = 0;
4532       func_chunk_i = -1;
4533       if (pi != 0) {
4534         memset(&ops, 0, pi * sizeof(ops[0]));
4535         memset(g_labels, 0, pi * sizeof(g_labels[0]));
4536         pi = 0;
4537       }
4538       g_eqcnt = 0;
4539       for (i = 0; i < g_func_pd_cnt; i++) {
4540         pd = &g_func_pd[i];
4541         if (pd->type == OPT_OFFSET) {
4542           for (j = 0; j < pd->count; j++)
4543             free(pd->d[j].u.label);
4544         }
4545         free(pd->d);
4546         pd->d = NULL;
4547       }
4548       g_func_pd_cnt = 0;
4549       pd = NULL;
4550       if (wordc == 0)
4551         continue;
4552     }
4553
4554     if (IS(words[1], "proc")) {
4555       if (in_func)
4556         aerr("proc '%s' while in_func '%s'?\n",
4557           words[0], g_func);
4558       p = words[0];
4559       if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4560         skip_func = 1;
4561       strcpy(g_func, words[0]);
4562       set_label(0, words[0]);
4563       in_func = 1;
4564       continue;
4565     }
4566
4567     if (IS(words[1], "endp"))
4568     {
4569       if (!in_func)
4570         aerr("endp '%s' while not in_func?\n", words[0]);
4571       if (!IS(g_func, words[0]))
4572         aerr("endp '%s' while in_func '%s'?\n",
4573           words[0], g_func);
4574
4575       if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
4576         && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
4577       {
4578         // import jump
4579         skip_func = 1;
4580       }
4581
4582       if (!skip_func && func_chunks_used) {
4583         // start processing chunks
4584         struct chunk_item *ci, key = { g_func, 0 };
4585
4586         func_chunk_ret = ftell(fasm);
4587         func_chunk_ret_ln = asmln;
4588         if (!func_chunks_sorted) {
4589           qsort(func_chunks, func_chunk_cnt,
4590             sizeof(func_chunks[0]), cmp_chunks);
4591           func_chunks_sorted = 1;
4592         }
4593         ci = bsearch(&key, func_chunks, func_chunk_cnt,
4594                sizeof(func_chunks[0]), cmp_chunks);
4595         if (ci == NULL)
4596           aerr("'%s' needs chunks, but none found\n", g_func);
4597         func_chunk_i = ci - func_chunks;
4598         for (; func_chunk_i > 0; func_chunk_i--)
4599           if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4600             break;
4601
4602         ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4603         if (ret)
4604           aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4605         asmln = func_chunks[func_chunk_i].asmln;
4606         func_chunk_i++;
4607         continue;
4608       }
4609       pending_endp = 1;
4610       continue;
4611     }
4612
4613     if (wordc == 2 && IS(words[1], "ends"))
4614       break;
4615
4616     p = strchr(words[0], ':');
4617     if (p != NULL) {
4618       set_label(pi, words[0]);
4619       continue;
4620     }
4621
4622     if (!in_func || skip_func) {
4623       if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4624         if (verbose)
4625           anote("skipping from '%s'\n", g_labels[pi]);
4626         skip_warned = 1;
4627       }
4628       g_labels[pi][0] = 0;
4629       continue;
4630     }
4631
4632     if (wordc > 1 && IS(words[1], "="))
4633     {
4634       if (wordc != 5)
4635         aerr("unhandled equ, wc=%d\n", wordc);
4636       if (g_eqcnt >= eq_alloc) {
4637         eq_alloc *= 2;
4638         g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4639         my_assert_not(g_eqs, NULL);
4640       }
4641
4642       len = strlen(words[0]);
4643       if (len > sizeof(g_eqs[0].name) - 1)
4644         aerr("equ name too long: %d\n", len);
4645       strcpy(g_eqs[g_eqcnt].name, words[0]);
4646
4647       if (!IS(words[3], "ptr"))
4648         aerr("unhandled equ\n");
4649       if (IS(words[2], "dword"))
4650         g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4651       else if (IS(words[2], "word"))
4652         g_eqs[g_eqcnt].lmod = OPLM_WORD;
4653       else if (IS(words[2], "byte"))
4654         g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4655       else
4656         aerr("bad lmod: '%s'\n", words[2]);
4657
4658       g_eqs[g_eqcnt].offset = parse_number(words[4]);
4659       g_eqcnt++;
4660       continue;
4661     }
4662
4663     if (pi >= ARRAY_SIZE(ops))
4664       aerr("too many ops\n");
4665
4666     parse_op(&ops[pi], words, wordc);
4667
4668     if (sctproto != NULL) {
4669       if (ops[pi].op == OP_CALL)
4670         ops[pi].datap = sctproto;
4671       sctproto = NULL;
4672     }
4673     pi++;
4674   }
4675
4676   fclose(fout);
4677   fclose(fasm);
4678   fclose(g_fhdr);
4679
4680   return 0;
4681 }
4682
4683 // vim:ts=2:shiftwidth=2:expandtab