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