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