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