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