fixes, standalone works?
[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   char buf[256];
1454
1455   if (pp->argc_reg != 0) {
1456     if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1457       pp_print(buf, sizeof(buf), pp);
1458       ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1459     }
1460     if (pp->argc_stack > 0 && pp->argc_reg != 2)
1461       ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1462         pfx, pp->argc_reg, pp->argc_stack);
1463   }
1464 }
1465
1466 static void check_label_read_ref(struct parsed_op *po, const char *name)
1467 {
1468   const struct parsed_proto *pp;
1469
1470   pp = proto_parse(g_fhdr, name, 0);
1471   if (pp == NULL)
1472     ferr(po, "proto_parse failed for ref '%s'\n", name);
1473
1474   if (pp->is_func)
1475     check_func_pp(po, pp, "ref");
1476 }
1477
1478 static char *out_src_opr(char *buf, size_t buf_size,
1479         struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1480   int is_lea)
1481 {
1482   char tmp1[256], tmp2[256];
1483   char expr[256];
1484   char *p;
1485   int ret;
1486
1487   if (cast == NULL)
1488     cast = "";
1489
1490   switch (popr->type) {
1491   case OPT_REG:
1492     if (is_lea)
1493       ferr(po, "lea from reg?\n");
1494
1495     switch (popr->lmod) {
1496     case OPLM_DWORD:
1497       snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1498       break;
1499     case OPLM_WORD:
1500       snprintf(buf, buf_size, "%s%s",
1501         simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1502       break;
1503     case OPLM_BYTE:
1504       if (popr->name[1] == 'h') // XXX..
1505         snprintf(buf, buf_size, "%s(%s >> 8)",
1506           simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1507       else
1508         snprintf(buf, buf_size, "%s%s",
1509           simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1510       break;
1511     default:
1512       ferr(po, "invalid src lmod: %d\n", popr->lmod);
1513     }
1514     break;
1515
1516   case OPT_REGMEM:
1517     if (is_stack_access(po, popr)) {
1518       stack_frame_access(po, popr, buf, buf_size,
1519         popr->name, cast, 1, is_lea);
1520       break;
1521     }
1522
1523     strcpy(expr, popr->name);
1524     if (strchr(expr, '[')) {
1525       // special case: '[' can only be left for label[reg] form
1526       ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1527       if (ret != 2)
1528         ferr(po, "parse failure for '%s'\n", expr);
1529       if (tmp1[0] == '(') {
1530         // (off_4FFF50+3)[eax]
1531         p = strchr(tmp1 + 1, ')');
1532         if (p == NULL || p[1] != 0)
1533           ferr(po, "parse failure (2) for '%s'\n", expr);
1534         *p = 0;
1535         memmove(tmp1, tmp1 + 1, strlen(tmp1));
1536       }
1537       snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1538     }
1539
1540     // XXX: do we need more parsing?
1541     if (is_lea) {
1542       snprintf(buf, buf_size, "%s", expr);
1543       break;
1544     }
1545
1546     snprintf(buf, buf_size, "%s(%s)",
1547       simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1548     break;
1549
1550   case OPT_LABEL:
1551     check_label_read_ref(po, popr->name);
1552     if (cast[0] == 0 && popr->is_ptr)
1553       cast = "(u32)";
1554
1555     if (is_lea)
1556       snprintf(buf, buf_size, "(u32)&%s", popr->name);
1557     else if (popr->size_lt)
1558       snprintf(buf, buf_size, "%s%s%s%s", cast,
1559         lmod_cast_u_ptr(po, popr->lmod),
1560         popr->is_array ? "" : "&",
1561         popr->name);
1562     else
1563       snprintf(buf, buf_size, "%s%s%s", cast, popr->name,
1564         popr->is_array ? "[0]" : "");
1565     break;
1566
1567   case OPT_OFFSET:
1568     check_label_read_ref(po, popr->name);
1569     if (cast[0] == 0)
1570       cast = "(u32)";
1571     if (is_lea)
1572       ferr(po, "lea an offset?\n");
1573     snprintf(buf, buf_size, "%s&%s", cast, popr->name);
1574     break;
1575
1576   case OPT_CONST:
1577     if (is_lea)
1578       ferr(po, "lea from const?\n");
1579
1580     printf_number(tmp1, sizeof(tmp1), popr->val);
1581     if (popr->val == 0 && strchr(cast, '*'))
1582       snprintf(buf, buf_size, "NULL");
1583     else
1584       snprintf(buf, buf_size, "%s%s",
1585         simplify_cast_num(cast, popr->val), tmp1);
1586     break;
1587
1588   default:
1589     ferr(po, "invalid src type: %d\n", popr->type);
1590   }
1591
1592   return buf;
1593 }
1594
1595 // note: may set is_ptr (we find that out late for ebp frame..)
1596 static char *out_dst_opr(char *buf, size_t buf_size,
1597         struct parsed_op *po, struct parsed_opr *popr)
1598 {
1599   switch (popr->type) {
1600   case OPT_REG:
1601     switch (popr->lmod) {
1602     case OPLM_DWORD:
1603       snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1604       break;
1605     case OPLM_WORD:
1606       // ugh..
1607       snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1608       break;
1609     case OPLM_BYTE:
1610       // ugh..
1611       if (popr->name[1] == 'h') // XXX..
1612         snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1613       else
1614         snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1615       break;
1616     default:
1617       ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1618     }
1619     break;
1620
1621   case OPT_REGMEM:
1622     if (is_stack_access(po, popr)) {
1623       stack_frame_access(po, popr, buf, buf_size,
1624         popr->name, "", 0, 0);
1625       break;
1626     }
1627
1628     return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1629
1630   case OPT_LABEL:
1631     if (popr->size_mismatch)
1632       snprintf(buf, buf_size, "%s%s%s",
1633         lmod_cast_u_ptr(po, popr->lmod),
1634         popr->is_array ? "" : "&", popr->name);
1635     else
1636       snprintf(buf, buf_size, "%s%s", popr->name,
1637         popr->is_array ? "[0]" : "");
1638     break;
1639
1640   default:
1641     ferr(po, "invalid dst type: %d\n", popr->type);
1642   }
1643
1644   return buf;
1645 }
1646
1647 static char *out_src_opr_u32(char *buf, size_t buf_size,
1648         struct parsed_op *po, struct parsed_opr *popr)
1649 {
1650   return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1651 }
1652
1653 static enum parsed_flag_op split_cond(struct parsed_op *po,
1654   enum op_op op, int *is_inv)
1655 {
1656   *is_inv = 0;
1657
1658   switch (op) {
1659   case OP_JO:
1660     return PFO_O;
1661   case OP_JC:
1662     return PFO_C;
1663   case OP_JZ:
1664     return PFO_Z;
1665   case OP_JBE:
1666     return PFO_BE;
1667   case OP_JS:
1668     return PFO_S;
1669   case OP_JP:
1670     return PFO_P;
1671   case OP_JL:
1672     return PFO_L;
1673   case OP_JLE:
1674     return PFO_LE;
1675
1676   case OP_JNO:
1677     *is_inv = 1;
1678     return PFO_O;
1679   case OP_JNC:
1680     *is_inv = 1;
1681     return PFO_C;
1682   case OP_JNZ:
1683     *is_inv = 1;
1684     return PFO_Z;
1685   case OP_JA:
1686     *is_inv = 1;
1687     return PFO_BE;
1688   case OP_JNS:
1689     *is_inv = 1;
1690     return PFO_S;
1691   case OP_JNP:
1692     *is_inv = 1;
1693     return PFO_P;
1694   case OP_JGE:
1695     *is_inv = 1;
1696     return PFO_L;
1697   case OP_JG:
1698     *is_inv = 1;
1699     return PFO_LE;
1700
1701   case OP_ADC:
1702   case OP_SBB:
1703     return PFO_C;
1704
1705   default:
1706     ferr(po, "split_cond: bad op %d\n", op);
1707     return -1;
1708   }
1709 }
1710
1711 static void out_test_for_cc(char *buf, size_t buf_size,
1712   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1713   enum opr_lenmod lmod, const char *expr)
1714 {
1715   const char *cast, *scast;
1716
1717   cast = lmod_cast_u(po, lmod);
1718   scast = lmod_cast_s(po, lmod);
1719
1720   switch (pfo) {
1721   case PFO_Z:
1722   case PFO_BE: // CF=1||ZF=1; CF=0
1723     snprintf(buf, buf_size, "(%s%s %s 0)",
1724       cast, expr, is_inv ? "!=" : "==");
1725     break;
1726
1727   case PFO_S:
1728   case PFO_L: // SF!=OF; OF=0
1729     snprintf(buf, buf_size, "(%s%s %s 0)",
1730       scast, expr, is_inv ? ">=" : "<");
1731     break;
1732
1733   case PFO_LE: // ZF=1||SF!=OF; OF=0
1734     snprintf(buf, buf_size, "(%s%s %s 0)",
1735       scast, expr, is_inv ? ">" : "<=");
1736     break;
1737
1738   default:
1739     ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1740   }
1741 }
1742
1743 static void out_cmp_for_cc(char *buf, size_t buf_size,
1744   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1745 {
1746   const char *cast, *scast, *cast_use;
1747   char buf1[256], buf2[256];
1748   enum opr_lenmod lmod;
1749
1750   if (po->operand[0].lmod != po->operand[1].lmod)
1751     ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1752       po->operand[0].lmod, po->operand[1].lmod);
1753   lmod = po->operand[0].lmod;
1754
1755   cast = lmod_cast_u(po, lmod);
1756   scast = lmod_cast_s(po, lmod);
1757
1758   switch (pfo) {
1759   case PFO_C:
1760   case PFO_Z:
1761   case PFO_BE: // !a
1762     cast_use = cast;
1763     break;
1764
1765   case PFO_S:
1766   case PFO_L: // !ge
1767   case PFO_LE:
1768     cast_use = scast;
1769     break;
1770
1771   default:
1772     ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1773   }
1774
1775   out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1776   out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1777
1778   switch (pfo) {
1779   case PFO_C:
1780     // note: must be unsigned compare
1781     snprintf(buf, buf_size, "(%s %s %s)",
1782       buf1, is_inv ? ">=" : "<", buf2);
1783     break;
1784
1785   case PFO_Z:
1786     snprintf(buf, buf_size, "(%s %s %s)",
1787       buf1, is_inv ? "!=" : "==", buf2);
1788     break;
1789
1790   case PFO_BE: // !a
1791     // note: must be unsigned compare
1792     snprintf(buf, buf_size, "(%s %s %s)",
1793       buf1, is_inv ? ">" : "<=", buf2);
1794
1795     // annoying case
1796     if (is_inv && lmod == OPLM_BYTE
1797       && po->operand[1].type == OPT_CONST
1798       && po->operand[1].val == 0xff)
1799     {
1800       snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1801       snprintf(buf, buf_size, "(0)");
1802     }
1803     break;
1804
1805   // note: must be signed compare
1806   case PFO_S:
1807     snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1808       scast, buf1, buf2, is_inv ? ">=" : "<");
1809     break;
1810
1811   case PFO_L: // !ge
1812     snprintf(buf, buf_size, "(%s %s %s)",
1813       buf1, is_inv ? ">=" : "<", buf2);
1814     break;
1815
1816   case PFO_LE:
1817     snprintf(buf, buf_size, "(%s %s %s)",
1818       buf1, is_inv ? ">" : "<=", buf2);
1819     break;
1820
1821   default:
1822     break;
1823   }
1824 }
1825
1826 static void out_cmp_test(char *buf, size_t buf_size,
1827   struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1828 {
1829   char buf1[256], buf2[256], buf3[256];
1830
1831   if (po->op == OP_TEST) {
1832     if (IS(opr_name(po, 0), opr_name(po, 1))) {
1833       out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1834     }
1835     else {
1836       out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1837       out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1838       snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1839     }
1840     out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1841       po->operand[0].lmod, buf3);
1842   }
1843   else if (po->op == OP_CMP) {
1844     out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1845   }
1846   else
1847     ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1848 }
1849
1850 static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1851         struct parsed_opr *popr2)
1852 {
1853   if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1854     ferr(po, "missing lmod for both operands\n");
1855
1856   if (popr1->lmod == OPLM_UNSPEC)
1857     popr1->lmod = popr2->lmod;
1858   else if (popr2->lmod == OPLM_UNSPEC)
1859     popr2->lmod = popr1->lmod;
1860   else if (popr1->lmod != popr2->lmod) {
1861     if (popr1->type_from_var) {
1862       popr1->size_mismatch = 1;
1863       if (popr1->lmod < popr2->lmod)
1864         popr1->size_lt = 1;
1865       popr1->lmod = popr2->lmod;
1866     }
1867     else if (popr2->type_from_var) {
1868       popr2->size_mismatch = 1;
1869       if (popr2->lmod < popr1->lmod)
1870         popr2->size_lt = 1;
1871       popr2->lmod = popr1->lmod;
1872     }
1873     else
1874       ferr(po, "conflicting lmods: %d vs %d\n",
1875         popr1->lmod, popr2->lmod);
1876   }
1877 }
1878
1879 static const char *op_to_c(struct parsed_op *po)
1880 {
1881   switch (po->op)
1882   {
1883     case OP_ADD:
1884     case OP_ADC:
1885       return "+";
1886     case OP_SUB:
1887     case OP_SBB:
1888       return "-";
1889     case OP_AND:
1890       return "&";
1891     case OP_OR:
1892       return "|";
1893     case OP_XOR:
1894       return "^";
1895     case OP_SHL:
1896       return "<<";
1897     case OP_SHR:
1898       return ">>";
1899     case OP_MUL:
1900     case OP_IMUL:
1901       return "*";
1902     default:
1903       ferr(po, "op_to_c was supplied with %d\n", po->op);
1904   }
1905 }
1906
1907 static void op_set_clear_flag(struct parsed_op *po,
1908   enum op_flags flag_set, enum op_flags flag_clear)
1909 {
1910   po->flags |= flag_set;
1911   po->flags &= ~flag_clear;
1912 }
1913
1914 // last op in stream - unconditional branch or ret
1915 #define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1916   || (ops[_i].flags & (OPF_JMP|OPF_CC)) == OPF_JMP)
1917
1918 static int scan_for_pop(int i, int opcnt, const char *reg,
1919   int magic, int depth, int *maxdepth, int do_flags)
1920 {
1921   const struct parsed_proto *pp;
1922   struct parsed_op *po;
1923   int ret = 0;
1924   int j;
1925
1926   for (; i < opcnt; i++) {
1927     po = &ops[i];
1928     if (po->cc_scratch == magic)
1929       break; // already checked
1930     po->cc_scratch = magic;
1931
1932     if (po->flags & OPF_TAIL) {
1933       if (po->op == OP_CALL) {
1934         pp = proto_parse(g_fhdr, po->operand[0].name, 0);
1935         if (pp != NULL && pp->is_noreturn)
1936           // no stack cleanup for noreturn
1937           return ret;
1938       }
1939       return -1; // deadend
1940     }
1941
1942     if ((po->flags & OPF_RMD)
1943         || (po->op == OP_PUSH && po->argnum != 0)) // arg push
1944       continue;
1945
1946     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
1947       if (po->btj != NULL) {
1948         // jumptable
1949         for (j = 0; j < po->btj->count; j++) {
1950           ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
1951                    depth, maxdepth, do_flags);
1952           if (ret < 0)
1953             return ret; // dead end
1954         }
1955         return ret;
1956       }
1957
1958       if (po->bt_i < 0) {
1959         ferr(po, "dead branch\n");
1960         return -1;
1961       }
1962
1963       if (po->flags & OPF_CC) {
1964         ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
1965                  depth, maxdepth, do_flags);
1966         if (ret < 0)
1967           return ret; // dead end
1968       }
1969       else {
1970         i = po->bt_i - 1;
1971       }
1972       continue;
1973     }
1974
1975     if ((po->op == OP_POP || po->op == OP_PUSH)
1976         && po->operand[0].type == OPT_REG
1977         && IS(po->operand[0].name, reg))
1978     {
1979       if (po->op == OP_PUSH && !(po->flags & OPF_FARG)) {
1980         depth++;
1981         if (depth > *maxdepth)
1982           *maxdepth = depth;
1983         if (do_flags)
1984           op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1985       }
1986       else if (po->op == OP_POP) {
1987         if (depth == 0) {
1988           if (do_flags)
1989             op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
1990           return 1;
1991         }
1992         else {
1993           depth--;
1994           if (depth < 0) // should not happen
1995             ferr(po, "fail with depth\n");
1996           if (do_flags)
1997             op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
1998         }
1999       }
2000     }
2001   }
2002
2003   return ret;
2004 }
2005
2006 // scan for pop starting from 'ret' op (all paths)
2007 static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2008   int flag_set)
2009 {
2010   int found = 0;
2011   int j;
2012
2013   for (; i < opcnt; i++) {
2014     if (!(ops[i].flags & OPF_TAIL))
2015       continue;
2016
2017     for (j = i - 1; j >= 0; j--) {
2018       if (ops[j].flags & OPF_RMD)
2019         continue;
2020       if (ops[j].flags & OPF_JMP)
2021         return -1;
2022
2023       if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2024           && IS(ops[j].operand[0].name, reg))
2025       {
2026         found = 1;
2027         ops[j].flags |= flag_set;
2028         break;
2029       }
2030
2031       if (g_labels[j][0] != 0)
2032         return -1;
2033     }
2034   }
2035
2036   return found ? 0 : -1;
2037 }
2038
2039 // is operand 'opr' modified by parsed_op 'po'?
2040 static int is_opr_modified(const struct parsed_opr *opr,
2041   const struct parsed_op *po)
2042 {
2043   int mask;
2044
2045   if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2046     return 0;
2047
2048   if (opr->type == OPT_REG) {
2049     if (po->op == OP_CALL) {
2050       mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2051       if ((1 << opr->reg) & mask)
2052         return 1;
2053       else
2054         return 0;
2055     }
2056
2057     if (po->operand[0].type == OPT_REG) {
2058       if (po->regmask_dst & (1 << opr->reg))
2059         return 1;
2060       else
2061         return 0;
2062     }
2063   }
2064
2065   return IS(po->operand[0].name, opr->name);
2066 }
2067
2068 // is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2069 static int is_any_opr_modified(const struct parsed_op *po_test,
2070   const struct parsed_op *po, int c_mode)
2071 {
2072   int mask;
2073   int i;
2074
2075   if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2076     return 0;
2077
2078   if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2079     return 0;
2080
2081   if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2082     return 1;
2083
2084   // in reality, it can wreck any register, but in decompiled C
2085   // version it can only overwrite eax or edx:eax
2086   mask = (1 << xAX) | (1 << xDX);
2087   if (!c_mode)
2088     mask |= 1 << xCX;
2089
2090   if (po->op == OP_CALL
2091    && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2092     return 1;
2093
2094   for (i = 0; i < po_test->operand_cnt; i++)
2095     if (IS(po_test->operand[i].name, po->operand[0].name))
2096       return 1;
2097
2098   return 0;
2099 }
2100
2101 // scan for any po_test operand modification in range given
2102 static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2103   int c_mode)
2104 {
2105   if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2106     return -1;
2107
2108   for (; i < opcnt; i++) {
2109     if (is_any_opr_modified(po_test, &ops[i], c_mode))
2110       return i;
2111   }
2112
2113   return -1;
2114 }
2115
2116 // scan for po_test operand[0] modification in range given
2117 static int scan_for_mod_opr0(struct parsed_op *po_test,
2118   int i, int opcnt)
2119 {
2120   for (; i < opcnt; i++) {
2121     if (is_opr_modified(&po_test->operand[0], &ops[i]))
2122       return i;
2123   }
2124
2125   return -1;
2126 }
2127
2128 static int scan_for_flag_set(int i, int magic, int *branched,
2129   int *setters, int *setter_cnt)
2130 {
2131   struct label_ref *lr;
2132   int ret;
2133
2134   while (i >= 0) {
2135     if (ops[i].cc_scratch == magic) {
2136       ferr(&ops[i], "%s looped\n", __func__);
2137       return -1;
2138     }
2139     ops[i].cc_scratch = magic;
2140
2141     if (g_labels[i][0] != 0) {
2142       *branched = 1;
2143
2144       lr = &g_label_refs[i];
2145       for (; lr->next; lr = lr->next) {
2146         ret = scan_for_flag_set(lr->i, magic,
2147                 branched, setters, setter_cnt);
2148         if (ret < 0)
2149           return ret;
2150       }
2151
2152       if (i > 0 && LAST_OP(i - 1)) {
2153         i = lr->i;
2154         continue;
2155       }
2156       ret = scan_for_flag_set(lr->i, magic,
2157               branched, setters, setter_cnt);
2158       if (ret < 0)
2159         return ret;
2160     }
2161     i--;
2162
2163     if (ops[i].flags & OPF_FLAGS) {
2164       setters[*setter_cnt] = i;
2165       (*setter_cnt)++;
2166       return 0;
2167     }
2168
2169     if ((ops[i].flags & OPF_JMP) && !(ops[i].flags & OPF_CC))
2170       return -1;
2171   }
2172
2173   return -1;
2174 }
2175
2176 // scan back for cdq, if anything modifies edx, fail
2177 static int scan_for_cdq_edx(int i)
2178 {
2179   while (i >= 0) {
2180     if (g_labels[i][0] != 0) {
2181       if (g_label_refs[i].next != NULL)
2182         return -1;
2183       if (i > 0 && LAST_OP(i - 1)) {
2184         i = g_label_refs[i].i;
2185         continue;
2186       }
2187       return -1;
2188     }
2189     i--;
2190
2191     if (ops[i].op == OP_CDQ)
2192       return i;
2193
2194     if (ops[i].regmask_dst & (1 << xDX))
2195       return -1;
2196   }
2197
2198   return -1;
2199 }
2200
2201 static int scan_for_reg_clear(int i, int reg)
2202 {
2203   while (i >= 0) {
2204     if (g_labels[i][0] != 0) {
2205       if (g_label_refs[i].next != NULL)
2206         return -1;
2207       if (i > 0 && LAST_OP(i - 1)) {
2208         i = g_label_refs[i].i;
2209         continue;
2210       }
2211       return -1;
2212     }
2213     i--;
2214
2215     if (ops[i].op == OP_XOR
2216      && ops[i].operand[0].lmod == OPLM_DWORD
2217      && ops[i].operand[0].reg == ops[i].operand[1].reg
2218      && ops[i].operand[0].reg == reg)
2219       return i;
2220
2221     if (ops[i].regmask_dst & (1 << reg))
2222       return -1;
2223   }
2224
2225   return -1;
2226 }
2227
2228 // scan for positive, constant esp adjust
2229 static int scan_for_esp_adjust(int i, int opcnt, int *adj)
2230 {
2231   const struct parsed_proto *pp;
2232   struct parsed_op *po;
2233   int first_pop = -1;
2234   *adj = 0;
2235
2236   for (; i < opcnt; i++) {
2237     po = &ops[i];
2238
2239     if (g_labels[i][0] != 0)
2240       break;
2241
2242     if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2243       if (po->operand[1].type != OPT_CONST)
2244         ferr(&ops[i], "non-const esp adjust?\n");
2245       *adj += po->operand[1].val;
2246       if (*adj & 3)
2247         ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2248       return i;
2249     }
2250     else if (po->op == OP_PUSH) {
2251       if (first_pop == -1)
2252         first_pop = -2; // none
2253       *adj -= lmod_bytes(po, po->operand[0].lmod);
2254     }
2255     else if (po->op == OP_POP) {
2256       if (first_pop == -1)
2257         first_pop = i;
2258       *adj += lmod_bytes(po, po->operand[0].lmod);
2259     }
2260     else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2261       if (po->op != OP_CALL)
2262         break;
2263       if (po->operand[0].type != OPT_LABEL)
2264         break;
2265       pp = po->datap;
2266       if (pp != NULL && pp->is_stdcall)
2267         break;
2268     }
2269   }
2270
2271   if (*adj == 4 && first_pop >= 0 && ops[first_pop].op == OP_POP
2272     && ops[first_pop].operand[0].type == OPT_REG
2273     && ops[first_pop].operand[0].reg == xCX)
2274   {
2275     // probably 'pop ecx' was used..
2276     return first_pop;
2277   }
2278
2279   return -1;
2280 }
2281
2282 static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2283 {
2284   struct parsed_op *po;
2285   int j;
2286
2287   if (i < 0)
2288     ferr(ops, "%s: followed bad branch?\n", __func__);
2289
2290   for (; i < opcnt; i++) {
2291     po = &ops[i];
2292     if (po->cc_scratch == magic)
2293       return;
2294     po->cc_scratch = magic;
2295     po->flags |= flags;
2296
2297     if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2298       if (po->btj != NULL) {
2299         // jumptable
2300         for (j = 0; j < po->btj->count; j++)
2301           scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2302         return;
2303       }
2304
2305       scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2306       if (!(po->flags & OPF_CC))
2307         return;
2308     }
2309     if (po->flags & OPF_TAIL)
2310       return;
2311   }
2312 }
2313
2314 static const struct parsed_proto *try_recover_pp(
2315   struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2316 {
2317   const struct parsed_proto *pp = NULL;
2318   char buf[256];
2319   char *p;
2320
2321   // maybe an arg of g_func?
2322   if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2323   {
2324     char ofs_reg[16] = { 0, };
2325     int arg, arg_s, arg_i;
2326     int stack_ra = 0;
2327     int offset = 0;
2328
2329     parse_stack_access(po, opr->name, ofs_reg,
2330       &offset, &stack_ra, NULL);
2331     if (ofs_reg[0] != 0)
2332       ferr(po, "offset reg on arg access?\n");
2333     if (offset <= stack_ra) {
2334       // search who set the stack var instead
2335       if (search_instead != NULL)
2336         *search_instead = 1;
2337       return NULL;
2338     }
2339
2340     arg_i = (offset - stack_ra - 4) / 4;
2341     for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2342       if (g_func_pp->arg[arg].reg != NULL)
2343         continue;
2344       if (arg_s == arg_i)
2345         break;
2346       arg_s++;
2347     }
2348     if (arg == g_func_pp->argc)
2349       ferr(po, "stack arg %d not in prototype?\n", arg_i);
2350
2351     pp = g_func_pp->arg[arg].fptr;
2352     if (pp == NULL)
2353       ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2354     check_func_pp(po, pp, "icall arg");
2355   }
2356   else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2357     // label[index]
2358     p = strchr(opr->name + 1, '[');
2359     memcpy(buf, opr->name, p - opr->name);
2360     buf[p - opr->name] = 0;
2361     pp = proto_parse(g_fhdr, buf, 0);
2362   }
2363   else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2364     pp = proto_parse(g_fhdr, opr->name, 0);
2365     if (pp == NULL)
2366       ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2367     check_func_pp(po, pp, "reg-fptr ref");
2368   }
2369
2370   return pp;
2371 }
2372
2373 static void scan_for_call_type(int i, const struct parsed_opr *opr,
2374   int magic, const struct parsed_proto **pp_found, int *multi)
2375 {
2376   const struct parsed_proto *pp = NULL;
2377   struct parsed_op *po;
2378   struct label_ref *lr;
2379
2380   while (i >= 0) {
2381     if (ops[i].cc_scratch == magic)
2382       return;
2383     ops[i].cc_scratch = magic;
2384
2385     if (g_labels[i][0] != 0) {
2386       lr = &g_label_refs[i];
2387       for (; lr != NULL; lr = lr->next)
2388         scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2389       if (i > 0 && LAST_OP(i - 1))
2390         return;
2391     }
2392     i--;
2393
2394     if (!(ops[i].flags & OPF_DATA))
2395       continue;
2396     if (!is_opr_modified(opr, &ops[i]))
2397       continue;
2398     if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2399       // most probably trashed by some processing
2400       *pp_found = NULL;
2401       return;
2402     }
2403
2404     opr = &ops[i].operand[1];
2405     if (opr->type != OPT_REG)
2406       break;
2407   }
2408
2409   po = (i >= 0) ? &ops[i] : ops;
2410
2411   if (i < 0) {
2412     // reached the top - can only be an arg-reg
2413     if (opr->type != OPT_REG)
2414       return;
2415
2416     for (i = 0; i < g_func_pp->argc; i++) {
2417       if (g_func_pp->arg[i].reg == NULL)
2418         continue;
2419       if (IS(opr->name, g_func_pp->arg[i].reg))
2420         break;
2421     }
2422     if (i == g_func_pp->argc)
2423       return;
2424     pp = g_func_pp->arg[i].fptr;
2425     if (pp == NULL)
2426       ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2427         i + 1, g_func_pp->arg[i].reg);
2428     check_func_pp(po, pp, "icall reg-arg");
2429   }
2430   else
2431     pp = try_recover_pp(po, opr, NULL);
2432
2433   if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2434     if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2435       || (*pp_found)->is_stdcall != pp->is_stdcall
2436       || (*pp_found)->is_fptr != pp->is_fptr
2437       || (*pp_found)->argc != pp->argc
2438       || (*pp_found)->argc_reg != pp->argc_reg
2439       || (*pp_found)->argc_stack != pp->argc_stack)
2440     {
2441       ferr(po, "icall: parsed_proto mismatch\n");
2442     }
2443     *multi = 1;
2444   }
2445   if (pp != NULL)
2446     *pp_found = pp;
2447 }
2448
2449 static const struct parsed_proto *resolve_icall(int i, int opcnt,
2450   int *multi_src)
2451 {
2452   const struct parsed_proto *pp = NULL;
2453   int search_advice = 0;
2454
2455   *multi_src = 0;
2456
2457   switch (ops[i].operand[0].type) {
2458   case OPT_REGMEM:
2459   case OPT_LABEL:
2460   case OPT_OFFSET:
2461     pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
2462     if (!search_advice)
2463       break;
2464     // fallthrough
2465   default:
2466     scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
2467       multi_src);
2468     break;
2469   }
2470
2471   return pp;
2472 }
2473
2474 static int collect_call_args_r(struct parsed_op *po, int i,
2475   struct parsed_proto *pp, int *regmask, int *save_arg_vars, int arg,
2476   int magic, int need_op_saving, int may_reuse)
2477 {
2478   struct parsed_proto *pp_tmp;
2479   struct label_ref *lr;
2480   int need_to_save_current;
2481   int ret = 0;
2482   int j;
2483
2484   if (i < 0) {
2485     ferr(po, "dead label encountered\n");
2486     return -1;
2487   }
2488
2489   for (; arg < pp->argc; arg++)
2490     if (pp->arg[arg].reg == NULL)
2491       break;
2492   magic = (magic & 0xffffff) | (arg << 24);
2493
2494   for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
2495   {
2496     if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2497       if (ops[j].cc_scratch != magic) {
2498         ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2499            pp->name);
2500         return -1;
2501       }
2502       // ok: have already been here
2503       return 0;
2504     }
2505     ops[j].cc_scratch = magic;
2506
2507     if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2508       lr = &g_label_refs[j];
2509       if (lr->next != NULL)
2510         need_op_saving = 1;
2511       for (; lr->next; lr = lr->next) {
2512         if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2513           may_reuse = 1;
2514         ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2515                 arg, magic, need_op_saving, may_reuse);
2516         if (ret < 0)
2517           return ret;
2518       }
2519
2520       if ((ops[lr->i].flags & (OPF_JMP|OPF_CC)) != OPF_JMP)
2521         may_reuse = 1;
2522       if (j > 0 && LAST_OP(j - 1)) {
2523         // follow last branch in reverse
2524         j = lr->i;
2525         continue;
2526       }
2527       need_op_saving = 1;
2528       ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2529                arg, magic, need_op_saving, may_reuse);
2530       if (ret < 0)
2531         return ret;
2532     }
2533     j--;
2534
2535     if (ops[j].op == OP_CALL)
2536     {
2537       if (pp->is_unresolved)
2538         break;
2539
2540       pp_tmp = ops[j].datap;
2541       if (pp_tmp == NULL)
2542         ferr(po, "arg collect hit unparsed call '%s'\n",
2543           ops[j].operand[0].name);
2544       if (may_reuse && pp_tmp->argc_stack > 0)
2545         ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2546           arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2547     }
2548     else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2549       if (pp->is_unresolved)
2550         break;
2551
2552       ferr(po, "arg collect %d/%d hit esp adjust\n",
2553         arg, pp->argc);
2554     }
2555     else if (ops[j].op == OP_POP) {
2556       if (pp->is_unresolved)
2557         break;
2558
2559       ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2560     }
2561     else if ((ops[j].flags & (OPF_JMP|OPF_CC)) == (OPF_JMP|OPF_CC))
2562     {
2563       if (pp->is_unresolved)
2564         break;
2565
2566       may_reuse = 1;
2567     }
2568     else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2569     {
2570       if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
2571         break;
2572
2573       pp->arg[arg].datap = &ops[j];
2574       need_to_save_current = 0;
2575       if (!need_op_saving) {
2576         ret = scan_for_mod(&ops[j], j + 1, i, 1);
2577         need_to_save_current = (ret >= 0);
2578       }
2579       if (need_op_saving || need_to_save_current) {
2580         // mark this push as one that needs operand saving
2581         ops[j].flags &= ~OPF_RMD;
2582         if (ops[j].argnum == 0) {
2583           ops[j].argnum = arg + 1;
2584           *save_arg_vars |= 1 << arg;
2585         }
2586         else if (ops[j].argnum < arg + 1)
2587           ferr(&ops[j], "argnum conflict (%d<%d) for '%s'\n",
2588             ops[j].argnum, arg + 1, pp->name);
2589       }
2590       else if (ops[j].argnum == 0)
2591         ops[j].flags |= OPF_RMD;
2592
2593       // some PUSHes are reused by different calls on other branches,
2594       // but that can't happen if we didn't branch, so they
2595       // can be removed from future searches (handles nested calls)
2596       if (!may_reuse)
2597         ops[j].flags |= OPF_FARG;
2598
2599       ops[j].flags &= ~OPF_RSAVE;
2600
2601       arg++;
2602       if (!pp->is_unresolved) {
2603         // next arg
2604         for (; arg < pp->argc; arg++)
2605           if (pp->arg[arg].reg == NULL)
2606             break;
2607       }
2608       magic = (magic & 0xffffff) | (arg << 24);
2609
2610       // tracking reg usage
2611       if (ops[j].operand[0].type == OPT_REG)
2612         *regmask |= 1 << ops[j].operand[0].reg;
2613     }
2614   }
2615
2616   if (arg < pp->argc) {
2617     ferr(po, "arg collect failed for '%s': %d/%d\n",
2618       pp->name, arg, pp->argc);
2619     return -1;
2620   }
2621
2622   return arg;
2623 }
2624
2625 static int collect_call_args(struct parsed_op *po, int i,
2626   struct parsed_proto *pp, int *regmask, int *save_arg_vars,
2627   int magic)
2628 {
2629   int ret;
2630   int a;
2631
2632   ret = collect_call_args_r(po, i, pp, regmask, save_arg_vars,
2633           0, magic, 0, 0);
2634   if (ret < 0)
2635     return ret;
2636
2637   if (pp->is_unresolved) {
2638     pp->argc += ret;
2639     pp->argc_stack += ret;
2640     for (a = 0; a < pp->argc; a++)
2641       if (pp->arg[a].type.name == NULL)
2642         pp->arg[a].type.name = strdup("int");
2643   }
2644
2645   return ret;
2646 }
2647
2648 static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
2649 {
2650   int i;
2651
2652   for (i = 0; i < pp->argc; i++)
2653     if (pp->arg[i].reg == NULL)
2654       break;
2655
2656   if (pp->argc_stack)
2657     memmove(&pp->arg[i + 1], &pp->arg[i],
2658       sizeof(pp->arg[0]) * pp->argc_stack);
2659   memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
2660   pp->arg[i].reg = strdup(reg);
2661   pp->arg[i].type.name = strdup("int");
2662   pp->argc++;
2663   pp->argc_reg++;
2664 }
2665
2666 static void add_label_ref(struct label_ref *lr, int op_i)
2667 {
2668   struct label_ref *lr_new;
2669
2670   if (lr->i == -1) {
2671     lr->i = op_i;
2672     return;
2673   }
2674
2675   lr_new = calloc(1, sizeof(*lr_new));
2676   lr_new->i = op_i;
2677   lr_new->next = lr->next;
2678   lr->next = lr_new;
2679 }
2680
2681 static void output_std_flags(FILE *fout, struct parsed_op *po,
2682   int *pfomask, const char *dst_opr_text)
2683 {
2684   if (*pfomask & (1 << PFO_Z)) {
2685     fprintf(fout, "\n  cond_z = (%s%s == 0);",
2686       lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2687     *pfomask &= ~(1 << PFO_Z);
2688   }
2689   if (*pfomask & (1 << PFO_S)) {
2690     fprintf(fout, "\n  cond_s = (%s%s < 0);",
2691       lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2692     *pfomask &= ~(1 << PFO_S);
2693   }
2694 }
2695
2696 static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
2697   int is_noreturn)
2698 {
2699   if (pp->is_fastcall)
2700     fprintf(fout, "__fastcall ");
2701   else if (pp->is_stdcall && pp->argc_reg == 0)
2702     fprintf(fout, "__stdcall ");
2703   if (pp->is_noreturn || is_noreturn)
2704     fprintf(fout, "noreturn ");
2705 }
2706
2707 static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2708 {
2709   struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2710   struct parsed_opr *last_arith_dst = NULL;
2711   char buf1[256], buf2[256], buf3[256], cast[64];
2712   const struct parsed_proto *pp_c;
2713   struct parsed_proto *pp, *pp_tmp;
2714   struct parsed_data *pd;
2715   const char *tmpname;
2716   enum parsed_flag_op pfo;
2717   int save_arg_vars = 0;
2718   int cmp_result_vars = 0;
2719   int need_mul_var = 0;
2720   int had_decl = 0;
2721   int label_pending = 0;
2722   int regmask_save = 0;
2723   int regmask_arg = 0;
2724   int regmask_now = 0;
2725   int regmask_init = 0;
2726   int regmask = 0;
2727   int pfomask = 0;
2728   int found = 0;
2729   int depth = 0;
2730   int no_output;
2731   int i, j, l;
2732   int dummy;
2733   int arg;
2734   int reg;
2735   int ret;
2736
2737   g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2738   g_stack_frame_used = 0;
2739
2740   g_func_pp = proto_parse(fhdr, funcn, 0);
2741   if (g_func_pp == NULL)
2742     ferr(ops, "proto_parse failed for '%s'\n", funcn);
2743
2744   fprintf(fout, "%s ", g_func_pp->ret_type.name);
2745   output_pp_attrs(fout, g_func_pp, g_ida_func_attr & IDAFA_NORETURN);
2746   fprintf(fout, "%s(", funcn);
2747
2748   for (i = 0; i < g_func_pp->argc; i++) {
2749     if (i > 0)
2750       fprintf(fout, ", ");
2751     if (g_func_pp->arg[i].fptr != NULL) {
2752       // func pointer..
2753       pp = g_func_pp->arg[i].fptr;
2754       fprintf(fout, "%s (", pp->ret_type.name);
2755       output_pp_attrs(fout, pp, 0);
2756       fprintf(fout, "*a%d)(", i + 1);
2757       for (j = 0; j < pp->argc; j++) {
2758         if (j > 0)
2759           fprintf(fout, ", ");
2760         if (pp->arg[j].fptr)
2761           ferr(ops, "nested fptr\n");
2762         fprintf(fout, "%s", pp->arg[j].type.name);
2763       }
2764       fprintf(fout, ")");
2765     }
2766     else {
2767       fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
2768     }
2769     if (g_func_pp->arg[i].reg != NULL) {
2770       reg = char_array_i(regs_r32,
2771               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
2772       if (reg < 0)
2773         ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
2774       regmask_arg |= 1 << reg;
2775     }
2776   }
2777   if (g_func_pp->is_vararg) {
2778     if (i > 0)
2779       fprintf(fout, ", ");
2780     fprintf(fout, "...");
2781   }
2782
2783   fprintf(fout, ")\n{\n");
2784
2785   // pass1:
2786   // - handle ebp/esp frame, remove ops related to it
2787   if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
2788       && ops[1].op == OP_MOV
2789       && IS(opr_name(&ops[1], 0), "ebp")
2790       && IS(opr_name(&ops[1], 1), "esp"))
2791   {
2792     int ecx_push = 0;
2793
2794     g_bp_frame = 1;
2795     ops[0].flags |= OPF_RMD;
2796     ops[1].flags |= OPF_RMD;
2797     i = 2;
2798
2799     if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
2800       g_stack_fsz = opr_const(&ops[2], 1);
2801       ops[2].flags |= OPF_RMD;
2802       i++;
2803     }
2804     else {
2805       // another way msvc builds stack frame..
2806       i = 2;
2807       while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
2808         g_stack_fsz += 4;
2809         ops[i].flags |= OPF_RMD;
2810         ecx_push++;
2811         i++;
2812       }
2813       // and another way..
2814       if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
2815           && ops[i].operand[1].type == OPT_CONST
2816           && ops[i + 1].op == OP_CALL
2817           && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
2818       {
2819         g_stack_fsz += ops[i].operand[1].val;
2820         ops[i].flags |= OPF_RMD;
2821         i++;
2822         ops[i].flags |= OPF_RMD;
2823         i++;
2824       }
2825     }
2826
2827     found = 0;
2828     do {
2829       for (; i < opcnt; i++)
2830         if (ops[i].op == OP_RET)
2831           break;
2832       if (i == opcnt && (ops[i - 1].flags & OPF_JMP) && found)
2833         break;
2834
2835       if (ops[i - 1].op == OP_POP && IS(opr_name(&ops[i - 1], 0), "ebp"))
2836         ops[i - 1].flags |= OPF_RMD;
2837       else if (!(g_ida_func_attr & IDAFA_NORETURN))
2838         ferr(&ops[i - 1], "'pop ebp' expected\n");
2839
2840       if (g_stack_fsz != 0) {
2841         if (ops[i - 2].op == OP_MOV
2842             && IS(opr_name(&ops[i - 2], 0), "esp")
2843             && IS(opr_name(&ops[i - 2], 1), "ebp"))
2844         {
2845           ops[i - 2].flags |= OPF_RMD;
2846         }
2847         else if (!(g_ida_func_attr & IDAFA_NORETURN))
2848           ferr(&ops[i - 2], "esp restore expected\n");
2849
2850         if (ecx_push && ops[i - 3].op == OP_POP
2851           && IS(opr_name(&ops[i - 3], 0), "ecx"))
2852         {
2853           ferr(&ops[i - 3], "unexpected ecx pop\n");
2854         }
2855       }
2856
2857       found = 1;
2858       i++;
2859     } while (i < opcnt);
2860   }
2861   else {
2862     for (i = 0; i < opcnt; i++) {
2863       if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
2864         break;
2865       if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
2866         && ops[i].operand[1].type == OPT_CONST)
2867       {
2868         g_sp_frame = 1;
2869         break;
2870       }
2871     }
2872
2873     if (g_sp_frame)
2874     {
2875       g_stack_fsz = ops[i].operand[1].val;
2876       ops[i].flags |= OPF_RMD;
2877
2878       i++;
2879       do {
2880         for (; i < opcnt; i++)
2881           if (ops[i].op == OP_RET)
2882             break;
2883         if (ops[i - 1].op != OP_ADD
2884             || !IS(opr_name(&ops[i - 1], 0), "esp")
2885             || ops[i - 1].operand[1].type != OPT_CONST
2886             || ops[i - 1].operand[1].val != g_stack_fsz)
2887           ferr(&ops[i - 1], "'add esp' expected\n");
2888         ops[i - 1].flags |= OPF_RMD;
2889
2890         i++;
2891       } while (i < opcnt);
2892     }
2893   }
2894
2895   // pass2:
2896   // - parse calls with labels
2897   // - resolve all branches
2898   for (i = 0; i < opcnt; i++)
2899   {
2900     po = &ops[i];
2901     po->bt_i = -1;
2902     po->btj = NULL;
2903
2904     if (po->flags & OPF_RMD)
2905       continue;
2906
2907     if (po->op == OP_CALL) {
2908       pp = NULL;
2909
2910       if (po->operand[0].type == OPT_LABEL) {
2911         tmpname = opr_name(po, 0);
2912         if (IS_START(tmpname, "loc_"))
2913           ferr(po, "call to loc_*\n");
2914         pp_c = proto_parse(fhdr, tmpname, 0);
2915         if (pp_c == NULL)
2916           ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2917
2918         pp = proto_clone(pp_c);
2919         my_assert_not(pp, NULL);
2920       }
2921       else if (po->datap != NULL) {
2922         pp = calloc(1, sizeof(*pp));
2923         my_assert_not(pp, NULL);
2924
2925         ret = parse_protostr(po->datap, pp);
2926         if (ret < 0)
2927           ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
2928         free(po->datap);
2929         po->datap = NULL;
2930       }
2931
2932       if (pp != NULL) {
2933         if (pp->is_fptr)
2934           check_func_pp(po, pp, "fptr var call");
2935         if (pp->is_noreturn)
2936           po->flags |= OPF_TAIL;
2937         po->datap = pp;
2938       }
2939       continue;
2940     }
2941
2942     if (!(po->flags & OPF_JMP) || po->op == OP_RET)
2943       continue;
2944
2945     if (po->operand[0].type == OPT_REGMEM) {
2946       char *p = strchr(po->operand[0].name, '[');
2947       if (p == NULL)
2948         goto tailcall;
2949       ret = p - po->operand[0].name;
2950       strncpy(buf1, po->operand[0].name, ret);
2951       buf1[ret] = 0;
2952
2953       for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2954         if (IS(g_func_pd[j].label, buf1)) {
2955           pd = &g_func_pd[j];
2956           break;
2957         }
2958       }
2959       if (pd == NULL)
2960         //ferr(po, "label '%s' not parsed?\n", buf1);
2961         goto tailcall;
2962       if (pd->type != OPT_OFFSET)
2963         ferr(po, "label '%s' with non-offset data?\n", buf1);
2964
2965       // find all labels, link
2966       for (j = 0; j < pd->count; j++) {
2967         for (l = 0; l < opcnt; l++) {
2968           if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
2969             add_label_ref(&g_label_refs[l], i);
2970             pd->d[j].bt_i = l;
2971             break;
2972           }
2973         }
2974       }
2975
2976       po->btj = pd;
2977       continue;
2978     }
2979
2980     for (l = 0; l < opcnt; l++) {
2981       if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
2982         add_label_ref(&g_label_refs[l], i);
2983         po->bt_i = l;
2984         break;
2985       }
2986     }
2987
2988     if (po->bt_i != -1)
2989       continue;
2990
2991     if (po->operand[0].type == OPT_LABEL)
2992       // assume tail call
2993       goto tailcall;
2994
2995     ferr(po, "unhandled branch\n");
2996
2997 tailcall:
2998     po->op = OP_CALL;
2999     po->flags |= OPF_TAIL;
3000     i--; // reprocess
3001   }
3002
3003   // pass3:
3004   // - remove dead labels
3005   // - process calls
3006   for (i = 0; i < opcnt; i++)
3007   {
3008     if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
3009       g_labels[i][0] = 0;
3010
3011     po = &ops[i];
3012     if (po->flags & OPF_RMD)
3013       continue;
3014
3015     if (po->op == OP_CALL)
3016     {
3017       tmpname = opr_name(po, 0);
3018       pp = po->datap;
3019       if (pp == NULL)
3020       {
3021         // indirect call
3022         pp_c = resolve_icall(i, opcnt, &l);
3023         if (pp_c != NULL) {
3024           pp = proto_clone(pp_c);
3025           my_assert_not(pp, NULL);
3026           if (l)
3027             // not resolved just to single func
3028             pp->is_fptr = 1;
3029         }
3030         if (pp == NULL) {
3031           pp = calloc(1, sizeof(*pp));
3032           my_assert_not(pp, NULL);
3033           pp->is_fptr = 1;
3034           ret = scan_for_esp_adjust(i + 1, opcnt, &j);
3035           if (ret < 0) {
3036             if (!g_allow_regfunc)
3037               ferr(po, "non-__cdecl indirect call unhandled yet\n");
3038             pp->is_unresolved = 1;
3039             j = 0;
3040           }
3041           j /= 4;
3042           if (j > ARRAY_SIZE(pp->arg))
3043             ferr(po, "esp adjust too large: %d\n", j);
3044           pp->ret_type.name = strdup("int");
3045           pp->argc = pp->argc_stack = j;
3046           for (arg = 0; arg < pp->argc; arg++)
3047             pp->arg[arg].type.name = strdup("int");
3048         }
3049         po->datap = pp;
3050       }
3051
3052       // look for and make use of esp adjust
3053       ret = -1;
3054       if (!pp->is_stdcall && pp->argc_stack > 0)
3055         ret = scan_for_esp_adjust(i + 1, opcnt, &j);
3056       if (ret >= 0) {
3057         if (pp->is_vararg) {
3058           if (j / 4 < pp->argc_stack)
3059             ferr(po, "esp adjust is too small: %x < %x\n",
3060               j, pp->argc_stack * 4);
3061           // modify pp to make it have varargs as normal args
3062           arg = pp->argc;
3063           pp->argc += j / 4 - pp->argc_stack;
3064           for (; arg < pp->argc; arg++) {
3065             pp->arg[arg].type.name = strdup("int");
3066             pp->argc_stack++;
3067           }
3068           if (pp->argc > ARRAY_SIZE(pp->arg))
3069             ferr(po, "too many args for '%s'\n", tmpname);
3070         }
3071         if (pp->argc_stack != j / 4)
3072           ferr(po, "stack tracking failed for '%s': %x %x\n",
3073             tmpname, pp->argc_stack * 4, j);
3074
3075         ops[ret].flags |= OPF_RMD;
3076         // a bit of a hack, but deals with use of
3077         // single adj for multiple calls
3078         ops[ret].operand[1].val -= j;
3079       }
3080       else if (pp->is_vararg)
3081         ferr(po, "missing esp_adjust for vararg func '%s'\n",
3082           pp->name);
3083
3084       if (!pp->is_unresolved) {
3085         // since we know the args, collect them
3086         collect_call_args(po, i, pp, &regmask, &save_arg_vars,
3087           i + opcnt * 2);
3088       }
3089
3090       if (strstr(pp->ret_type.name, "int64"))
3091         need_mul_var = 1;
3092     }
3093   }
3094
3095   // pass4:
3096   // - find POPs for PUSHes, rm both
3097   // - scan for all used registers
3098   // - find flag set ops for their users
3099   // - do unreselved calls
3100   // - declare indirect functions
3101   for (i = 0; i < opcnt; i++) {
3102     po = &ops[i];
3103     if (po->flags & OPF_RMD)
3104       continue;
3105
3106     if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3107       reg = po->operand[0].reg;
3108       if (!(regmask & (1 << reg)))
3109         // not a reg save after all, rerun scan_for_pop
3110         po->flags &= ~OPF_RSAVE;
3111       else
3112         regmask_save |= 1 << reg;
3113     }
3114
3115     if (po->op == OP_PUSH
3116         && po->argnum == 0 && !(po->flags & OPF_RSAVE)
3117         && po->operand[0].type == OPT_REG)
3118     {
3119       reg = po->operand[0].reg;
3120       if (reg < 0)
3121         ferr(po, "reg not set for push?\n");
3122
3123       depth = 0;
3124       ret = scan_for_pop(i + 1, opcnt,
3125               po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3126       if (ret == 1) {
3127         if (depth > 1)
3128           ferr(po, "too much depth: %d\n", depth);
3129
3130         po->flags |= OPF_RMD;
3131         scan_for_pop(i + 1, opcnt, po->operand[0].name,
3132           i + opcnt * 4, 0, &depth, 1);
3133         continue;
3134       }
3135       ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3136       if (ret == 0) {
3137         arg = OPF_RMD;
3138         if (regmask & (1 << reg)) {
3139           if (regmask_save & (1 << reg))
3140             ferr(po, "%s already saved?\n", po->operand[0].name);
3141           arg = OPF_RSAVE;
3142         }
3143         po->flags |= arg;
3144         scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3145         continue;
3146       }
3147     }
3148
3149     regmask_now = po->regmask_src | po->regmask_dst;
3150     if (regmask_now & (1 << xBP)) {
3151       if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3152         if (po->regmask_dst & (1 << xBP))
3153           // compiler decided to drop bp frame and use ebp as scratch
3154           scan_fwd_set_flags(i, opcnt, i + opcnt * 5, OPF_EBP_S);
3155         else
3156           regmask_now &= ~(1 << xBP);
3157       }
3158     }
3159
3160     regmask |= regmask_now;
3161
3162     if (po->flags & OPF_CC)
3163     {
3164       int setters[16], cnt = 0, branched = 0;
3165
3166       ret = scan_for_flag_set(i, i + opcnt * 6,
3167               &branched, setters, &cnt);
3168       if (ret < 0 || cnt <= 0)
3169         ferr(po, "unable to trace flag setter(s)\n");
3170       if (cnt > ARRAY_SIZE(setters))
3171         ferr(po, "too many flag setters\n");
3172
3173       pfo = split_cond(po, po->op, &dummy);
3174       for (j = 0; j < cnt; j++)
3175       {
3176         tmp_op = &ops[setters[j]]; // flag setter
3177         pfomask = 0;
3178
3179         // to get nicer code, we try to delay test and cmp;
3180         // if we can't because of operand modification, or if we
3181         // have math op, or branch, make it calculate flags explicitly
3182         if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP) {
3183           if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
3184             pfomask = 1 << pfo;
3185         }
3186         else if (tmp_op->op == OP_CMPS) {
3187           pfomask = 1 << PFO_Z;
3188         }
3189         else {
3190           // see if we'll be able to handle based on op result
3191           if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3192                && pfo != PFO_Z && pfo != PFO_S && pfo != PFO_P)
3193               || branched
3194               || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3195             pfomask = 1 << pfo;
3196         }
3197         if (pfomask) {
3198           tmp_op->pfomask |= pfomask;
3199           cmp_result_vars |= pfomask;
3200         }
3201         // note: may overwrite, currently not a problem
3202         po->datap = tmp_op;
3203       }
3204
3205       if (po->op == OP_ADC || po->op == OP_SBB)
3206         cmp_result_vars |= 1 << PFO_C;
3207     }
3208     else if (po->op == OP_MUL
3209       || (po->op == OP_IMUL && po->operand_cnt == 1))
3210     {
3211       need_mul_var = 1;
3212     }
3213     else if (po->op == OP_CALL) {
3214       pp = po->datap;
3215       if (pp == NULL)
3216         ferr(po, "NULL pp\n");
3217
3218       if (pp->is_unresolved) {
3219         int regmask_stack = 0;
3220         collect_call_args(po, i, pp, &regmask, &save_arg_vars,
3221           i + opcnt * 2);
3222
3223         // this is pretty rough guess:
3224         // see ecx and edx were pushed (and not their saved versions)
3225         for (arg = 0; arg < pp->argc; arg++) {
3226           if (pp->arg[arg].reg != NULL)
3227             continue;
3228
3229           tmp_op = pp->arg[arg].datap;
3230           if (tmp_op == NULL)
3231             ferr(po, "parsed_op missing for arg%d\n", arg);
3232           if (tmp_op->argnum == 0 && tmp_op->operand[0].type == OPT_REG)
3233             regmask_stack |= 1 << tmp_op->operand[0].reg;
3234         }
3235
3236         if (!((regmask_stack & (1 << xCX))
3237           && (regmask_stack & (1 << xDX))))
3238         {
3239           if (pp->argc_stack != 0
3240            || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
3241           {
3242             pp_insert_reg_arg(pp, "ecx");
3243             pp->is_fastcall = 1;
3244             regmask_init |= 1 << xCX;
3245             regmask |= 1 << xCX;
3246           }
3247           if (pp->argc_stack != 0
3248            || ((regmask | regmask_arg) & (1 << xDX)))
3249           {
3250             pp_insert_reg_arg(pp, "edx");
3251             regmask_init |= 1 << xDX;
3252             regmask |= 1 << xDX;
3253           }
3254         }
3255
3256         // note: __cdecl doesn't fall into is_unresolved category
3257         if (pp->argc_stack > 0)
3258           pp->is_stdcall = 1;
3259       }
3260
3261       for (arg = 0; arg < pp->argc; arg++) {
3262         if (pp->arg[arg].reg != NULL) {
3263           reg = char_array_i(regs_r32,
3264                   ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
3265           if (reg < 0)
3266             ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
3267           if (!(regmask & (1 << reg))) {
3268             regmask_init |= 1 << reg;
3269             regmask |= 1 << reg;
3270           }
3271         }
3272       }
3273
3274       if (pp->is_fptr) {
3275         if (pp->name[0] != 0) {
3276           memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
3277           memcpy(pp->name, "i_", 2);
3278
3279           // might be declared already
3280           found = 0;
3281           for (j = 0; j < i; j++) {
3282             if (ops[j].op == OP_CALL && (pp_tmp = ops[j].datap)) {
3283               if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
3284                 found = 1;
3285                 break;
3286               }
3287             }
3288           }
3289           if (found)
3290             continue;
3291         }
3292         else
3293           snprintf(pp->name, sizeof(pp->name), "icall%d", i);
3294
3295         fprintf(fout, "  %s (", pp->ret_type.name);
3296         output_pp_attrs(fout, pp, 0);
3297         fprintf(fout, "*%s)(", pp->name);
3298         for (j = 0; j < pp->argc; j++) {
3299           if (j > 0)
3300             fprintf(fout, ", ");
3301           fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3302         }
3303         fprintf(fout, ");\n");
3304       }
3305     }
3306     else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3307       regmask |= 1 << xAX;
3308   }
3309
3310   // pass4:
3311   // - confirm regmask_save, it might have been reduced
3312   if (regmask_save != 0)
3313   {
3314     regmask_save = 0;
3315     for (i = 0; i < opcnt; i++) {
3316       po = &ops[i];
3317       if (po->flags & OPF_RMD)
3318         continue;
3319
3320       if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
3321         regmask_save |= 1 << po->operand[0].reg;
3322     }
3323   }
3324
3325
3326   // output LUTs/jumptables
3327   for (i = 0; i < g_func_pd_cnt; i++) {
3328     pd = &g_func_pd[i];
3329     fprintf(fout, "  static const ");
3330     if (pd->type == OPT_OFFSET) {
3331       fprintf(fout, "void *jt_%s[] =\n    { ", pd->label);
3332
3333       for (j = 0; j < pd->count; j++) {
3334         if (j > 0)
3335           fprintf(fout, ", ");
3336         fprintf(fout, "&&%s", pd->d[j].u.label);
3337       }
3338     }
3339     else {
3340       fprintf(fout, "%s %s[] =\n    { ",
3341         lmod_type_u(ops, pd->lmod), pd->label);
3342
3343       for (j = 0; j < pd->count; j++) {
3344         if (j > 0)
3345           fprintf(fout, ", ");
3346         fprintf(fout, "%u", pd->d[j].u.val);
3347       }
3348     }
3349     fprintf(fout, " };\n");
3350   }
3351
3352   // declare stack frame, va_arg
3353   if (g_stack_fsz)
3354     fprintf(fout, "  union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3355       (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3356
3357   if (g_func_pp->is_vararg)
3358     fprintf(fout, "  va_list ap;\n");
3359
3360   // declare arg-registers
3361   for (i = 0; i < g_func_pp->argc; i++) {
3362     if (g_func_pp->arg[i].reg != NULL) {
3363       reg = char_array_i(regs_r32,
3364               ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3365       if (regmask & (1 << reg)) {
3366         fprintf(fout, "  u32 %s = (u32)a%d;\n",
3367           g_func_pp->arg[i].reg, i + 1);
3368       }
3369       else
3370         fprintf(fout, "  // %s = a%d; // unused\n",
3371           g_func_pp->arg[i].reg, i + 1);
3372       had_decl = 1;
3373     }
3374   }
3375
3376   regmask_now = regmask & ~regmask_arg;
3377   regmask_now &= ~(1 << xSP);
3378   if (regmask_now) {
3379     for (reg = 0; reg < 8; reg++) {
3380       if (regmask_now & (1 << reg)) {
3381         fprintf(fout, "  u32 %s", regs_r32[reg]);
3382         if (regmask_init & (1 << reg))
3383           fprintf(fout, " = 0");
3384         fprintf(fout, ";\n");
3385         had_decl = 1;
3386       }
3387     }
3388   }
3389
3390   if (regmask_save) {
3391     for (reg = 0; reg < 8; reg++) {
3392       if (regmask_save & (1 << reg)) {
3393         fprintf(fout, "  u32 s_%s;\n", regs_r32[reg]);
3394         had_decl = 1;
3395       }
3396     }
3397   }
3398
3399   if (save_arg_vars) {
3400     for (reg = 0; reg < 32; reg++) {
3401       if (save_arg_vars & (1 << reg)) {
3402         fprintf(fout, "  u32 s_a%d;\n", reg + 1);
3403         had_decl = 1;
3404       }
3405     }
3406   }
3407
3408   if (cmp_result_vars) {
3409     for (i = 0; i < 8; i++) {
3410       if (cmp_result_vars & (1 << i)) {
3411         fprintf(fout, "  u32 cond_%s;\n", parsed_flag_op_names[i]);
3412         had_decl = 1;
3413       }
3414     }
3415   }
3416
3417   if (need_mul_var) {
3418     fprintf(fout, "  u64 mul_tmp;\n");
3419     had_decl = 1;
3420   }
3421
3422   if (had_decl)
3423     fprintf(fout, "\n");
3424
3425   if (g_func_pp->is_vararg) {
3426     if (g_func_pp->argc_stack == 0)
3427       ferr(ops, "vararg func without stack args?\n");
3428     fprintf(fout, "  va_start(ap, a%d);\n", g_func_pp->argc);
3429   }
3430
3431   // output ops
3432   for (i = 0; i < opcnt; i++)
3433   {
3434     if (g_labels[i][0] != 0) {
3435       fprintf(fout, "\n%s:\n", g_labels[i]);
3436       label_pending = 1;
3437
3438       delayed_flag_op = NULL;
3439       last_arith_dst = NULL;
3440     }
3441
3442     po = &ops[i];
3443     if (po->flags & OPF_RMD)
3444       continue;
3445
3446     no_output = 0;
3447
3448     #define assert_operand_cnt(n_) \
3449       if (po->operand_cnt != n_) \
3450         ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3451
3452     // conditional/flag using op?
3453     if (po->flags & OPF_CC)
3454     {
3455       int is_delayed = 0;
3456       int is_inv = 0;
3457
3458       pfo = split_cond(po, po->op, &is_inv);
3459       tmp_op = po->datap;
3460
3461       // we go through all this trouble to avoid using parsed_flag_op,
3462       // which makes generated code much nicer
3463       if (delayed_flag_op != NULL)
3464       {
3465         out_cmp_test(buf1, sizeof(buf1), delayed_flag_op, pfo, is_inv);
3466         is_delayed = 1;
3467       }
3468       else if (last_arith_dst != NULL
3469         && (pfo == PFO_Z || pfo == PFO_S || pfo == PFO_P
3470            || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3471            ))
3472       {
3473         out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3474         out_test_for_cc(buf1, sizeof(buf1), po, pfo, is_inv,
3475           last_arith_dst->lmod, buf3);
3476         is_delayed = 1;
3477       }
3478       else if (tmp_op != NULL) {
3479         // use preprocessed flag calc results
3480         if (!(tmp_op->pfomask & (1 << pfo)))
3481           ferr(po, "not prepared for pfo %d\n", pfo);
3482
3483         // note: is_inv was not yet applied
3484         snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3485           is_inv ? "!" : "", parsed_flag_op_names[pfo]);
3486       }
3487       else {
3488         ferr(po, "all methods of finding comparison failed\n");
3489       }
3490  
3491       if (po->flags & OPF_JMP) {
3492         fprintf(fout, "  if %s\n", buf1);
3493       }
3494       else if (po->op == OP_ADC || po->op == OP_SBB) {
3495         if (is_delayed)
3496           fprintf(fout, "  cond_%s = %s;\n",
3497             parsed_flag_op_names[pfo], buf1);
3498       }
3499       else if (po->flags & OPF_DATA) { // SETcc
3500         out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3501         fprintf(fout, "  %s = %s;", buf2, buf1);
3502       }
3503       else {
3504         ferr(po, "unhandled conditional op\n");
3505       }
3506     }
3507
3508     pfomask = po->pfomask;
3509
3510     switch (po->op)
3511     {
3512       case OP_MOV:
3513         assert_operand_cnt(2);
3514         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3515         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3516         fprintf(fout, "  %s = %s;", buf1,
3517             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3518               po->operand[0].is_ptr ? "(void *)" : "", 0));
3519         break;
3520
3521       case OP_LEA:
3522         assert_operand_cnt(2);
3523         po->operand[1].lmod = OPLM_DWORD; // always
3524         fprintf(fout, "  %s = %s;",
3525             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3526             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3527               NULL, 1));
3528         break;
3529
3530       case OP_MOVZX:
3531         assert_operand_cnt(2);
3532         fprintf(fout, "  %s = %s;",
3533             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3534             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3535         break;
3536
3537       case OP_MOVSX:
3538         assert_operand_cnt(2);
3539         switch (po->operand[1].lmod) {
3540         case OPLM_BYTE:
3541           strcpy(buf3, "(s8)");
3542           break;
3543         case OPLM_WORD:
3544           strcpy(buf3, "(s16)");
3545           break;
3546         default:
3547           ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
3548         }
3549         fprintf(fout, "  %s = %s;",
3550             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3551             out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3552               buf3, 0));
3553         break;
3554
3555       case OP_NOT:
3556         assert_operand_cnt(1);
3557         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3558         fprintf(fout, "  %s = ~%s;", buf1, buf1);
3559         break;
3560
3561       case OP_CDQ:
3562         assert_operand_cnt(2);
3563         fprintf(fout, "  %s = (s32)%s >> 31;",
3564             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3565             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3566         strcpy(g_comment, "cdq");
3567         break;
3568
3569       case OP_STOS:
3570         // assumes DF=0
3571         assert_operand_cnt(3);
3572         if (po->flags & OPF_REP) {
3573           fprintf(fout, "  for (; ecx != 0; ecx--, edi += %d)\n",
3574             lmod_bytes(po, po->operand[0].lmod));
3575           fprintf(fout, "    %sedi = eax;",
3576             lmod_cast_u_ptr(po, po->operand[0].lmod));
3577           strcpy(g_comment, "rep stos");
3578         }
3579         else {
3580           fprintf(fout, "    %sedi = eax; edi += %d;",
3581             lmod_cast_u_ptr(po, po->operand[0].lmod),
3582             lmod_bytes(po, po->operand[0].lmod));
3583           strcpy(g_comment, "stos");
3584         }
3585         break;
3586
3587       case OP_MOVS:
3588         // assumes DF=0
3589         assert_operand_cnt(3);
3590         j = lmod_bytes(po, po->operand[0].lmod);
3591         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3592         if (po->flags & OPF_REP) {
3593           fprintf(fout,
3594             "  for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3595             j, j);
3596           fprintf(fout,
3597             "    %sedi = %sesi;", buf1, buf1);
3598           strcpy(g_comment, "rep movs");
3599         }
3600         else {
3601           fprintf(fout, "    %sedi = %sesi; edi += %d; esi += %d;",
3602             buf1, buf1, j, j);
3603           strcpy(g_comment, "movs");
3604         }
3605         break;
3606
3607       case OP_CMPS:
3608         // assumes DF=0
3609         // repe ~ repeat while ZF=1
3610         assert_operand_cnt(3);
3611         j = lmod_bytes(po, po->operand[0].lmod);
3612         strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
3613         if (po->flags & OPF_REP) {
3614           fprintf(fout,
3615             "  for (; ecx != 0; ecx--, edi += %d, esi += %d)\n",
3616             j, j);
3617           fprintf(fout,
3618             "    if ((cond_z = (%sedi == %sesi)) %s 0)\n",
3619               buf1, buf1, (po->flags & OPF_REPZ) ? "==" : "!=");
3620           fprintf(fout,
3621             "      break;");
3622           snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
3623             (po->flags & OPF_REPZ) ? "e" : "ne");
3624         }
3625         else {
3626           fprintf(fout,
3627             "    cond_z = (%sedi = %sesi); edi += %d; esi += %d;",
3628             buf1, buf1, j, j);
3629           strcpy(g_comment, "cmps");
3630         }
3631         pfomask &= ~(1 << PFO_Z);
3632         last_arith_dst = NULL;
3633         delayed_flag_op = NULL;
3634         break;
3635
3636       // arithmetic w/flags
3637       case OP_ADD:
3638       case OP_SUB:
3639       case OP_AND:
3640       case OP_OR:
3641         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3642         // fallthrough
3643       dualop_arith:
3644         assert_operand_cnt(2);
3645         fprintf(fout, "  %s %s= %s;",
3646             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3647             op_to_c(po),
3648             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3649         output_std_flags(fout, po, &pfomask, buf1);
3650         last_arith_dst = &po->operand[0];
3651         delayed_flag_op = NULL;
3652         break;
3653
3654       case OP_SHL:
3655       case OP_SHR:
3656         assert_operand_cnt(2);
3657         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3658         if (pfomask & (1 << PFO_C)) {
3659           if (po->operand[1].type == OPT_CONST) {
3660             l = lmod_bytes(po, po->operand[0].lmod) * 8;
3661             j = po->operand[1].val;
3662             j %= l;
3663             if (j != 0) {
3664               if (po->op == OP_SHL)
3665                 j = l - j;
3666               else
3667                 j -= 1;
3668               fprintf(fout, "  cond_c = (%s & 0x%02x) ? 1 : 0;\n",
3669                 buf1, 1 << j);
3670             }
3671             else
3672               ferr(po, "zero shift?\n");
3673           }
3674           else
3675             ferr(po, "TODO\n");
3676           pfomask &= ~(1 << PFO_C);
3677         }
3678         fprintf(fout, "  %s %s= %s;", buf1, op_to_c(po),
3679             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3680         output_std_flags(fout, po, &pfomask, buf1);
3681         last_arith_dst = &po->operand[0];
3682         delayed_flag_op = NULL;
3683         break;
3684
3685       case OP_SAR:
3686         assert_operand_cnt(2);
3687         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3688         fprintf(fout, "  %s = %s%s >> %s;", buf1,
3689           lmod_cast_s(po, po->operand[0].lmod), buf1,
3690           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3691         output_std_flags(fout, po, &pfomask, buf1);
3692         last_arith_dst = &po->operand[0];
3693         delayed_flag_op = NULL;
3694         break;
3695
3696       case OP_ROL:
3697       case OP_ROR:
3698         assert_operand_cnt(2);
3699         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3700         if (po->operand[1].type == OPT_CONST) {
3701           j = po->operand[1].val;
3702           j %= lmod_bytes(po, po->operand[0].lmod) * 8;
3703           fprintf(fout, po->op == OP_ROL ?
3704             "  %s = (%s << %d) | (%s >> %d);" :
3705             "  %s = (%s >> %d) | (%s << %d);",
3706             buf1, buf1, j, buf1,
3707             lmod_bytes(po, po->operand[0].lmod) * 8 - j);
3708         }
3709         else
3710           ferr(po, "TODO\n");
3711         output_std_flags(fout, po, &pfomask, buf1);
3712         last_arith_dst = &po->operand[0];
3713         delayed_flag_op = NULL;
3714         break;
3715
3716       case OP_XOR:
3717         assert_operand_cnt(2);
3718         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3719         if (IS(opr_name(po, 0), opr_name(po, 1))) {
3720           // special case for XOR
3721           fprintf(fout, "  %s = 0;",
3722             out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
3723           last_arith_dst = &po->operand[0];
3724           delayed_flag_op = NULL;
3725           break;
3726         }
3727         goto dualop_arith;
3728
3729       case OP_ADC:
3730       case OP_SBB:
3731         assert_operand_cnt(2);
3732         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3733         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3734         if (po->op == OP_SBB
3735           && IS(po->operand[0].name, po->operand[1].name))
3736         {
3737           // avoid use of unitialized var
3738           fprintf(fout, "  %s = -cond_c;", buf1);
3739           // carry remains what it was
3740           pfomask &= ~(1 << PFO_C);
3741         }
3742         else {
3743           fprintf(fout, "  %s %s= %s + cond_c;", buf1, op_to_c(po),
3744             out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
3745         }
3746         output_std_flags(fout, po, &pfomask, buf1);
3747         last_arith_dst = &po->operand[0];
3748         delayed_flag_op = NULL;
3749         break;
3750
3751       case OP_INC:
3752       case OP_DEC:
3753         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3754         if (po->operand[0].type == OPT_REG) {
3755           strcpy(buf2, po->op == OP_INC ? "++" : "--");
3756           fprintf(fout, "  %s%s;", buf1, buf2);
3757         }
3758         else {
3759           strcpy(buf2, po->op == OP_INC ? "+" : "-");
3760           fprintf(fout, "  %s %s= 1;", buf1, buf2);
3761         }
3762         output_std_flags(fout, po, &pfomask, buf1);
3763         last_arith_dst = &po->operand[0];
3764         delayed_flag_op = NULL;
3765         break;
3766
3767       case OP_NEG:
3768         out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3769         out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
3770         fprintf(fout, "  %s = -%s%s;", buf1,
3771           lmod_cast_s(po, po->operand[0].lmod), buf2);
3772         last_arith_dst = &po->operand[0];
3773         delayed_flag_op = NULL;
3774         if (pfomask & (1 << PFO_C)) {
3775           fprintf(fout, "\n  cond_c = (%s != 0);", buf1);
3776           pfomask &= ~(1 << PFO_C);
3777         }
3778         break;
3779
3780       case OP_IMUL:
3781         if (po->operand_cnt == 2) {
3782           propagate_lmod(po, &po->operand[0], &po->operand[1]);
3783           goto dualop_arith;
3784         }
3785         if (po->operand_cnt == 3)
3786           ferr(po, "TODO imul3\n");
3787         // fallthrough
3788       case OP_MUL:
3789         assert_operand_cnt(1);
3790         strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
3791         fprintf(fout, "  mul_tmp = %seax * %s%s;\n", buf1, buf1,
3792           out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
3793         fprintf(fout, "  edx = mul_tmp >> 32;\n");
3794         fprintf(fout, "  eax = mul_tmp;");
3795         last_arith_dst = NULL;
3796         delayed_flag_op = NULL;
3797         break;
3798
3799       case OP_DIV:
3800       case OP_IDIV:
3801         assert_operand_cnt(1);
3802         if (po->operand[0].lmod != OPLM_DWORD)
3803           ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
3804
3805         // 32bit division is common, look for it
3806         if (po->op == OP_DIV)
3807           ret = scan_for_reg_clear(i, xDX);
3808         else
3809           ret = scan_for_cdq_edx(i);
3810         if (ret >= 0) {
3811           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3812           strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
3813             po->op == OP_IDIV));
3814           fprintf(fout, "  edx = %seax %% %s%s;\n", buf2, buf2, buf1);
3815           fprintf(fout, "  eax = %seax / %s%s;", buf2, buf2, buf1);
3816         }
3817         else
3818           ferr(po, "TODO 64bit divident\n");
3819         last_arith_dst = NULL;
3820         delayed_flag_op = NULL;
3821         break;
3822
3823       case OP_TEST:
3824       case OP_CMP:
3825         propagate_lmod(po, &po->operand[0], &po->operand[1]);
3826         if (pfomask != 0) {
3827           for (j = 0; j < 8; j++) {
3828             if (pfomask & (1 << j)) {
3829               out_cmp_test(buf1, sizeof(buf1), po, j, 0);
3830               fprintf(fout, "  cond_%s = %s;",
3831                 parsed_flag_op_names[j], buf1);
3832             }
3833           }
3834           pfomask = 0;
3835         }
3836         else
3837           no_output = 1;
3838         last_arith_dst = NULL;
3839         delayed_flag_op = po;
3840         break;
3841
3842       // note: we reuse OP_Jcc for SETcc, only flags differ
3843       case OP_JO ... OP_JG:
3844         if (po->flags & OPF_JMP)
3845           fprintf(fout, "    goto %s;", po->operand[0].name);
3846         // else SETcc - should already be handled
3847         break;
3848
3849       case OP_JMP:
3850         assert_operand_cnt(1);
3851         last_arith_dst = NULL;
3852         delayed_flag_op = NULL;
3853
3854         if (po->operand[0].type == OPT_REGMEM) {
3855           ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
3856                   buf1, buf2);
3857           if (ret != 2)
3858             ferr(po, "parse failure for jmp '%s'\n",
3859               po->operand[0].name);
3860           fprintf(fout, "  goto *jt_%s[%s];", buf1, buf2);
3861           break;
3862         }
3863         else if (po->operand[0].type != OPT_LABEL)
3864           ferr(po, "unhandled jmp type\n");
3865
3866         fprintf(fout, "  goto %s;", po->operand[0].name);
3867         break;
3868
3869       case OP_CALL:
3870         assert_operand_cnt(1);
3871         pp = po->datap;
3872         my_assert_not(pp, NULL);
3873
3874         if (pp->is_fptr)
3875           fprintf(fout, "  %s = %s;\n", pp->name,
3876             out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
3877               "(void *)", 0));
3878
3879         fprintf(fout, "  ");
3880         if (strstr(pp->ret_type.name, "int64")) {
3881           if (po->flags & OPF_TAIL)
3882             ferr(po, "int64 and tail?\n");
3883           fprintf(fout, "mul_tmp = ");
3884         }
3885         else if (!IS(pp->ret_type.name, "void")) {
3886           if (po->flags & OPF_TAIL) {
3887             if (!IS(g_func_pp->ret_type.name, "void")) {
3888               fprintf(fout, "return ");
3889               if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
3890                 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
3891             }
3892           }
3893           else if (regmask & (1 << xAX)) {
3894             fprintf(fout, "eax = ");
3895             if (pp->ret_type.is_ptr)
3896               fprintf(fout, "(u32)");
3897           }
3898         }
3899
3900         if (pp->name[0] == 0)
3901           ferr(po, "missing pp->name\n");
3902         fprintf(fout, "%s%s(", pp->name,
3903           pp->has_structarg ? "_sa" : "");
3904
3905         for (arg = 0; arg < pp->argc; arg++) {
3906           if (arg > 0)
3907             fprintf(fout, ", ");
3908
3909           cast[0] = 0;
3910           if (pp->arg[arg].type.is_ptr)
3911             snprintf(cast, sizeof(cast), "(%s)", pp->arg[arg].type.name);
3912
3913           if (pp->arg[arg].reg != NULL) {
3914             fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
3915             continue;
3916           }
3917
3918           // stack arg
3919           tmp_op = pp->arg[arg].datap;
3920           if (tmp_op == NULL)
3921             ferr(po, "parsed_op missing for arg%d\n", arg);
3922           if (tmp_op->argnum != 0) {
3923             fprintf(fout, "%ss_a%d", cast, tmp_op->argnum);
3924           }
3925           else {
3926             fprintf(fout, "%s",
3927               out_src_opr(buf1, sizeof(buf1),
3928                 tmp_op, &tmp_op->operand[0], cast, 0));
3929           }
3930         }
3931         fprintf(fout, ");");
3932
3933         if (strstr(pp->ret_type.name, "int64")) {
3934           fprintf(fout, "\n");
3935           fprintf(fout, "  edx = mul_tmp >> 32;\n");
3936           fprintf(fout, "  eax = mul_tmp;");
3937         }
3938
3939         if (pp->is_unresolved) {
3940           snprintf(buf3, sizeof(buf3), " unresoved %dreg",
3941             pp->argc_reg);
3942           strcat(g_comment, buf3);
3943         }
3944
3945         if (po->flags & OPF_TAIL) {
3946           ret = 0;
3947           if (i == opcnt - 1 || pp->is_noreturn)
3948             ret = 0;
3949           else if (IS(pp->ret_type.name, "void"))
3950             ret = 1;
3951           else if (IS(g_func_pp->ret_type.name, "void"))
3952             ret = 1;
3953           // else already handled as 'return f()'
3954
3955           if (ret) {
3956             if (!IS(g_func_pp->ret_type.name, "void")) {
3957               ferr(po, "int func -> void func tailcall?\n");
3958             }
3959             else {
3960               fprintf(fout, "\n  return;");
3961               strcat(g_comment, " ^ tailcall");
3962             }
3963           }
3964           else
3965             strcat(g_comment, " tailcall");
3966         }
3967         if (pp->is_noreturn)
3968           strcat(g_comment, " noreturn");
3969         delayed_flag_op = NULL;
3970         last_arith_dst = NULL;
3971         break;
3972
3973       case OP_RET:
3974         if (g_func_pp->is_vararg)
3975           fprintf(fout, "  va_end(ap);\n");
3976  
3977         if (IS(g_func_pp->ret_type.name, "void")) {
3978           if (i != opcnt - 1 || label_pending)
3979             fprintf(fout, "  return;");
3980         }
3981         else if (g_func_pp->ret_type.is_ptr) {
3982           fprintf(fout, "  return (%s)eax;",
3983             g_func_pp->ret_type.name);
3984         }
3985         else
3986           fprintf(fout, "  return eax;");
3987
3988         last_arith_dst = NULL;
3989         delayed_flag_op = NULL;
3990         break;
3991
3992       case OP_PUSH:
3993         if (po->argnum != 0) {
3994           // special case - saved func arg
3995           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
3996           fprintf(fout, "  s_a%d = %s;", po->argnum, buf1);
3997           break;
3998         }
3999         else if (po->flags & OPF_RSAVE) {
4000           out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4001           fprintf(fout, "  s_%s = %s;", buf1, buf1);
4002           break;
4003         }
4004         if (!(g_ida_func_attr & IDAFA_NORETURN))
4005           ferr(po, "stray push encountered\n");
4006         no_output = 1;
4007         break;
4008
4009       case OP_POP:
4010         if (po->flags & OPF_RSAVE) {
4011           out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4012           fprintf(fout, "  %s = s_%s;", buf1, buf1);
4013           break;
4014         }
4015         ferr(po, "stray pop encountered\n");
4016         break;
4017
4018       case OP_NOP:
4019         no_output = 1;
4020         break;
4021
4022       default:
4023         no_output = 1;
4024         ferr(po, "unhandled op type %d, flags %x\n",
4025           po->op, po->flags);
4026         break;
4027     }
4028
4029     if (g_comment[0] != 0) {
4030       char *p = g_comment;
4031       while (my_isblank(*p))
4032         p++;
4033       fprintf(fout, "  // %s", p);
4034       g_comment[0] = 0;
4035       no_output = 0;
4036     }
4037     if (!no_output)
4038       fprintf(fout, "\n");
4039
4040     // some sanity checking
4041     if ((po->flags & OPF_REP) && po->op != OP_STOS
4042         && po->op != OP_MOVS && po->op != OP_CMPS)
4043       ferr(po, "unexpected rep\n");
4044     if ((po->flags & (OPF_REPZ|OPF_REPNZ)) && po->op != OP_CMPS)
4045       ferr(po, "unexpected repz/repnz\n");
4046
4047     if (pfomask != 0)
4048       ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
4049
4050     // see is delayed flag stuff is still valid
4051     if (delayed_flag_op != NULL && delayed_flag_op != po) {
4052       if (is_any_opr_modified(delayed_flag_op, po, 0))
4053         delayed_flag_op = NULL;
4054     }
4055
4056     if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
4057       if (is_opr_modified(last_arith_dst, po))
4058         last_arith_dst = NULL;
4059     }
4060
4061     label_pending = 0;
4062   }
4063
4064   if (g_stack_fsz && !g_stack_frame_used)
4065     fprintf(fout, "  (void)sf;\n");
4066
4067   fprintf(fout, "}\n\n");
4068
4069   // cleanup
4070   for (i = 0; i < opcnt; i++) {
4071     struct label_ref *lr, *lr_del;
4072
4073     lr = g_label_refs[i].next;
4074     while (lr != NULL) {
4075       lr_del = lr;
4076       lr = lr->next;
4077       free(lr_del);
4078     }
4079     g_label_refs[i].i = -1;
4080     g_label_refs[i].next = NULL;
4081
4082     if (ops[i].op == OP_CALL) {
4083       pp = ops[i].datap;
4084       if (pp)
4085         proto_release(pp);
4086     }
4087   }
4088   g_func_pp = NULL;
4089 }
4090
4091 static void set_label(int i, const char *name)
4092 {
4093   const char *p;
4094   int len;
4095
4096   len = strlen(name);
4097   p = strchr(name, ':');
4098   if (p != NULL)
4099     len = p - name;
4100
4101   if (len > sizeof(g_labels[0]) - 1)
4102     aerr("label '%s' too long: %d\n", name, len);
4103   if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
4104     aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
4105   memcpy(g_labels[i], name, len);
4106   g_labels[i][len] = 0;
4107 }
4108
4109 // '=' needs special treatment..
4110 static char *next_word_s(char *w, size_t wsize, char *s)
4111 {
4112         size_t i;
4113
4114         s = sskip(s);
4115
4116         for (i = 0; i < wsize - 1; i++) {
4117                 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
4118                         break;
4119                 w[i] = s[i];
4120         }
4121         w[i] = 0;
4122
4123         if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
4124                 printf("warning: '%s' truncated\n", w);
4125
4126         return s + i;
4127 }
4128
4129 struct chunk_item {
4130   char *name;
4131   long fptr;
4132   int asmln;
4133 };
4134
4135 static struct chunk_item *func_chunks;
4136 static int func_chunk_cnt;
4137 static int func_chunk_alloc;
4138
4139 static void add_func_chunk(FILE *fasm, const char *name, int line)
4140 {
4141   if (func_chunk_cnt >= func_chunk_alloc) {
4142     func_chunk_alloc *= 2;
4143     func_chunks = realloc(func_chunks,
4144       func_chunk_alloc * sizeof(func_chunks[0]));
4145     my_assert_not(func_chunks, NULL);
4146   }
4147   func_chunks[func_chunk_cnt].fptr = ftell(fasm);
4148   func_chunks[func_chunk_cnt].name = strdup(name);
4149   func_chunks[func_chunk_cnt].asmln = line;
4150   func_chunk_cnt++;
4151 }
4152
4153 static int cmp_chunks(const void *p1, const void *p2)
4154 {
4155   const struct chunk_item *c1 = p1, *c2 = p2;
4156   return strcmp(c1->name, c2->name);
4157 }
4158
4159 static int cmpstringp(const void *p1, const void *p2)
4160 {
4161   return strcmp(*(char * const *)p1, *(char * const *)p2);
4162 }
4163
4164 static void scan_ahead(FILE *fasm)
4165 {
4166   char words[2][256];
4167   char line[256];
4168   long oldpos;
4169   int oldasmln;
4170   int wordc;
4171   char *p;
4172   int i;
4173
4174   oldpos = ftell(fasm);
4175   oldasmln = asmln;
4176
4177   while (fgets(line, sizeof(line), fasm))
4178   {
4179     wordc = 0;
4180     asmln++;
4181
4182     p = sskip(line);
4183     if (*p == 0)
4184       continue;
4185
4186     if (*p == ';')
4187     {
4188       // get rid of random tabs
4189       for (i = 0; line[i] != 0; i++)
4190         if (line[i] == '\t')
4191           line[i] = ' ';
4192
4193       if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4194       {
4195         p += 30;
4196         next_word(words[0], sizeof(words[0]), p);
4197         if (words[0][0] == 0)
4198           aerr("missing name for func chunk?\n");
4199
4200         add_func_chunk(fasm, words[0], asmln);
4201       }
4202       continue;
4203     } // *p == ';'
4204
4205     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4206       words[wordc][0] = 0;
4207       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4208       if (*p == 0 || *p == ';') {
4209         wordc++;
4210         break;
4211       }
4212     }
4213
4214     if (wordc == 2 && IS(words[1], "ends"))
4215       break;
4216   }
4217
4218   fseek(fasm, oldpos, SEEK_SET);
4219   asmln = oldasmln;
4220 }
4221
4222 int main(int argc, char *argv[])
4223 {
4224   FILE *fout, *fasm, *frlist;
4225   struct parsed_data *pd = NULL;
4226   int pd_alloc = 0;
4227   char **rlist = NULL;
4228   int rlist_len = 0;
4229   int rlist_alloc = 0;
4230   int func_chunks_used = 0;
4231   int func_chunks_sorted = 0;
4232   int func_chunk_i = -1;
4233   long func_chunk_ret = 0;
4234   int func_chunk_ret_ln = 0;
4235   int scanned_ahead = 0;
4236   char line[256];
4237   char words[20][256];
4238   enum opr_lenmod lmod;
4239   char *sctproto = NULL;
4240   int in_func = 0;
4241   int pending_endp = 0;
4242   int skip_func = 0;
4243   int skip_warned = 0;
4244   int eq_alloc;
4245   int verbose = 0;
4246   int arg_out;
4247   int arg;
4248   int pi = 0;
4249   int i, j;
4250   int ret, len;
4251   char *p;
4252   int wordc;
4253
4254   for (arg = 1; arg < argc; arg++) {
4255     if (IS(argv[arg], "-v"))
4256       verbose = 1;
4257     else if (IS(argv[arg], "-rf"))
4258       g_allow_regfunc = 1;
4259     else
4260       break;
4261   }
4262
4263   if (argc < arg + 3) {
4264     printf("usage:\n%s [-v] [-rf] <.c> <.asm> <hdrf> [rlist]*\n",
4265       argv[0]);
4266     return 1;
4267   }
4268
4269   arg_out = arg++;
4270
4271   asmfn = argv[arg++];
4272   fasm = fopen(asmfn, "r");
4273   my_assert_not(fasm, NULL);
4274
4275   hdrfn = argv[arg++];
4276   g_fhdr = fopen(hdrfn, "r");
4277   my_assert_not(g_fhdr, NULL);
4278
4279   rlist_alloc = 64;
4280   rlist = malloc(rlist_alloc * sizeof(rlist[0]));
4281   my_assert_not(rlist, NULL);
4282   // needs special handling..
4283   rlist[rlist_len++] = "__alloca_probe";
4284
4285   func_chunk_alloc = 32;
4286   func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
4287   my_assert_not(func_chunks, NULL);
4288
4289   memset(words, 0, sizeof(words));
4290
4291   for (; arg < argc; arg++) {
4292     frlist = fopen(argv[arg], "r");
4293     my_assert_not(frlist, NULL);
4294
4295     while (fgets(line, sizeof(line), frlist)) {
4296       p = sskip(line);
4297       if (*p == 0 || *p == ';')
4298         continue;
4299       if (*p == '#') {
4300         if (IS_START(p, "#if 0")
4301          || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
4302         {
4303           skip_func = 1;
4304         }
4305         else if (IS_START(p, "#endif"))
4306           skip_func = 0;
4307         continue;
4308       }
4309       if (skip_func)
4310         continue;
4311
4312       p = next_word(words[0], sizeof(words[0]), p);
4313       if (words[0][0] == 0)
4314         continue;
4315
4316       if (rlist_len >= rlist_alloc) {
4317         rlist_alloc = rlist_alloc * 2 + 64;
4318         rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
4319         my_assert_not(rlist, NULL);
4320       }
4321       rlist[rlist_len++] = strdup(words[0]);
4322     }
4323     skip_func = 0;
4324
4325     fclose(frlist);
4326     frlist = NULL;
4327   }
4328
4329   if (rlist_len > 0)
4330     qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
4331
4332   fout = fopen(argv[arg_out], "w");
4333   my_assert_not(fout, NULL);
4334
4335   eq_alloc = 128;
4336   g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
4337   my_assert_not(g_eqs, NULL);
4338
4339   for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
4340     g_label_refs[i].i = -1;
4341     g_label_refs[i].next = NULL;
4342   }
4343
4344   while (fgets(line, sizeof(line), fasm))
4345   {
4346     wordc = 0;
4347     asmln++;
4348
4349     p = sskip(line);
4350     if (*p == 0)
4351       continue;
4352
4353     // get rid of random tabs
4354     for (i = 0; line[i] != 0; i++)
4355       if (line[i] == '\t')
4356         line[i] = ' ';
4357
4358     if (*p == ';')
4359     {
4360       if (p[2] == '=' && IS_START(p, "; =============== S U B"))
4361         goto do_pending_endp; // eww..
4362
4363       if (p[2] == 'A' && IS_START(p, "; Attributes:"))
4364       {
4365         static const char *attrs[] = {
4366           "bp-based frame",
4367           "library function",
4368           "static",
4369           "noreturn",
4370           "thunk",
4371           "fpd=",
4372         };
4373
4374         // parse IDA's attribute-list comment
4375         g_ida_func_attr = 0;
4376         p = sskip(p + 13);
4377
4378         for (; *p != 0; p = sskip(p)) {
4379           for (i = 0; i < ARRAY_SIZE(attrs); i++) {
4380             if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
4381               g_ida_func_attr |= 1 << i;
4382               p += strlen(attrs[i]);
4383               break;
4384             }
4385           }
4386           if (i == ARRAY_SIZE(attrs)) {
4387             anote("unparsed IDA attr: %s\n", p);
4388             break;
4389           }
4390           if (IS(attrs[i], "fpd=")) {
4391             p = next_word(words[0], sizeof(words[0]), p);
4392             // ignore for now..
4393           }
4394         }
4395       }
4396       else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4397       {
4398         p += 30;
4399         next_word(words[0], sizeof(words[0]), p);
4400         if (words[0][0] == 0)
4401           aerr("missing name for func chunk?\n");
4402
4403         if (!scanned_ahead) {
4404           add_func_chunk(fasm, words[0], asmln);
4405           func_chunks_sorted = 0;
4406         }
4407       }
4408       else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
4409       {
4410         if (func_chunk_i >= 0) {
4411           if (func_chunk_i < func_chunk_cnt
4412             && IS(func_chunks[func_chunk_i].name, g_func))
4413           {
4414             // move on to next chunk
4415             ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4416             if (ret)
4417               aerr("seek failed for '%s' chunk #%d\n",
4418                 g_func, func_chunk_i);
4419             asmln = func_chunks[func_chunk_i].asmln;
4420             func_chunk_i++;
4421           }
4422           else {
4423             if (func_chunk_ret == 0)
4424               aerr("no return from chunk?\n");
4425             fseek(fasm, func_chunk_ret, SEEK_SET);
4426             asmln = func_chunk_ret_ln;
4427             func_chunk_ret = 0;
4428             pending_endp = 1;
4429           }
4430         }
4431       }
4432       else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
4433         func_chunks_used = 1;
4434         p += 20;
4435         if (IS_START(g_func, "sub_")) {
4436           unsigned long addr = strtoul(p, NULL, 16);
4437           unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
4438           if (addr > f_addr && !scanned_ahead) {
4439             anote("scan_ahead caused by '%s', addr %lx\n",
4440               g_func, addr);
4441             scan_ahead(fasm);
4442             scanned_ahead = 1;
4443             func_chunks_sorted = 0;
4444           }
4445         }
4446       }
4447       continue;
4448     } // *p == ';'
4449
4450 parse_words:
4451     for (i = wordc; i < ARRAY_SIZE(words); i++)
4452       words[i][0] = 0;
4453     for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4454       p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4455       if (*p == 0 || *p == ';') {
4456         wordc++;
4457         break;
4458       }
4459     }
4460     if (*p != 0 && *p != ';')
4461       aerr("too many words\n");
4462
4463     // alow asm patches in comments
4464     if (*p == ';') {
4465       if (IS_START(p, "; sctpatch:")) {
4466         p = sskip(p + 11);
4467         if (*p == 0 || *p == ';')
4468           continue;
4469         goto parse_words; // lame
4470       }
4471       if (IS_START(p, "; sctproto:")) {
4472         sctproto = strdup(p + 11);
4473       }
4474     }
4475
4476     if (wordc == 0) {
4477       // shouldn't happen
4478       awarn("wordc == 0?\n");
4479       continue;
4480     }
4481
4482     // don't care about this:
4483     if (words[0][0] == '.'
4484         || IS(words[0], "include")
4485         || IS(words[0], "assume") || IS(words[1], "segment")
4486         || IS(words[0], "align"))
4487     {
4488       continue;
4489     }
4490
4491 do_pending_endp:
4492     // do delayed endp processing to collect switch jumptables
4493     if (pending_endp) {
4494       if (in_func && !skip_func && wordc >= 2
4495           && ((words[0][0] == 'd' && words[0][2] == 0)
4496               || (words[1][0] == 'd' && words[1][2] == 0)))
4497       {
4498         i = 1;
4499         if (words[1][0] == 'd' && words[1][2] == 0) {
4500           // label
4501           if (g_func_pd_cnt >= pd_alloc) {
4502             pd_alloc = pd_alloc * 2 + 16;
4503             g_func_pd = realloc(g_func_pd,
4504               sizeof(g_func_pd[0]) * pd_alloc);
4505             my_assert_not(g_func_pd, NULL);
4506           }
4507           pd = &g_func_pd[g_func_pd_cnt];
4508           g_func_pd_cnt++;
4509           memset(pd, 0, sizeof(*pd));
4510           strcpy(pd->label, words[0]);
4511           pd->type = OPT_CONST;
4512           pd->lmod = lmod_from_directive(words[1]);
4513           i = 2;
4514         }
4515         else {
4516           if (pd == NULL) {
4517             if (verbose)
4518               anote("skipping alignment byte?\n");
4519             continue;
4520           }
4521           lmod = lmod_from_directive(words[0]);
4522           if (lmod != pd->lmod)
4523             aerr("lmod change? %d->%d\n", pd->lmod, lmod);
4524         }
4525
4526         if (pd->count_alloc < pd->count + wordc) {
4527           pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
4528           pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
4529           my_assert_not(pd->d, NULL);
4530         }
4531         for (; i < wordc; i++) {
4532           if (IS(words[i], "offset")) {
4533             pd->type = OPT_OFFSET;
4534             i++;
4535           }
4536           p = strchr(words[i], ',');
4537           if (p != NULL)
4538             *p = 0;
4539           if (pd->type == OPT_OFFSET)
4540             pd->d[pd->count].u.label = strdup(words[i]);
4541           else
4542             pd->d[pd->count].u.val = parse_number(words[i]);
4543           pd->d[pd->count].bt_i = -1;
4544           pd->count++;
4545         }
4546         continue;
4547       }
4548
4549       if (in_func && !skip_func)
4550         gen_func(fout, g_fhdr, g_func, pi);
4551
4552       pending_endp = 0;
4553       in_func = 0;
4554       g_ida_func_attr = 0;
4555       skip_warned = 0;
4556       skip_func = 0;
4557       g_func[0] = 0;
4558       func_chunks_used = 0;
4559       func_chunk_i = -1;
4560       if (pi != 0) {
4561         memset(&ops, 0, pi * sizeof(ops[0]));
4562         memset(g_labels, 0, pi * sizeof(g_labels[0]));
4563         pi = 0;
4564       }
4565       g_eqcnt = 0;
4566       for (i = 0; i < g_func_pd_cnt; i++) {
4567         pd = &g_func_pd[i];
4568         if (pd->type == OPT_OFFSET) {
4569           for (j = 0; j < pd->count; j++)
4570             free(pd->d[j].u.label);
4571         }
4572         free(pd->d);
4573         pd->d = NULL;
4574       }
4575       g_func_pd_cnt = 0;
4576       pd = NULL;
4577       if (wordc == 0)
4578         continue;
4579     }
4580
4581     if (IS(words[1], "proc")) {
4582       if (in_func)
4583         aerr("proc '%s' while in_func '%s'?\n",
4584           words[0], g_func);
4585       p = words[0];
4586       if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
4587         skip_func = 1;
4588       strcpy(g_func, words[0]);
4589       set_label(0, words[0]);
4590       in_func = 1;
4591       continue;
4592     }
4593
4594     if (IS(words[1], "endp"))
4595     {
4596       if (!in_func)
4597         aerr("endp '%s' while not in_func?\n", words[0]);
4598       if (!IS(g_func, words[0]))
4599         aerr("endp '%s' while in_func '%s'?\n",
4600           words[0], g_func);
4601
4602       if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
4603         && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
4604       {
4605         // import jump
4606         skip_func = 1;
4607       }
4608
4609       if (!skip_func && func_chunks_used) {
4610         // start processing chunks
4611         struct chunk_item *ci, key = { g_func, 0 };
4612
4613         func_chunk_ret = ftell(fasm);
4614         func_chunk_ret_ln = asmln;
4615         if (!func_chunks_sorted) {
4616           qsort(func_chunks, func_chunk_cnt,
4617             sizeof(func_chunks[0]), cmp_chunks);
4618           func_chunks_sorted = 1;
4619         }
4620         ci = bsearch(&key, func_chunks, func_chunk_cnt,
4621                sizeof(func_chunks[0]), cmp_chunks);
4622         if (ci == NULL)
4623           aerr("'%s' needs chunks, but none found\n", g_func);
4624         func_chunk_i = ci - func_chunks;
4625         for (; func_chunk_i > 0; func_chunk_i--)
4626           if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
4627             break;
4628
4629         ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
4630         if (ret)
4631           aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
4632         asmln = func_chunks[func_chunk_i].asmln;
4633         func_chunk_i++;
4634         continue;
4635       }
4636       pending_endp = 1;
4637       continue;
4638     }
4639
4640     if (wordc == 2 && IS(words[1], "ends"))
4641       break;
4642
4643     p = strchr(words[0], ':');
4644     if (p != NULL) {
4645       set_label(pi, words[0]);
4646       continue;
4647     }
4648
4649     if (!in_func || skip_func) {
4650       if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
4651         if (verbose)
4652           anote("skipping from '%s'\n", g_labels[pi]);
4653         skip_warned = 1;
4654       }
4655       g_labels[pi][0] = 0;
4656       continue;
4657     }
4658
4659     if (wordc > 1 && IS(words[1], "="))
4660     {
4661       if (wordc != 5)
4662         aerr("unhandled equ, wc=%d\n", wordc);
4663       if (g_eqcnt >= eq_alloc) {
4664         eq_alloc *= 2;
4665         g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
4666         my_assert_not(g_eqs, NULL);
4667       }
4668
4669       len = strlen(words[0]);
4670       if (len > sizeof(g_eqs[0].name) - 1)
4671         aerr("equ name too long: %d\n", len);
4672       strcpy(g_eqs[g_eqcnt].name, words[0]);
4673
4674       if (!IS(words[3], "ptr"))
4675         aerr("unhandled equ\n");
4676       if (IS(words[2], "dword"))
4677         g_eqs[g_eqcnt].lmod = OPLM_DWORD;
4678       else if (IS(words[2], "word"))
4679         g_eqs[g_eqcnt].lmod = OPLM_WORD;
4680       else if (IS(words[2], "byte"))
4681         g_eqs[g_eqcnt].lmod = OPLM_BYTE;
4682       else
4683         aerr("bad lmod: '%s'\n", words[2]);
4684
4685       g_eqs[g_eqcnt].offset = parse_number(words[4]);
4686       g_eqcnt++;
4687       continue;
4688     }
4689
4690     if (pi >= ARRAY_SIZE(ops))
4691       aerr("too many ops\n");
4692
4693     parse_op(&ops[pi], words, wordc);
4694
4695     if (sctproto != NULL) {
4696       if (ops[pi].op == OP_CALL)
4697         ops[pi].datap = sctproto;
4698       sctproto = NULL;
4699     }
4700     pi++;
4701   }
4702
4703   fclose(fout);
4704   fclose(fasm);
4705   fclose(g_fhdr);
4706
4707   return 0;
4708 }
4709
4710 // vim:ts=2:shiftwidth=2:expandtab