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