translate: deal with and 0 / or ~0
[ia32rtools.git] / tools / translate.c
CommitLineData
7637b6cc 1/*
2 * ia32rtools
2c10ea1f 3 * (C) notaz, 2013-2015
7637b6cc 4 *
5 * This work is licensed under the terms of 3-clause BSD license.
6 * See COPYING file in the top-level directory.
7 */
8
33c35af6 9#define _GNU_SOURCE
c36e914d 10#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
13
14#include "my_assert.h"
15#include "my_str.h"
9ea60b8d 16#include "common.h"
c36e914d 17
18#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
19#define IS(w, y) !strcmp(w, y)
39b168b8 20#define IS_START(w, y) !strncmp(w, y, strlen(y))
c36e914d 21
22#include "protoparse.h"
23
06c5d854 24static const char *asmfn;
c36e914d 25static int asmln;
06c5d854 26static FILE *g_fhdr;
c36e914d 27
940e8e66 28#define anote(fmt, ...) \
29 printf("%s:%d: note: " fmt, asmfn, asmln, ##__VA_ARGS__)
c36e914d 30#define awarn(fmt, ...) \
940e8e66 31 printf("%s:%d: warning: " fmt, asmfn, asmln, ##__VA_ARGS__)
c36e914d 32#define aerr(fmt, ...) do { \
940e8e66 33 printf("%s:%d: error: " fmt, asmfn, asmln, ##__VA_ARGS__); \
33c35af6 34 fcloseall(); \
c36e914d 35 exit(1); \
36} while (0)
37
054f95b2 38#include "masm_tools.h"
39
69a3cdfc 40enum op_flags {
5e49b270 41 OPF_RMD = (1 << 0), /* removed from code generation */
87bf6cec 42 OPF_DATA = (1 << 1), /* data processing - writes to dst opr */
43 OPF_FLAGS = (1 << 2), /* sets flags */
5c024ef7 44 OPF_JMP = (1 << 3), /* branch, call */
04abc5d6 45 OPF_CJMP = (1 << 4), /* cond. branch (cc or jecxz/loop) */
5c024ef7 46 OPF_CC = (1 << 5), /* uses flags */
47 OPF_TAIL = (1 << 6), /* ret or tail call */
48 OPF_RSAVE = (1 << 7), /* push/pop is local reg save/load */
49 OPF_REP = (1 << 8), /* prefixed by rep */
50 OPF_REPZ = (1 << 9), /* rep is repe/repz */
51 OPF_REPNZ = (1 << 10), /* rep is repne/repnz */
9af2d373 52 OPF_FARG = (1 << 11), /* push collected as func arg */
53 OPF_FARGNR = (1 << 12), /* push collected as func arg (no reuse) */
54 OPF_EBP_S = (1 << 13), /* ebp used as scratch here, not BP */
55 OPF_DF = (1 << 14), /* DF flag set */
56 OPF_ATAIL = (1 << 15), /* tail call with reused arg frame */
57 OPF_32BIT = (1 << 16), /* 32bit division */
58 OPF_LOCK = (1 << 17), /* op has lock prefix */
59 OPF_VAPUSH = (1 << 18), /* vararg ptr push (as call arg) */
26677139 60 OPF_DONE = (1 << 19), /* already fully handled by analysis */
25a330eb 61 OPF_PPUSH = (1 << 20), /* part of complex push-pop graph */
c36e914d 62};
63
64enum op_op {
65 OP_INVAL,
33c35af6 66 OP_NOP,
c36e914d 67 OP_PUSH,
68 OP_POP,
591721d7 69 OP_LEAVE,
c36e914d 70 OP_MOV,
850c9265 71 OP_LEA,
72 OP_MOVZX,
73 OP_MOVSX,
108e9fe3 74 OP_XCHG,
850c9265 75 OP_NOT,
04abc5d6 76 OP_XLAT,
5101a5f9 77 OP_CDQ,
092f64e1 78 OP_LODS,
33c35af6 79 OP_STOS,
d4e3b5db 80 OP_MOVS,
7ba45c34 81 OP_CMPS,
591721d7 82 OP_SCAS,
83 OP_STD,
84 OP_CLD,
c36e914d 85 OP_RET,
86 OP_ADD,
91977a1c 87 OP_SUB,
850c9265 88 OP_AND,
89 OP_OR,
90 OP_XOR,
91 OP_SHL,
92 OP_SHR,
93 OP_SAR,
04abc5d6 94 OP_SHLD,
3b2f4044 95 OP_SHRD,
d4e3b5db 96 OP_ROL,
97 OP_ROR,
cb090db0 98 OP_RCL,
99 OP_RCR,
69a3cdfc 100 OP_ADC,
850c9265 101 OP_SBB,
1f84f6b3 102 OP_BSF,
850c9265 103 OP_INC,
104 OP_DEC,
5101a5f9 105 OP_NEG,
850c9265 106 OP_MUL,
107 OP_IMUL,
5101a5f9 108 OP_DIV,
109 OP_IDIV,
c36e914d 110 OP_TEST,
111 OP_CMP,
112 OP_CALL,
113 OP_JMP,
5c024ef7 114 OP_JECXZ,
04abc5d6 115 OP_LOOP,
092f64e1 116 OP_JCC,
117 OP_SCC,
90307a99 118 // x87
119 // mmx
120 OP_EMMS,
30c8c549 121 // undefined
2c10ea1f 122 OP_UD2,
c36e914d 123};
124
125enum opr_type {
87bf6cec 126 OPT_UNSPEC,
127 OPT_REG,
128 OPT_REGMEM,
129 OPT_LABEL,
850c9265 130 OPT_OFFSET,
87bf6cec 131 OPT_CONST,
c36e914d 132};
133
2b43685d 134// must be sorted (larger len must be further in enum)
c36e914d 135enum opr_lenmod {
91977a1c 136 OPLM_UNSPEC,
137 OPLM_BYTE,
138 OPLM_WORD,
139 OPLM_DWORD,
90307a99 140 OPLM_QWORD,
c36e914d 141};
142
850c9265 143#define MAX_OPERANDS 3
92d715b6 144#define NAMELEN 112
c36e914d 145
146struct parsed_opr {
91977a1c 147 enum opr_type type;
148 enum opr_lenmod lmod;
7ba45c34 149 unsigned int is_ptr:1; // pointer in C
150 unsigned int is_array:1; // array in C
a3684be1 151 unsigned int type_from_var:1; // .. in header, sometimes wrong
2b43685d 152 unsigned int size_mismatch:1; // type override differs from C
153 unsigned int size_lt:1; // type override is larger than C
ddaf8bd7 154 unsigned int had_ds:1; // had ds: prefix
c7ed83dd 155 const struct parsed_proto *pp; // for OPT_LABEL
91977a1c 156 int reg;
157 unsigned int val;
92d715b6 158 char name[NAMELEN];
c36e914d 159};
160
161struct parsed_op {
91977a1c 162 enum op_op op;
163 struct parsed_opr operand[MAX_OPERANDS];
69a3cdfc 164 unsigned int flags;
092f64e1 165 unsigned char pfo;
166 unsigned char pfo_inv;
167 unsigned char operand_cnt;
3a5101d7 168 unsigned char p_argnum; // arg push: altered before call arg #
169 unsigned char p_arggrp; // arg push: arg group # for above
170 unsigned char p_argpass;// arg push: arg of host func
171 short p_argnext;// arg push: same arg pushed elsewhere or -1
69a3cdfc 172 int regmask_src; // all referensed regs
173 int regmask_dst;
940e8e66 174 int pfomask; // flagop: parsed_flag_op that can't be delayed
940e8e66 175 int cc_scratch; // scratch storage during analysis
4c45fa73 176 int bt_i; // branch target for branches
177 struct parsed_data *btj;// branch targets for jumptables
c7ed83dd 178 struct parsed_proto *pp;// parsed_proto for OP_CALL
91977a1c 179 void *datap;
8eb12e72 180 int asmln;
91977a1c 181};
182
69a3cdfc 183// datap:
25a330eb 184// OP_CALL - parser proto hint (str)
2c10ea1f 185// (OPF_CC) - points to one of (OPF_FLAGS) that affects cc op
25a330eb 186// OP_PUSH - points to OP_POP in complex push/pop graph
187// OP_POP - points to OP_PUSH in simple push/pop pair
69a3cdfc 188
91977a1c 189struct parsed_equ {
190 char name[64];
191 enum opr_lenmod lmod;
192 int offset;
c36e914d 193};
194
4c45fa73 195struct parsed_data {
196 char label[256];
197 enum opr_type type;
198 enum opr_lenmod lmod;
199 int count;
200 int count_alloc;
201 struct {
202 union {
203 char *label;
63df67be 204 unsigned int val;
4c45fa73 205 } u;
206 int bt_i;
207 } *d;
208};
209
210struct label_ref {
211 int i;
212 struct label_ref *next;
213};
214
1bafb621 215enum ida_func_attr {
216 IDAFA_BP_FRAME = (1 << 0),
217 IDAFA_LIB_FUNC = (1 << 1),
218 IDAFA_STATIC = (1 << 2),
219 IDAFA_NORETURN = (1 << 3),
220 IDAFA_THUNK = (1 << 4),
221 IDAFA_FPD = (1 << 5),
222};
223
3a5101d7 224// note: limited to 32k due to p_argnext
225#define MAX_OPS 4096
226#define MAX_ARG_GRP 2
c36e914d 227
228static struct parsed_op ops[MAX_OPS];
91977a1c 229static struct parsed_equ *g_eqs;
230static int g_eqcnt;
d7857c3a 231static char *g_labels[MAX_OPS];
4c45fa73 232static struct label_ref g_label_refs[MAX_OPS];
bd96f656 233static const struct parsed_proto *g_func_pp;
4c45fa73 234static struct parsed_data *g_func_pd;
235static int g_func_pd_cnt;
91977a1c 236static char g_func[256];
237static char g_comment[256];
238static int g_bp_frame;
1bafb621 239static int g_sp_frame;
a2c1d768 240static int g_stack_frame_used;
1bafb621 241static int g_stack_fsz;
4c45fa73 242static int g_ida_func_attr;
30c8c549 243static int g_skip_func;
89ff3147 244static int g_allow_regfunc;
92d715b6 245static int g_quiet_pp;
9af2d373 246static int g_header_mode;
92d715b6 247
91977a1c 248#define ferr(op_, fmt, ...) do { \
bfacdc83 249 printf("%s:%d: error %u: [%s] '%s': " fmt, asmfn, (op_)->asmln, \
250 __LINE__, g_func, dump_op(op_), ##__VA_ARGS__); \
33c35af6 251 fcloseall(); \
91977a1c 252 exit(1); \
253} while (0)
de50b98b 254#define fnote(op_, fmt, ...) \
8eb12e72 255 printf("%s:%d: note: [%s] '%s': " fmt, asmfn, (op_)->asmln, g_func, \
de50b98b 256 dump_op(op_), ##__VA_ARGS__)
91977a1c 257
26677139 258#define ferr_assert(op_, cond) do { \
2b70f6d3 259 if (!(cond)) ferr(op_, "assertion '%s' failed\n", #cond); \
26677139 260} while (0)
261
90307a99 262const char *regs_r32[] = {
263 "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "esp",
264 // not r32, but list here for easy parsing and printing
265 "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
266};
91977a1c 267const char *regs_r16[] = { "ax", "bx", "cx", "dx", "si", "di", "bp", "sp" };
268const char *regs_r8l[] = { "al", "bl", "cl", "dl" };
269const char *regs_r8h[] = { "ah", "bh", "ch", "dh" };
270
271enum x86_regs { xUNSPEC = -1, xAX, xBX, xCX, xDX, xSI, xDI, xBP, xSP };
272
69a3cdfc 273// possible basic comparison types (without inversion)
274enum parsed_flag_op {
275 PFO_O, // 0 OF=1
276 PFO_C, // 2 CF=1
277 PFO_Z, // 4 ZF=1
278 PFO_BE, // 6 CF=1||ZF=1
279 PFO_S, // 8 SF=1
280 PFO_P, // a PF=1
281 PFO_L, // c SF!=OF
282 PFO_LE, // e ZF=1||SF!=OF
283};
284
90307a99 285#define PFOB_O (1 << PFO_O)
286#define PFOB_C (1 << PFO_C)
287#define PFOB_Z (1 << PFO_Z)
288#define PFOB_S (1 << PFO_S)
289
69a3cdfc 290static const char *parsed_flag_op_names[] = {
291 "o", "c", "z", "be", "s", "p", "l", "le"
292};
293
91977a1c 294static int char_array_i(const char *array[], size_t len, const char *s)
295{
296 int i;
c36e914d 297
91977a1c 298 for (i = 0; i < len; i++)
299 if (IS(s, array[i]))
300 return i;
c36e914d 301
91977a1c 302 return -1;
303}
304
63df67be 305static void printf_number(char *buf, size_t buf_size,
306 unsigned long number)
91977a1c 307{
5101a5f9 308 // output in C-friendly form
309 snprintf(buf, buf_size, number < 10 ? "%lu" : "0x%02lx", number);
310}
91977a1c 311
fdd5548a 312static int check_segment_prefix(const char *s)
313{
314 if (s[0] == 0 || s[1] != 's' || s[2] != ':')
315 return 0;
316
317 switch (s[0]) {
318 case 'c': return 1;
319 case 'd': return 2;
320 case 's': return 3;
321 case 'e': return 4;
322 case 'f': return 5;
323 case 'g': return 6;
324 default: return 0;
325 }
326}
327
5101a5f9 328static int parse_reg(enum opr_lenmod *reg_lmod, const char *s)
329{
330 int reg;
91977a1c 331
5101a5f9 332 reg = char_array_i(regs_r32, ARRAY_SIZE(regs_r32), s);
90307a99 333 if (reg >= 8) {
334 *reg_lmod = OPLM_QWORD;
335 return reg;
336 }
5101a5f9 337 if (reg >= 0) {
338 *reg_lmod = OPLM_DWORD;
339 return reg;
91977a1c 340 }
5101a5f9 341 reg = char_array_i(regs_r16, ARRAY_SIZE(regs_r16), s);
342 if (reg >= 0) {
343 *reg_lmod = OPLM_WORD;
344 return reg;
345 }
346 reg = char_array_i(regs_r8h, ARRAY_SIZE(regs_r8h), s);
347 if (reg >= 0) {
348 *reg_lmod = OPLM_BYTE;
349 return reg;
350 }
351 reg = char_array_i(regs_r8l, ARRAY_SIZE(regs_r8l), s);
352 if (reg >= 0) {
353 *reg_lmod = OPLM_BYTE;
354 return reg;
850c9265 355 }
356
357 return -1;
91977a1c 358}
359
5101a5f9 360static int parse_indmode(char *name, int *regmask, int need_c_cvt)
361{
362 enum opr_lenmod lmod;
363 char cvtbuf[256];
364 char *d = cvtbuf;
365 char *s = name;
366 char w[64];
367 long number;
368 int reg;
369 int c = 0;
370
371 *d = 0;
372
373 while (*s != 0) {
374 d += strlen(d);
375 while (my_isblank(*s))
376 s++;
377 for (; my_issep(*s); d++, s++)
378 *d = *s;
379 while (my_isblank(*s))
380 s++;
381 *d = 0;
382
fdd5548a 383 // skip '?s:' prefixes
384 if (check_segment_prefix(s))
87bf6cec 385 s += 3;
386
5101a5f9 387 s = next_idt(w, sizeof(w), s);
388 if (w[0] == 0)
389 break;
390 c++;
391
392 reg = parse_reg(&lmod, w);
393 if (reg >= 0) {
394 *regmask |= 1 << reg;
395 goto pass;
396 }
397
398 if ('0' <= w[0] && w[0] <= '9') {
399 number = parse_number(w);
400 printf_number(d, sizeof(cvtbuf) - (d - cvtbuf), number);
401 continue;
402 }
403
404 // probably some label/identifier - pass
405
406pass:
407 snprintf(d, sizeof(cvtbuf) - (d - cvtbuf), "%s", w);
408 }
409
410 if (need_c_cvt)
411 strcpy(name, cvtbuf);
412
413 return c;
414}
415
4c45fa73 416static int is_reg_in_str(const char *s)
417{
418 int i;
419
420 if (strlen(s) < 3 || (s[3] && !my_issep(s[3]) && !my_isblank(s[3])))
421 return 0;
422
423 for (i = 0; i < ARRAY_SIZE(regs_r32); i++)
424 if (!strncmp(s, regs_r32[i], 3))
425 return 1;
426
427 return 0;
428}
429
09bc6fd5 430static const char *parse_stack_el(const char *name, char *extra_reg,
431 int early_try)
d4e3b5db 432{
4c45fa73 433 const char *p, *p2, *s;
1bafb621 434 char *endp = NULL;
d4e3b5db 435 char buf[32];
1bafb621 436 long val;
d4e3b5db 437 int len;
438
09bc6fd5 439 if (g_bp_frame || early_try)
440 {
441 p = name;
442 if (IS_START(p + 3, "+ebp+") && is_reg_in_str(p)) {
443 p += 4;
444 if (extra_reg != NULL) {
445 strncpy(extra_reg, name, 3);
446 extra_reg[4] = 0;
447 }
4c45fa73 448 }
4c45fa73 449
09bc6fd5 450 if (IS_START(p, "ebp+")) {
451 p += 4;
4c45fa73 452
09bc6fd5 453 p2 = strchr(p, '+');
454 if (p2 != NULL && is_reg_in_str(p)) {
455 if (extra_reg != NULL) {
456 strncpy(extra_reg, p, p2 - p);
457 extra_reg[p2 - p] = 0;
458 }
459 p = p2 + 1;
4c45fa73 460 }
4c45fa73 461
09bc6fd5 462 if (!('0' <= *p && *p <= '9'))
463 return p;
4c45fa73 464
09bc6fd5 465 return NULL;
466 }
4c45fa73 467 }
468
39b168b8 469 if (!IS_START(name, "esp+"))
d4e3b5db 470 return NULL;
471
037f4971 472 s = name + 4;
473 p = strchr(s, '+');
d4e3b5db 474 if (p) {
037f4971 475 if (is_reg_in_str(s)) {
476 if (extra_reg != NULL) {
477 strncpy(extra_reg, s, p - s);
478 extra_reg[p - s] = 0;
479 }
480 s = p + 1;
481 p = strchr(s, '+');
482 if (p == NULL)
483 aerr("%s IDA stackvar not set?\n", __func__);
484 }
1bafb621 485 if (!('0' <= *s && *s <= '9')) {
037f4971 486 aerr("%s IDA stackvar offset not set?\n", __func__);
d4e3b5db 487 return NULL;
1bafb621 488 }
489 if (s[0] == '0' && s[1] == 'x')
490 s += 2;
491 len = p - s;
d4e3b5db 492 if (len < sizeof(buf) - 1) {
1bafb621 493 strncpy(buf, s, len);
d4e3b5db 494 buf[len] = 0;
1bafb621 495 val = strtol(buf, &endp, 16);
496 if (val == 0 || *endp != 0) {
497 aerr("%s num parse fail for '%s'\n", __func__, buf);
498 return NULL;
499 }
d4e3b5db 500 }
501 p++;
502 }
503 else
504 p = name + 4;
505
506 if ('0' <= *p && *p <= '9')
507 return NULL;
508
509 return p;
510}
511
850c9265 512static int guess_lmod_from_name(struct parsed_opr *opr)
513{
04abc5d6 514 if (IS_START(opr->name, "dword_") || IS_START(opr->name, "off_")) {
850c9265 515 opr->lmod = OPLM_DWORD;
516 return 1;
517 }
04abc5d6 518 if (IS_START(opr->name, "word_")) {
850c9265 519 opr->lmod = OPLM_WORD;
520 return 1;
521 }
04abc5d6 522 if (IS_START(opr->name, "byte_")) {
850c9265 523 opr->lmod = OPLM_BYTE;
524 return 1;
525 }
04abc5d6 526 if (IS_START(opr->name, "qword_")) {
90307a99 527 opr->lmod = OPLM_QWORD;
528 return 1;
529 }
850c9265 530 return 0;
531}
532
3ebea2cf 533static int guess_lmod_from_c_type(enum opr_lenmod *lmod,
534 const struct parsed_type *c_type)
06c5d854 535{
06c5d854 536 static const char *dword_types[] = {
c0de9015 537 "uint32_t", "int", "_DWORD", "UINT_PTR", "DWORD",
4741fdfe 538 "WPARAM", "LPARAM", "UINT", "__int32",
09bc6fd5 539 "LONG", "HIMC", "BOOL", "size_t",
feb0ee5d 540 "float",
06c5d854 541 };
542 static const char *word_types[] = {
fe18709a 543 "uint16_t", "int16_t", "_WORD", "WORD",
2b43685d 544 "unsigned __int16", "__int16",
06c5d854 545 };
546 static const char *byte_types[] = {
2b43685d 547 "uint8_t", "int8_t", "char",
89ff3147 548 "unsigned __int8", "__int8", "BYTE", "_BYTE",
4741fdfe 549 "CHAR", "_UNKNOWN",
b4878d2b 550 // structures.. deal the same as with _UNKNOWN for now
551 "CRITICAL_SECTION",
06c5d854 552 };
3ebea2cf 553 const char *n;
06c5d854 554 int i;
555
3ebea2cf 556 if (c_type->is_ptr) {
557 *lmod = OPLM_DWORD;
06c5d854 558 return 1;
559 }
560
3ebea2cf 561 n = skip_type_mod(c_type->name);
06c5d854 562
3ebea2cf 563 for (i = 0; i < ARRAY_SIZE(dword_types); i++) {
564 if (IS(n, dword_types[i])) {
565 *lmod = OPLM_DWORD;
06c5d854 566 return 1;
567 }
568 }
569
570 for (i = 0; i < ARRAY_SIZE(word_types); i++) {
3ebea2cf 571 if (IS(n, word_types[i])) {
572 *lmod = OPLM_WORD;
06c5d854 573 return 1;
574 }
575 }
576
577 for (i = 0; i < ARRAY_SIZE(byte_types); i++) {
3ebea2cf 578 if (IS(n, byte_types[i])) {
579 *lmod = OPLM_BYTE;
06c5d854 580 return 1;
581 }
582 }
583
06c5d854 584 return 0;
585}
586
c7ed83dd 587static char *default_cast_to(char *buf, size_t buf_size,
588 struct parsed_opr *opr)
589{
590 buf[0] = 0;
591
592 if (!opr->is_ptr)
593 return buf;
594 if (opr->pp == NULL || opr->pp->type.name == NULL
595 || opr->pp->is_fptr)
596 {
597 snprintf(buf, buf_size, "%s", "(void *)");
598 return buf;
599 }
600
601 snprintf(buf, buf_size, "(%s)", opr->pp->type.name);
602 return buf;
603}
604
4c45fa73 605static enum opr_type lmod_from_directive(const char *d)
606{
607 if (IS(d, "dd"))
608 return OPLM_DWORD;
609 else if (IS(d, "dw"))
610 return OPLM_WORD;
611 else if (IS(d, "db"))
612 return OPLM_BYTE;
613
614 aerr("unhandled directive: '%s'\n", d);
615 return OPLM_UNSPEC;
616}
617
5101a5f9 618static void setup_reg_opr(struct parsed_opr *opr, int reg, enum opr_lenmod lmod,
619 int *regmask)
620{
621 opr->type = OPT_REG;
622 opr->reg = reg;
623 opr->lmod = lmod;
624 *regmask |= 1 << reg;
625}
626
39b168b8 627static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
628 int *extra_offs);
87bf6cec 629
69a3cdfc 630static int parse_operand(struct parsed_opr *opr,
631 int *regmask, int *regmask_indirect,
1bafb621 632 char words[16][256], int wordc, int w, unsigned int op_flags)
c36e914d 633{
92d715b6 634 const struct parsed_proto *pp = NULL;
850c9265 635 enum opr_lenmod tmplmod;
63df67be 636 unsigned long number;
89ff3147 637 char buf[256];
850c9265 638 int ret, len;
1bafb621 639 int wordc_in;
89ff3147 640 char *p;
850c9265 641 int i;
c36e914d 642
1bafb621 643 if (w >= wordc)
644 aerr("parse_operand w %d, wordc %d\n", w, wordc);
c36e914d 645
1bafb621 646 opr->reg = xUNSPEC;
91977a1c 647
1bafb621 648 for (i = w; i < wordc; i++) {
649 len = strlen(words[i]);
650 if (words[i][len - 1] == ',') {
651 words[i][len - 1] = 0;
652 wordc = i + 1;
653 break;
654 }
655 }
c36e914d 656
1bafb621 657 wordc_in = wordc - w;
c36e914d 658
1bafb621 659 if ((op_flags & OPF_JMP) && wordc_in > 0
660 && !('0' <= words[w][0] && words[w][0] <= '9'))
661 {
662 const char *label = NULL;
663
664 if (wordc_in == 3 && !strncmp(words[w], "near", 4)
665 && IS(words[w + 1], "ptr"))
666 label = words[w + 2];
667 else if (wordc_in == 2 && IS(words[w], "short"))
668 label = words[w + 1];
669 else if (wordc_in == 1
670 && strchr(words[w], '[') == NULL
671 && parse_reg(&tmplmod, words[w]) < 0)
672 label = words[w];
673
674 if (label != NULL) {
675 opr->type = OPT_LABEL;
fdd5548a 676 ret = check_segment_prefix(label);
677 if (ret != 0) {
678 if (ret >= 5)
679 aerr("fs/gs used\n");
ddaf8bd7 680 opr->had_ds = 1;
39b168b8 681 label += 3;
ddaf8bd7 682 }
1bafb621 683 strcpy(opr->name, label);
684 return wordc;
685 }
686 }
c36e914d 687
1bafb621 688 if (wordc_in >= 3) {
689 if (IS(words[w + 1], "ptr")) {
690 if (IS(words[w], "dword"))
691 opr->lmod = OPLM_DWORD;
692 else if (IS(words[w], "word"))
693 opr->lmod = OPLM_WORD;
694 else if (IS(words[w], "byte"))
695 opr->lmod = OPLM_BYTE;
90307a99 696 else if (IS(words[w], "qword"))
697 opr->lmod = OPLM_QWORD;
1bafb621 698 else
699 aerr("type parsing failed\n");
700 w += 2;
701 wordc_in = wordc - w;
702 }
703 }
704
39b168b8 705 if (wordc_in == 2) {
706 if (IS(words[w], "offset")) {
707 opr->type = OPT_OFFSET;
27ebfaed 708 opr->lmod = OPLM_DWORD;
39b168b8 709 strcpy(opr->name, words[w + 1]);
27ebfaed 710 pp = proto_parse(g_fhdr, opr->name, 1);
711 goto do_label;
39b168b8 712 }
713 if (IS(words[w], "(offset")) {
89ff3147 714 p = strchr(words[w + 1], ')');
39b168b8 715 if (p == NULL)
716 aerr("parse of bracketed offset failed\n");
717 *p = 0;
718 opr->type = OPT_OFFSET;
719 strcpy(opr->name, words[w + 1]);
720 return wordc;
721 }
1bafb621 722 }
c36e914d 723
1bafb621 724 if (wordc_in != 1)
850c9265 725 aerr("parse_operand 1 word expected\n");
c36e914d 726
fdd5548a 727 ret = check_segment_prefix(words[w]);
728 if (ret != 0) {
729 if (ret >= 5)
730 aerr("fs/gs used\n");
ddaf8bd7 731 opr->had_ds = 1;
89ff3147 732 memmove(words[w], words[w] + 3, strlen(words[w]) - 2);
ddaf8bd7 733 }
89ff3147 734 strcpy(opr->name, words[w]);
c36e914d 735
850c9265 736 if (words[w][0] == '[') {
737 opr->type = OPT_REGMEM;
738 ret = sscanf(words[w], "[%[^]]]", opr->name);
739 if (ret != 1)
740 aerr("[] parse failure\n");
87bf6cec 741
5101a5f9 742 parse_indmode(opr->name, regmask_indirect, 1);
09bc6fd5 743 if (opr->lmod == OPLM_UNSPEC && parse_stack_el(opr->name, NULL, 1))
744 {
87bf6cec 745 // might be an equ
d4e3b5db 746 struct parsed_equ *eq =
09bc6fd5 747 equ_find(NULL, parse_stack_el(opr->name, NULL, 1), &i);
87bf6cec 748 if (eq)
749 opr->lmod = eq->lmod;
750 }
850c9265 751 return wordc;
752 }
753 else if (strchr(words[w], '[')) {
754 // label[reg] form
89ff3147 755 p = strchr(words[w], '[');
850c9265 756 opr->type = OPT_REGMEM;
89ff3147 757 parse_indmode(p, regmask_indirect, 0);
758 strncpy(buf, words[w], p - words[w]);
759 buf[p - words[w]] = 0;
760 pp = proto_parse(g_fhdr, buf, 1);
761 goto do_label;
850c9265 762 }
763 else if (('0' <= words[w][0] && words[w][0] <= '9')
764 || words[w][0] == '-')
765 {
5101a5f9 766 number = parse_number(words[w]);
91977a1c 767 opr->type = OPT_CONST;
5101a5f9 768 opr->val = number;
769 printf_number(opr->name, sizeof(opr->name), number);
91977a1c 770 return wordc;
850c9265 771 }
c36e914d 772
5101a5f9 773 ret = parse_reg(&tmplmod, opr->name);
774 if (ret >= 0) {
775 setup_reg_opr(opr, ret, tmplmod, regmask);
850c9265 776 return wordc;
777 }
778
779 // most likely var in data segment
780 opr->type = OPT_LABEL;
92d715b6 781 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
89ff3147 782
783do_label:
bd96f656 784 if (pp != NULL) {
1cd4a663 785 if (pp->is_fptr || pp->is_func) {
06c5d854 786 opr->lmod = OPLM_DWORD;
787 opr->is_ptr = 1;
788 }
2b43685d 789 else {
840257f6 790 tmplmod = OPLM_UNSPEC;
bd96f656 791 if (!guess_lmod_from_c_type(&tmplmod, &pp->type))
2b43685d 792 anote("unhandled C type '%s' for '%s'\n",
bd96f656 793 pp->type.name, opr->name);
2b43685d 794
a3684be1 795 if (opr->lmod == OPLM_UNSPEC) {
2b43685d 796 opr->lmod = tmplmod;
a3684be1 797 opr->type_from_var = 1;
798 }
2b43685d 799 else if (opr->lmod != tmplmod) {
800 opr->size_mismatch = 1;
801 if (tmplmod < opr->lmod)
802 opr->size_lt = 1;
803 }
a652aa9f 804 opr->is_ptr = pp->type.is_ptr;
3ebea2cf 805 }
bd96f656 806 opr->is_array = pp->type.is_array;
06c5d854 807 }
c7ed83dd 808 opr->pp = pp;
06c5d854 809
850c9265 810 if (opr->lmod == OPLM_UNSPEC)
811 guess_lmod_from_name(opr);
850c9265 812 return wordc;
c36e914d 813}
814
33c35af6 815static const struct {
816 const char *name;
817 unsigned int flags;
818} pref_table[] = {
819 { "rep", OPF_REP },
7ba45c34 820 { "repe", OPF_REP|OPF_REPZ },
821 { "repz", OPF_REP|OPF_REPZ },
822 { "repne", OPF_REP|OPF_REPNZ },
823 { "repnz", OPF_REP|OPF_REPNZ },
037f4971 824 { "lock", OPF_LOCK }, // ignored for now..
33c35af6 825};
826
5c024ef7 827#define OPF_CJMP_CC (OPF_JMP|OPF_CJMP|OPF_CC)
828
c36e914d 829static const struct {
850c9265 830 const char *name;
831 enum op_op op;
092f64e1 832 unsigned short minopr;
833 unsigned short maxopr;
69a3cdfc 834 unsigned int flags;
092f64e1 835 unsigned char pfo;
836 unsigned char pfo_inv;
c36e914d 837} op_table[] = {
33c35af6 838 { "nop", OP_NOP, 0, 0, 0 },
69a3cdfc 839 { "push", OP_PUSH, 1, 1, 0 },
840 { "pop", OP_POP, 1, 1, OPF_DATA },
591721d7 841 { "leave",OP_LEAVE, 0, 0, OPF_DATA },
69a3cdfc 842 { "mov" , OP_MOV, 2, 2, OPF_DATA },
843 { "lea", OP_LEA, 2, 2, OPF_DATA },
844 { "movzx",OP_MOVZX, 2, 2, OPF_DATA },
845 { "movsx",OP_MOVSX, 2, 2, OPF_DATA },
108e9fe3 846 { "xchg", OP_XCHG, 2, 2, OPF_DATA },
69a3cdfc 847 { "not", OP_NOT, 1, 1, OPF_DATA },
04abc5d6 848 { "xlat", OP_XLAT, 0, 0, OPF_DATA },
5101a5f9 849 { "cdq", OP_CDQ, 0, 0, OPF_DATA },
092f64e1 850 { "lodsb",OP_LODS, 0, 0, OPF_DATA },
851 { "lodsw",OP_LODS, 0, 0, OPF_DATA },
852 { "lodsd",OP_LODS, 0, 0, OPF_DATA },
33c35af6 853 { "stosb",OP_STOS, 0, 0, OPF_DATA },
854 { "stosw",OP_STOS, 0, 0, OPF_DATA },
855 { "stosd",OP_STOS, 0, 0, OPF_DATA },
d4e3b5db 856 { "movsb",OP_MOVS, 0, 0, OPF_DATA },
857 { "movsw",OP_MOVS, 0, 0, OPF_DATA },
858 { "movsd",OP_MOVS, 0, 0, OPF_DATA },
7ba45c34 859 { "cmpsb",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
860 { "cmpsw",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
861 { "cmpsd",OP_CMPS, 0, 0, OPF_DATA|OPF_FLAGS },
591721d7 862 { "scasb",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
863 { "scasw",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
864 { "scasd",OP_SCAS, 0, 0, OPF_DATA|OPF_FLAGS },
865 { "std", OP_STD, 0, 0, OPF_DATA }, // special flag
866 { "cld", OP_CLD, 0, 0, OPF_DATA },
69a3cdfc 867 { "add", OP_ADD, 2, 2, OPF_DATA|OPF_FLAGS },
868 { "sub", OP_SUB, 2, 2, OPF_DATA|OPF_FLAGS },
869 { "and", OP_AND, 2, 2, OPF_DATA|OPF_FLAGS },
870 { "or", OP_OR, 2, 2, OPF_DATA|OPF_FLAGS },
871 { "xor", OP_XOR, 2, 2, OPF_DATA|OPF_FLAGS },
872 { "shl", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
873 { "shr", OP_SHR, 2, 2, OPF_DATA|OPF_FLAGS },
874 { "sal", OP_SHL, 2, 2, OPF_DATA|OPF_FLAGS },
875 { "sar", OP_SAR, 2, 2, OPF_DATA|OPF_FLAGS },
04abc5d6 876 { "shld", OP_SHLD, 3, 3, OPF_DATA|OPF_FLAGS },
3b2f4044 877 { "shrd", OP_SHRD, 3, 3, OPF_DATA|OPF_FLAGS },
d4e3b5db 878 { "rol", OP_ROL, 2, 2, OPF_DATA|OPF_FLAGS },
879 { "ror", OP_ROR, 2, 2, OPF_DATA|OPF_FLAGS },
092f64e1 880 { "rcl", OP_RCL, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
881 { "rcr", OP_RCR, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
882 { "adc", OP_ADC, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
883 { "sbb", OP_SBB, 2, 2, OPF_DATA|OPF_FLAGS|OPF_CC, PFO_C },
1f84f6b3 884 { "bsf", OP_BSF, 2, 2, OPF_DATA|OPF_FLAGS },
69a3cdfc 885 { "inc", OP_INC, 1, 1, OPF_DATA|OPF_FLAGS },
886 { "dec", OP_DEC, 1, 1, OPF_DATA|OPF_FLAGS },
5101a5f9 887 { "neg", OP_NEG, 1, 1, OPF_DATA|OPF_FLAGS },
888 { "mul", OP_MUL, 1, 1, OPF_DATA|OPF_FLAGS },
69a3cdfc 889 { "imul", OP_IMUL, 1, 3, OPF_DATA|OPF_FLAGS },
5101a5f9 890 { "div", OP_DIV, 1, 1, OPF_DATA|OPF_FLAGS },
891 { "idiv", OP_IDIV, 1, 1, OPF_DATA|OPF_FLAGS },
69a3cdfc 892 { "test", OP_TEST, 2, 2, OPF_FLAGS },
893 { "cmp", OP_CMP, 2, 2, OPF_FLAGS },
a3684be1 894 { "retn", OP_RET, 0, 1, OPF_TAIL },
de50b98b 895 { "call", OP_CALL, 1, 1, OPF_JMP|OPF_DATA|OPF_FLAGS },
69a3cdfc 896 { "jmp", OP_JMP, 1, 1, OPF_JMP },
5c024ef7 897 { "jecxz",OP_JECXZ, 1, 1, OPF_JMP|OPF_CJMP },
04abc5d6 898 { "loop", OP_LOOP, 1, 1, OPF_JMP|OPF_CJMP|OPF_DATA },
092f64e1 899 { "jo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 0 }, // 70 OF=1
900 { "jno", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_O, 1 }, // 71 OF=0
901 { "jc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72 CF=1
902 { "jb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 0 }, // 72
903 { "jnc", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73 CF=0
904 { "jnb", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
905 { "jae", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_C, 1 }, // 73
906 { "jz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74 ZF=1
907 { "je", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 0 }, // 74
908 { "jnz", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75 ZF=0
909 { "jne", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_Z, 1 }, // 75
910 { "jbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76 CF=1||ZF=1
911 { "jna", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 0 }, // 76
912 { "ja", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77 CF=0&&ZF=0
913 { "jnbe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_BE, 1 }, // 77
914 { "js", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 0 }, // 78 SF=1
915 { "jns", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_S, 1 }, // 79 SF=0
916 { "jp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a PF=1
917 { "jpe", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 0 }, // 7a
918 { "jnp", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b PF=0
919 { "jpo", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_P, 1 }, // 7b
920 { "jl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c SF!=OF
921 { "jnge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 0 }, // 7c
922 { "jge", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d SF=OF
923 { "jnl", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_L, 1 }, // 7d
924 { "jle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e ZF=1||SF!=OF
925 { "jng", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 0 }, // 7e
926 { "jg", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f ZF=0&&SF=OF
927 { "jnle", OP_JCC, 1, 1, OPF_CJMP_CC, PFO_LE, 1 }, // 7f
928 { "seto", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 0 },
929 { "setno", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_O, 1 },
930 { "setc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
931 { "setb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 0 },
932 { "setnc", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
933 { "setae", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
934 { "setnb", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_C, 1 },
935 { "setz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
936 { "sete", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 0 },
937 { "setnz", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
938 { "setne", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_Z, 1 },
939 { "setbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
940 { "setna", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 0 },
941 { "seta", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
942 { "setnbe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_BE, 1 },
943 { "sets", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 0 },
944 { "setns", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_S, 1 },
945 { "setp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
946 { "setpe", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 0 },
947 { "setnp", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
948 { "setpo", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_P, 1 },
949 { "setl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
950 { "setnge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 0 },
951 { "setge", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
952 { "setnl", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_L, 1 },
953 { "setle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
954 { "setng", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 0 },
955 { "setg", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
956 { "setnle", OP_SCC, 1, 1, OPF_DATA|OPF_CC, PFO_LE, 1 },
90307a99 957 // x87
958 // mmx
959 { "emms", OP_EMMS, 0, 0, OPF_DATA },
960 { "movq", OP_MOV, 2, 2, OPF_DATA },
2c10ea1f 961 // must be last
962 { "ud2", OP_UD2 },
69a3cdfc 963};
c36e914d 964
965static void parse_op(struct parsed_op *op, char words[16][256], int wordc)
966{
bfa4a6ee 967 enum opr_lenmod lmod = OPLM_UNSPEC;
33c35af6 968 int prefix_flags = 0;
69a3cdfc 969 int regmask_ind;
970 int regmask;
33c35af6 971 int op_w = 0;
91977a1c 972 int opr = 0;
33c35af6 973 int w = 0;
91977a1c 974 int i;
c36e914d 975
33c35af6 976 for (i = 0; i < ARRAY_SIZE(pref_table); i++) {
977 if (IS(words[w], pref_table[i].name)) {
978 prefix_flags = pref_table[i].flags;
979 break;
980 }
981 }
982
983 if (prefix_flags) {
984 if (wordc <= 1)
985 aerr("lone prefix: '%s'\n", words[0]);
986 w++;
987 }
988
989 op_w = w;
91977a1c 990 for (i = 0; i < ARRAY_SIZE(op_table); i++) {
33c35af6 991 if (IS(words[w], op_table[i].name))
69a3cdfc 992 break;
993 }
c36e914d 994
2c10ea1f 995 if (i == ARRAY_SIZE(op_table)) {
30c8c549 996 if (!g_skip_func)
997 aerr("unhandled op: '%s'\n", words[0]);
2c10ea1f 998 i--; // OP_UD2
999 }
33c35af6 1000 w++;
c36e914d 1001
69a3cdfc 1002 op->op = op_table[i].op;
33c35af6 1003 op->flags = op_table[i].flags | prefix_flags;
092f64e1 1004 op->pfo = op_table[i].pfo;
1005 op->pfo_inv = op_table[i].pfo_inv;
69a3cdfc 1006 op->regmask_src = op->regmask_dst = 0;
8eb12e72 1007 op->asmln = asmln;
69a3cdfc 1008
2c10ea1f 1009 if (op->op == OP_UD2)
1010 return;
1011
92d715b6 1012 for (opr = 0; opr < op_table[i].maxopr; opr++) {
1013 if (opr >= op_table[i].minopr && w >= wordc)
1014 break;
1015
69a3cdfc 1016 regmask = regmask_ind = 0;
1017 w = parse_operand(&op->operand[opr], &regmask, &regmask_ind,
1018 words, wordc, w, op->flags);
1019
1020 if (opr == 0 && (op->flags & OPF_DATA))
1021 op->regmask_dst = regmask;
92d715b6 1022 else
1023 op->regmask_src |= regmask;
1024 op->regmask_src |= regmask_ind;
91977a1c 1025 }
c36e914d 1026
91977a1c 1027 if (w < wordc)
1028 aerr("parse_op %s incomplete: %d/%d\n",
1029 words[0], w, wordc);
5101a5f9 1030
1031 // special cases
1032 op->operand_cnt = opr;
1033 if (!strncmp(op_table[i].name, "set", 3))
1034 op->operand[0].lmod = OPLM_BYTE;
1035
5101a5f9 1036 switch (op->op) {
92d715b6 1037 // first operand is not dst
1038 case OP_CMP:
1039 case OP_TEST:
1040 op->regmask_src |= op->regmask_dst;
1041 op->regmask_dst = 0;
1042 break;
1043
1044 // first operand is src too
1045 case OP_NOT:
1046 case OP_ADD:
1047 case OP_AND:
1048 case OP_OR:
1049 case OP_RCL:
1050 case OP_RCR:
1051 case OP_ADC:
1052 case OP_INC:
1053 case OP_DEC:
1054 case OP_NEG:
1055 // more below..
1056 op->regmask_src |= op->regmask_dst;
1057 break;
1058
1059 // special
1060 case OP_XCHG:
1061 op->regmask_src |= op->regmask_dst;
1062 op->regmask_dst |= op->regmask_src;
1063 goto check_align;
1064
1065 case OP_SUB:
1066 case OP_SBB:
1067 case OP_XOR:
1068 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
1069 && op->operand[0].lmod == op->operand[1].lmod
1070 && op->operand[0].reg == op->operand[1].reg
1071 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
1072 {
1073 op->regmask_src = 0;
1074 }
1075 else
1076 op->regmask_src |= op->regmask_dst;
1077 break;
1078
1079 // ops with implicit argumets
04abc5d6 1080 case OP_XLAT:
1081 op->operand_cnt = 2;
1082 setup_reg_opr(&op->operand[0], xAX, OPLM_BYTE, &op->regmask_src);
1083 op->regmask_dst = op->regmask_src;
1084 setup_reg_opr(&op->operand[1], xDX, OPLM_DWORD, &op->regmask_src);
1085 break;
1086
5101a5f9 1087 case OP_CDQ:
1088 op->operand_cnt = 2;
1089 setup_reg_opr(&op->operand[0], xDX, OPLM_DWORD, &op->regmask_dst);
1090 setup_reg_opr(&op->operand[1], xAX, OPLM_DWORD, &op->regmask_src);
1091 break;
1092
092f64e1 1093 case OP_LODS:
33c35af6 1094 case OP_STOS:
591721d7 1095 case OP_SCAS:
33c35af6 1096 if (op->operand_cnt != 0)
1097 break;
591721d7 1098 if (words[op_w][4] == 'b')
33c35af6 1099 lmod = OPLM_BYTE;
591721d7 1100 else if (words[op_w][4] == 'w')
33c35af6 1101 lmod = OPLM_WORD;
591721d7 1102 else if (words[op_w][4] == 'd')
33c35af6 1103 lmod = OPLM_DWORD;
1104 op->operand_cnt = 3;
092f64e1 1105 setup_reg_opr(&op->operand[0], op->op == OP_LODS ? xSI : xDI,
1106 lmod, &op->regmask_src);
d4e3b5db 1107 setup_reg_opr(&op->operand[1], xCX, OPLM_DWORD, &op->regmask_src);
1108 op->regmask_dst = op->regmask_src;
092f64e1 1109 setup_reg_opr(&op->operand[2], xAX, OPLM_DWORD,
1110 op->op == OP_LODS ? &op->regmask_dst : &op->regmask_src);
33c35af6 1111 break;
1112
d4e3b5db 1113 case OP_MOVS:
7ba45c34 1114 case OP_CMPS:
d4e3b5db 1115 if (op->operand_cnt != 0)
1116 break;
7ba45c34 1117 if (words[op_w][4] == 'b')
d4e3b5db 1118 lmod = OPLM_BYTE;
7ba45c34 1119 else if (words[op_w][4] == 'w')
d4e3b5db 1120 lmod = OPLM_WORD;
7ba45c34 1121 else if (words[op_w][4] == 'd')
d4e3b5db 1122 lmod = OPLM_DWORD;
1123 op->operand_cnt = 3;
1124 setup_reg_opr(&op->operand[0], xDI, lmod, &op->regmask_src);
1125 setup_reg_opr(&op->operand[1], xSI, OPLM_DWORD, &op->regmask_src);
1126 setup_reg_opr(&op->operand[2], xCX, OPLM_DWORD, &op->regmask_src);
1127 op->regmask_dst = op->regmask_src;
1128 break;
1129
04abc5d6 1130 case OP_LOOP:
1131 op->regmask_dst = 1 << xCX;
1132 // fallthrough
5c024ef7 1133 case OP_JECXZ:
04abc5d6 1134 op->operand_cnt = 2;
5c024ef7 1135 op->regmask_src = 1 << xCX;
04abc5d6 1136 op->operand[1].type = OPT_REG;
1137 op->operand[1].reg = xCX;
1138 op->operand[1].lmod = OPLM_DWORD;
5c024ef7 1139 break;
1140
5101a5f9 1141 case OP_IMUL:
1142 if (op->operand_cnt != 1)
1143 break;
1144 // fallthrough
1145 case OP_MUL:
1146 // singleop mul
92d715b6 1147 op->regmask_src |= op->regmask_dst;
5101a5f9 1148 op->regmask_dst = (1 << xDX) | (1 << xAX);
5101a5f9 1149 if (op->operand[0].lmod == OPLM_UNSPEC)
1150 op->operand[0].lmod = OPLM_DWORD;
1151 break;
1152
1153 case OP_DIV:
1154 case OP_IDIV:
1155 // we could set up operands for edx:eax, but there is no real need to
1156 // (see is_opr_modified())
92d715b6 1157 op->regmask_src |= op->regmask_dst;
1158 op->regmask_dst = (1 << xDX) | (1 << xAX);
5101a5f9 1159 if (op->operand[0].lmod == OPLM_UNSPEC)
1160 op->operand[0].lmod = OPLM_DWORD;
1161 break;
1162
1163 case OP_SHL:
1164 case OP_SHR:
1165 case OP_SAR:
d4e3b5db 1166 case OP_ROL:
1167 case OP_ROR:
92d715b6 1168 op->regmask_src |= op->regmask_dst;
5101a5f9 1169 if (op->operand[1].lmod == OPLM_UNSPEC)
1170 op->operand[1].lmod = OPLM_BYTE;
1171 break;
1172
3b2f4044 1173 case OP_SHRD:
92d715b6 1174 op->regmask_src |= op->regmask_dst;
3b2f4044 1175 if (op->operand[2].lmod == OPLM_UNSPEC)
1176 op->operand[2].lmod = OPLM_BYTE;
1177 break;
1178
7ba45c34 1179 case OP_PUSH:
92d715b6 1180 op->regmask_src |= op->regmask_dst;
1181 op->regmask_dst = 0;
7ba45c34 1182 if (op->operand[0].lmod == OPLM_UNSPEC
1183 && (op->operand[0].type == OPT_CONST
1184 || op->operand[0].type == OPT_OFFSET
1185 || op->operand[0].type == OPT_LABEL))
1186 op->operand[0].lmod = OPLM_DWORD;
1187 break;
1188
3ebea2cf 1189 // alignment
1190 case OP_MOV:
092f64e1 1191 check_align:
3ebea2cf 1192 if (op->operand[0].type == OPT_REG && op->operand[1].type == OPT_REG
092f64e1 1193 && op->operand[0].lmod == op->operand[1].lmod
1194 && op->operand[0].reg == op->operand[1].reg
92d715b6 1195 && IS(op->operand[0].name, op->operand[1].name)) // ! ah, al..
3ebea2cf 1196 {
5e49b270 1197 op->flags |= OPF_RMD | OPF_DONE;
092f64e1 1198 op->regmask_src = op->regmask_dst = 0;
3ebea2cf 1199 }
1200 break;
1201
de50b98b 1202 case OP_LEA:
1203 if (op->operand[0].type == OPT_REG
1204 && op->operand[1].type == OPT_REGMEM)
1205 {
1206 char buf[16];
1207 snprintf(buf, sizeof(buf), "%s+0", op->operand[0].name);
1208 if (IS(buf, op->operand[1].name))
5e49b270 1209 op->flags |= OPF_RMD | OPF_DONE;
de50b98b 1210 }
1211 break;
1212
89ff3147 1213 case OP_CALL:
1214 // trashed regs must be explicitly detected later
1215 op->regmask_dst = 0;
1216 break;
1217
92d715b6 1218 case OP_LEAVE:
1219 op->regmask_dst = (1 << xBP) | (1 << xSP);
1220 op->regmask_src = 1 << xBP;
1221 break;
1222
5101a5f9 1223 default:
1224 break;
1225 }
2b70f6d3 1226
1227 if (op->operand[0].type == OPT_REG
1228 && op->operand[0].lmod == OPLM_DWORD
1229 && op->operand[1].type == OPT_CONST)
1230 {
1231 if ((op->op == OP_AND && op->operand[1].val == 0)
1232 || (op->op == OP_OR && op->operand[1].val == ~0))
1233 {
1234 op->regmask_src = 0;
1235 }
1236 }
c36e914d 1237}
1238
092f64e1 1239static const char *op_name(struct parsed_op *po)
850c9265 1240{
092f64e1 1241 static char buf[16];
1242 char *p;
850c9265 1243 int i;
1244
092f64e1 1245 if (po->op == OP_JCC || po->op == OP_SCC) {
1246 p = buf;
1247 *p++ = (po->op == OP_JCC) ? 'j' : 's';
1248 if (po->pfo_inv)
1249 *p++ = 'n';
1250 strcpy(p, parsed_flag_op_names[po->pfo]);
1251 return buf;
1252 }
1253
850c9265 1254 for (i = 0; i < ARRAY_SIZE(op_table); i++)
092f64e1 1255 if (op_table[i].op == po->op)
850c9265 1256 return op_table[i].name;
1257
1258 return "???";
1259}
1260
1261// debug
1262static const char *dump_op(struct parsed_op *po)
1263{
1264 static char out[128];
1265 char *p = out;
1266 int i;
1267
4c45fa73 1268 if (po == NULL)
1269 return "???";
1270
092f64e1 1271 snprintf(out, sizeof(out), "%s", op_name(po));
850c9265 1272 for (i = 0; i < po->operand_cnt; i++) {
1273 p += strlen(p);
1274 if (i > 0)
1275 *p++ = ',';
1276 snprintf(p, sizeof(out) - (p - out),
1277 po->operand[i].type == OPT_REGMEM ? " [%s]" : " %s",
1278 po->operand[i].name);
1279 }
1280
1281 return out;
1282}
1283
4c45fa73 1284static const char *lmod_type_u(struct parsed_op *po,
1285 enum opr_lenmod lmod)
1286{
1287 switch (lmod) {
90307a99 1288 case OPLM_QWORD:
1289 return "u64";
4c45fa73 1290 case OPLM_DWORD:
1291 return "u32";
1292 case OPLM_WORD:
1293 return "u16";
1294 case OPLM_BYTE:
1295 return "u8";
1296 default:
1297 ferr(po, "invalid lmod: %d\n", lmod);
1298 return "(_invalid_)";
1299 }
1300}
1301
d4e3b5db 1302static const char *lmod_cast_u(struct parsed_op *po,
1303 enum opr_lenmod lmod)
1304{
1305 switch (lmod) {
90307a99 1306 case OPLM_QWORD:
1307 return "";
d4e3b5db 1308 case OPLM_DWORD:
1309 return "";
1310 case OPLM_WORD:
1311 return "(u16)";
1312 case OPLM_BYTE:
1313 return "(u8)";
1314 default:
1315 ferr(po, "invalid lmod: %d\n", lmod);
1316 return "(_invalid_)";
1317 }
1318}
1319
1320static const char *lmod_cast_u_ptr(struct parsed_op *po,
1321 enum opr_lenmod lmod)
1322{
1323 switch (lmod) {
90307a99 1324 case OPLM_QWORD:
1325 return "*(u64 *)";
d4e3b5db 1326 case OPLM_DWORD:
1327 return "*(u32 *)";
1328 case OPLM_WORD:
1329 return "*(u16 *)";
1330 case OPLM_BYTE:
1331 return "*(u8 *)";
1332 default:
1333 ferr(po, "invalid lmod: %d\n", lmod);
1334 return "(_invalid_)";
1335 }
1336}
1337
1338static const char *lmod_cast_s(struct parsed_op *po,
1339 enum opr_lenmod lmod)
1340{
1341 switch (lmod) {
90307a99 1342 case OPLM_QWORD:
1343 return "(s64)";
d4e3b5db 1344 case OPLM_DWORD:
1345 return "(s32)";
1346 case OPLM_WORD:
1347 return "(s16)";
1348 case OPLM_BYTE:
1349 return "(s8)";
1350 default:
1351 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1352 return "(_invalid_)";
1353 }
1354}
1355
1356static const char *lmod_cast(struct parsed_op *po,
1357 enum opr_lenmod lmod, int is_signed)
1358{
1359 return is_signed ?
1360 lmod_cast_s(po, lmod) :
1361 lmod_cast_u(po, lmod);
1362}
1363
1364static int lmod_bytes(struct parsed_op *po, enum opr_lenmod lmod)
1365{
1366 switch (lmod) {
90307a99 1367 case OPLM_QWORD:
1368 return 8;
d4e3b5db 1369 case OPLM_DWORD:
1370 return 4;
1371 case OPLM_WORD:
1372 return 2;
1373 case OPLM_BYTE:
1374 return 1;
1375 default:
1376 ferr(po, "%s: invalid lmod: %d\n", __func__, lmod);
1377 return 0;
1378 }
1379}
1380
91977a1c 1381static const char *opr_name(struct parsed_op *po, int opr_num)
c36e914d 1382{
91977a1c 1383 if (opr_num >= po->operand_cnt)
1384 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1385 return po->operand[opr_num].name;
c36e914d 1386}
1387
91977a1c 1388static unsigned int opr_const(struct parsed_op *po, int opr_num)
c36e914d 1389{
91977a1c 1390 if (opr_num >= po->operand_cnt)
1391 ferr(po, "opr OOR: %d/%d\n", opr_num, po->operand_cnt);
1392 if (po->operand[opr_num].type != OPT_CONST)
1393 ferr(po, "opr %d: const expected\n", opr_num);
1394 return po->operand[opr_num].val;
1395}
c36e914d 1396
91977a1c 1397static const char *opr_reg_p(struct parsed_op *po, struct parsed_opr *popr)
1398{
90307a99 1399 if ((unsigned int)popr->reg >= ARRAY_SIZE(regs_r32))
91977a1c 1400 ferr(po, "invalid reg: %d\n", popr->reg);
1401 return regs_r32[popr->reg];
1402}
c36e914d 1403
a2c1d768 1404// cast1 is the "final" cast
1405static const char *simplify_cast(const char *cast1, const char *cast2)
1406{
1407 static char buf[256];
1408
1409 if (cast1[0] == 0)
1410 return cast2;
1411 if (cast2[0] == 0)
1412 return cast1;
1413 if (IS(cast1, cast2))
1414 return cast1;
1415 if (IS(cast1, "(s8)") && IS(cast2, "(u8)"))
1416 return cast1;
1417 if (IS(cast1, "(s16)") && IS(cast2, "(u16)"))
1418 return cast1;
1419 if (IS(cast1, "(u8)") && IS_START(cast2, "*(u8 *)"))
1420 return cast2;
1421 if (IS(cast1, "(u16)") && IS_START(cast2, "*(u16 *)"))
1422 return cast2;
1cd4a663 1423 if (strchr(cast1, '*') && IS_START(cast2, "(u32)"))
1424 return cast1;
a2c1d768 1425
1426 snprintf(buf, sizeof(buf), "%s%s", cast1, cast2);
1427 return buf;
1428}
1429
1430static const char *simplify_cast_num(const char *cast, unsigned int val)
1431{
1432 if (IS(cast, "(u8)") && val < 0x100)
1433 return "";
1434 if (IS(cast, "(s8)") && val < 0x80)
1435 return "";
1436 if (IS(cast, "(u16)") && val < 0x10000)
1437 return "";
1438 if (IS(cast, "(s16)") && val < 0x8000)
1439 return "";
1440 if (IS(cast, "(s32)") && val < 0x80000000)
1441 return "";
1442
1443 return cast;
1444}
1445
39b168b8 1446static struct parsed_equ *equ_find(struct parsed_op *po, const char *name,
1447 int *extra_offs)
91977a1c 1448{
39b168b8 1449 const char *p;
1450 char *endp;
1451 int namelen;
850c9265 1452 int i;
1453
39b168b8 1454 *extra_offs = 0;
1455 namelen = strlen(name);
1456
1457 p = strchr(name, '+');
1458 if (p != NULL) {
1459 namelen = p - name;
1460 if (namelen <= 0)
1461 ferr(po, "equ parse failed for '%s'\n", name);
1462
1463 if (IS_START(p, "0x"))
1464 p += 2;
1465 *extra_offs = strtol(p, &endp, 16);
1466 if (*endp != 0)
1467 ferr(po, "equ parse failed for '%s'\n", name);
1468 }
1469
850c9265 1470 for (i = 0; i < g_eqcnt; i++)
39b168b8 1471 if (strncmp(g_eqs[i].name, name, namelen) == 0
1472 && g_eqs[i].name[namelen] == 0)
850c9265 1473 break;
87bf6cec 1474 if (i >= g_eqcnt) {
1475 if (po != NULL)
1476 ferr(po, "unresolved equ name: '%s'\n", name);
1477 return NULL;
1478 }
850c9265 1479
1480 return &g_eqs[i];
1481}
1482
1cd4a663 1483static int is_stack_access(struct parsed_op *po,
1484 const struct parsed_opr *popr)
850c9265 1485{
09bc6fd5 1486 return (parse_stack_el(popr->name, NULL, 0)
1cd4a663 1487 || (g_bp_frame && !(po->flags & OPF_EBP_S)
1488 && IS_START(popr->name, "ebp")));
1489}
1490
1491static void parse_stack_access(struct parsed_op *po,
1492 const char *name, char *ofs_reg, int *offset_out,
037f4971 1493 int *stack_ra_out, const char **bp_arg_out, int is_lea)
1cd4a663 1494{
1495 const char *bp_arg = "";
1496 const char *p = NULL;
91977a1c 1497 struct parsed_equ *eq;
4f12f671 1498 char *endp = NULL;
d4e3b5db 1499 int stack_ra = 0;
39b168b8 1500 int offset = 0;
91977a1c 1501
1cd4a663 1502 ofs_reg[0] = 0;
a3684be1 1503
1504 if (IS_START(name, "ebp-")
1505 || (IS_START(name, "ebp+") && '0' <= name[4] && name[4] <= '9'))
1506 {
1507 p = name + 4;
1508 if (IS_START(p, "0x"))
1509 p += 2;
1510 offset = strtoul(p, &endp, 16);
1511 if (name[3] == '-')
1512 offset = -offset;
1513 if (*endp != 0)
1514 ferr(po, "ebp- parse of '%s' failed\n", name);
1515 }
1516 else {
09bc6fd5 1517 bp_arg = parse_stack_el(name, ofs_reg, 0);
4f12f671 1518 snprintf(g_comment, sizeof(g_comment), "%s", bp_arg);
1519 eq = equ_find(po, bp_arg, &offset);
1520 if (eq == NULL)
1521 ferr(po, "detected but missing eq\n");
1522 offset += eq->offset;
1523 }
39b168b8 1524
d4e3b5db 1525 if (!strncmp(name, "ebp", 3))
1526 stack_ra = 4;
1527
037f4971 1528 // yes it sometimes LEAs ra for compares..
1529 if (!is_lea && ofs_reg[0] == 0
1530 && stack_ra <= offset && offset < stack_ra + 4)
1531 {
39b168b8 1532 ferr(po, "reference to ra? %d %d\n", offset, stack_ra);
037f4971 1533 }
d4e3b5db 1534
1cd4a663 1535 *offset_out = offset;
1536 *stack_ra_out = stack_ra;
1537 if (bp_arg_out)
1538 *bp_arg_out = bp_arg;
1539}
1540
5f70a34f 1541static int stack_frame_access(struct parsed_op *po,
1cd4a663 1542 struct parsed_opr *popr, char *buf, size_t buf_size,
1543 const char *name, const char *cast, int is_src, int is_lea)
1544{
1545 enum opr_lenmod tmp_lmod = OPLM_UNSPEC;
1546 const char *prefix = "";
1547 const char *bp_arg = NULL;
1548 char ofs_reg[16] = { 0, };
1549 int i, arg_i, arg_s;
1550 int unaligned = 0;
1551 int stack_ra = 0;
1552 int offset = 0;
5f70a34f 1553 int retval = -1;
1cd4a663 1554 int sf_ofs;
1555 int lim;
1556
1557 if (po->flags & OPF_EBP_S)
1558 ferr(po, "stack_frame_access while ebp is scratch\n");
1559
037f4971 1560 parse_stack_access(po, name, ofs_reg, &offset,
1561 &stack_ra, &bp_arg, is_lea);
1cd4a663 1562
4f12f671 1563 if (offset > stack_ra)
1564 {
39b168b8 1565 arg_i = (offset - stack_ra - 4) / 4;
bd96f656 1566 if (arg_i < 0 || arg_i >= g_func_pp->argc_stack)
4f12f671 1567 {
bd96f656 1568 if (g_func_pp->is_vararg
1569 && arg_i == g_func_pp->argc_stack && is_lea)
1570 {
4f12f671 1571 // should be va_list
1572 if (cast[0] == 0)
1573 cast = "(u32)";
1574 snprintf(buf, buf_size, "%sap", cast);
5f70a34f 1575 return -1;
4f12f671 1576 }
1577 ferr(po, "offset %d (%s,%d) doesn't map to any arg\n",
1578 offset, bp_arg, arg_i);
1579 }
4c45fa73 1580 if (ofs_reg[0] != 0)
7ba45c34 1581 ferr(po, "offset reg on arg access?\n");
91977a1c 1582
bd96f656 1583 for (i = arg_s = 0; i < g_func_pp->argc; i++) {
1584 if (g_func_pp->arg[i].reg != NULL)
91977a1c 1585 continue;
1586 if (arg_s == arg_i)
1587 break;
1588 arg_s++;
1589 }
bd96f656 1590 if (i == g_func_pp->argc)
91977a1c 1591 ferr(po, "arg %d not in prototype?\n", arg_i);
850c9265 1592
bd96f656 1593 popr->is_ptr = g_func_pp->arg[i].type.is_ptr;
5f70a34f 1594 retval = i;
de50b98b 1595
1596 switch (popr->lmod)
7ba45c34 1597 {
1598 case OPLM_BYTE:
4f12f671 1599 if (is_lea)
1600 ferr(po, "lea/byte to arg?\n");
7ba45c34 1601 if (is_src && (offset & 3) == 0)
a2c1d768 1602 snprintf(buf, buf_size, "%sa%d",
1603 simplify_cast(cast, "(u8)"), i + 1);
7ba45c34 1604 else
a2c1d768 1605 snprintf(buf, buf_size, "%sBYTE%d(a%d)",
1606 cast, offset & 3, i + 1);
7ba45c34 1607 break;
1608
1609 case OPLM_WORD:
4f12f671 1610 if (is_lea)
1611 ferr(po, "lea/word to arg?\n");
a3684be1 1612 if (offset & 1) {
1613 unaligned = 1;
1614 if (!is_src) {
1615 if (offset & 2)
1616 ferr(po, "problematic arg store\n");
a2c1d768 1617 snprintf(buf, buf_size, "%s((char *)&a%d + 1)",
1618 simplify_cast(cast, "*(u16 *)"), i + 1);
a3684be1 1619 }
1620 else
1621 ferr(po, "unaligned arg word load\n");
1622 }
1623 else if (is_src && (offset & 2) == 0)
a2c1d768 1624 snprintf(buf, buf_size, "%sa%d",
1625 simplify_cast(cast, "(u16)"), i + 1);
7ba45c34 1626 else
a2c1d768 1627 snprintf(buf, buf_size, "%s%sWORD(a%d)",
1628 cast, (offset & 2) ? "HI" : "LO", i + 1);
7ba45c34 1629 break;
1630
1631 case OPLM_DWORD:
3ebea2cf 1632 if (cast[0])
1633 prefix = cast;
1634 else if (is_src)
1635 prefix = "(u32)";
a3684be1 1636
de50b98b 1637 if (offset & 3) {
a3684be1 1638 unaligned = 1;
2b43685d 1639 if (is_lea)
1640 snprintf(buf, buf_size, "(u32)&a%d + %d",
1641 i + 1, offset & 3);
a3684be1 1642 else if (!is_src)
1643 ferr(po, "unaligned arg store\n");
1644 else {
1645 // mov edx, [ebp+arg_4+2]; movsx ecx, dx
2b43685d 1646 snprintf(buf, buf_size, "%s(a%d >> %d)",
1647 prefix, i + 1, (offset & 3) * 8);
a3684be1 1648 }
de50b98b 1649 }
1650 else {
1651 snprintf(buf, buf_size, "%s%sa%d",
1652 prefix, is_lea ? "&" : "", i + 1);
1653 }
7ba45c34 1654 break;
1655
1656 default:
de50b98b 1657 ferr(po, "bp_arg bad lmod: %d\n", popr->lmod);
7ba45c34 1658 }
1659
a3684be1 1660 if (unaligned)
1661 snprintf(g_comment, sizeof(g_comment), "%s unaligned", bp_arg);
1662
7ba45c34 1663 // common problem
bd96f656 1664 guess_lmod_from_c_type(&tmp_lmod, &g_func_pp->arg[i].type);
a2c1d768 1665 if (tmp_lmod != OPLM_DWORD
de041e5b 1666 && (unaligned || (!is_src && lmod_bytes(po, tmp_lmod)
1667 < lmod_bytes(po, popr->lmod) + (offset & 3))))
a2c1d768 1668 {
1669 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1670 i + 1, offset, g_func_pp->arg[i].type.name);
1671 }
4741fdfe 1672 // can't check this because msvc likes to reuse
1673 // arg space for scratch..
1674 //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1675 // ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
91977a1c 1676 }
4f12f671 1677 else
1678 {
1bafb621 1679 if (g_stack_fsz == 0)
1680 ferr(po, "stack var access without stackframe\n");
a2c1d768 1681 g_stack_frame_used = 1;
850c9265 1682
39b168b8 1683 sf_ofs = g_stack_fsz + offset;
de50b98b 1684 lim = (ofs_reg[0] != 0) ? -4 : 0;
1685 if (offset > 0 || sf_ofs < lim)
39b168b8 1686 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
850c9265 1687
1688 if (is_lea)
33c35af6 1689 prefix = "(u32)&";
3ebea2cf 1690 else
1691 prefix = cast;
850c9265 1692
de50b98b 1693 switch (popr->lmod)
850c9265 1694 {
1695 case OPLM_BYTE:
7ba45c34 1696 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1697 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
850c9265 1698 break;
7ba45c34 1699
850c9265 1700 case OPLM_WORD:
7ba45c34 1701 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1702 // known unaligned or possibly unaligned
1703 strcat(g_comment, " unaligned");
1704 if (prefix[0] == 0)
1705 prefix = "*(u16 *)&";
1706 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1707 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1708 break;
1709 }
1710 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
850c9265 1711 break;
7ba45c34 1712
850c9265 1713 case OPLM_DWORD:
7ba45c34 1714 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1715 // known unaligned or possibly unaligned
1716 strcat(g_comment, " unaligned");
1717 if (prefix[0] == 0)
1718 prefix = "*(u32 *)&";
1719 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1720 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1721 break;
1722 }
1723 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
850c9265 1724 break;
7ba45c34 1725
850c9265 1726 default:
de50b98b 1727 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
850c9265 1728 }
91977a1c 1729 }
5f70a34f 1730
1731 return retval;
91977a1c 1732}
c36e914d 1733
89ff3147 1734static void check_func_pp(struct parsed_op *po,
1735 const struct parsed_proto *pp, const char *pfx)
1736{
179b79a9 1737 enum opr_lenmod tmp_lmod;
b74c31e3 1738 char buf[256];
179b79a9 1739 int ret, i;
b74c31e3 1740
89ff3147 1741 if (pp->argc_reg != 0) {
b74c31e3 1742 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1743 pp_print(buf, sizeof(buf), pp);
1744 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1745 }
89ff3147 1746 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1747 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1748 pfx, pp->argc_reg, pp->argc_stack);
1749 }
179b79a9 1750
1751 // fptrs must use 32bit args, callsite might have no information and
1752 // lack a cast to smaller types, which results in incorrectly masked
1753 // args passed (callee may assume masked args, it does on ARM)
61e29183 1754 if (!pp->is_osinc) {
179b79a9 1755 for (i = 0; i < pp->argc; i++) {
1756 ret = guess_lmod_from_c_type(&tmp_lmod, &pp->arg[i].type);
1757 if (ret && tmp_lmod != OPLM_DWORD)
1758 ferr(po, "reference to %s with arg%d '%s'\n", pp->name,
1759 i + 1, pp->arg[i].type.name);
1760 }
1761 }
89ff3147 1762}
1763
7aca4698 1764static const char *check_label_read_ref(struct parsed_op *po,
1765 const char *name)
3ebea2cf 1766{
840257f6 1767 const struct parsed_proto *pp;
1768
36595fd2 1769 pp = proto_parse(g_fhdr, name, 0);
840257f6 1770 if (pp == NULL)
1771 ferr(po, "proto_parse failed for ref '%s'\n", name);
1772
89ff3147 1773 if (pp->is_func)
1774 check_func_pp(po, pp, "ref");
7aca4698 1775
1776 return pp->name;
3ebea2cf 1777}
1778
91977a1c 1779static char *out_src_opr(char *buf, size_t buf_size,
591721d7 1780 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
3ebea2cf 1781 int is_lea)
91977a1c 1782{
850c9265 1783 char tmp1[256], tmp2[256];
1784 char expr[256];
7aca4698 1785 const char *name;
a2c1d768 1786 char *p;
850c9265 1787 int ret;
1788
3ebea2cf 1789 if (cast == NULL)
1790 cast = "";
1791
91977a1c 1792 switch (popr->type) {
1793 case OPT_REG:
850c9265 1794 if (is_lea)
1795 ferr(po, "lea from reg?\n");
1796
91977a1c 1797 switch (popr->lmod) {
90307a99 1798 case OPLM_QWORD:
1799 snprintf(buf, buf_size, "%s%s.q", cast, opr_reg_p(po, popr));
1800 break;
91977a1c 1801 case OPLM_DWORD:
3ebea2cf 1802 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
91977a1c 1803 break;
850c9265 1804 case OPLM_WORD:
a2c1d768 1805 snprintf(buf, buf_size, "%s%s",
1806 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
850c9265 1807 break;
1808 case OPLM_BYTE:
5101a5f9 1809 if (popr->name[1] == 'h') // XXX..
a2c1d768 1810 snprintf(buf, buf_size, "%s(%s >> 8)",
1811 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
5101a5f9 1812 else
a2c1d768 1813 snprintf(buf, buf_size, "%s%s",
1814 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
850c9265 1815 break;
91977a1c 1816 default:
1817 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1818 }
1819 break;
850c9265 1820
91977a1c 1821 case OPT_REGMEM:
1cd4a663 1822 if (is_stack_access(po, popr)) {
de50b98b 1823 stack_frame_access(po, popr, buf, buf_size,
3ebea2cf 1824 popr->name, cast, 1, is_lea);
91977a1c 1825 break;
1826 }
850c9265 1827
1828 strcpy(expr, popr->name);
1829 if (strchr(expr, '[')) {
1830 // special case: '[' can only be left for label[reg] form
1831 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1832 if (ret != 2)
1833 ferr(po, "parse failure for '%s'\n", expr);
a2c1d768 1834 if (tmp1[0] == '(') {
1835 // (off_4FFF50+3)[eax]
1836 p = strchr(tmp1 + 1, ')');
1837 if (p == NULL || p[1] != 0)
1838 ferr(po, "parse failure (2) for '%s'\n", expr);
1839 *p = 0;
1840 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1841 }
33c35af6 1842 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
850c9265 1843 }
1844
1845 // XXX: do we need more parsing?
1846 if (is_lea) {
1847 snprintf(buf, buf_size, "%s", expr);
1848 break;
1849 }
1850
a2c1d768 1851 snprintf(buf, buf_size, "%s(%s)",
1852 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
91977a1c 1853 break;
850c9265 1854
91977a1c 1855 case OPT_LABEL:
7aca4698 1856 name = check_label_read_ref(po, popr->name);
3ebea2cf 1857 if (cast[0] == 0 && popr->is_ptr)
1858 cast = "(u32)";
2b43685d 1859
850c9265 1860 if (is_lea)
7aca4698 1861 snprintf(buf, buf_size, "(u32)&%s", name);
2b43685d 1862 else if (popr->size_lt)
1863 snprintf(buf, buf_size, "%s%s%s%s", cast,
1864 lmod_cast_u_ptr(po, popr->lmod),
7aca4698 1865 popr->is_array ? "" : "&", name);
850c9265 1866 else
7aca4698 1867 snprintf(buf, buf_size, "%s%s%s", cast, name,
7ba45c34 1868 popr->is_array ? "[0]" : "");
850c9265 1869 break;
1870
1871 case OPT_OFFSET:
7aca4698 1872 name = check_label_read_ref(po, popr->name);
3ebea2cf 1873 if (cast[0] == 0)
1874 cast = "(u32)";
850c9265 1875 if (is_lea)
1876 ferr(po, "lea an offset?\n");
7aca4698 1877 snprintf(buf, buf_size, "%s&%s", cast, name);
91977a1c 1878 break;
850c9265 1879
91977a1c 1880 case OPT_CONST:
850c9265 1881 if (is_lea)
1882 ferr(po, "lea from const?\n");
1883
a2c1d768 1884 printf_number(tmp1, sizeof(tmp1), popr->val);
ddaf8bd7 1885 if (popr->val == 0 && strchr(cast, '*'))
1886 snprintf(buf, buf_size, "NULL");
1887 else
1888 snprintf(buf, buf_size, "%s%s",
1889 simplify_cast_num(cast, popr->val), tmp1);
91977a1c 1890 break;
850c9265 1891
91977a1c 1892 default:
1893 ferr(po, "invalid src type: %d\n", popr->type);
1894 }
1895
1896 return buf;
1897}
c36e914d 1898
de50b98b 1899// note: may set is_ptr (we find that out late for ebp frame..)
91977a1c 1900static char *out_dst_opr(char *buf, size_t buf_size,
1901 struct parsed_op *po, struct parsed_opr *popr)
1902{
1903 switch (popr->type) {
1904 case OPT_REG:
1905 switch (popr->lmod) {
90307a99 1906 case OPLM_QWORD:
1907 snprintf(buf, buf_size, "%s.q", opr_reg_p(po, popr));
1908 break;
91977a1c 1909 case OPLM_DWORD:
1910 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1911 break;
850c9265 1912 case OPLM_WORD:
1913 // ugh..
1914 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1915 break;
1916 case OPLM_BYTE:
1917 // ugh..
5101a5f9 1918 if (popr->name[1] == 'h') // XXX..
1919 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1920 else
1921 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
850c9265 1922 break;
91977a1c 1923 default:
1924 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1925 }
1926 break;
850c9265 1927
1928 case OPT_REGMEM:
1cd4a663 1929 if (is_stack_access(po, popr)) {
de50b98b 1930 stack_frame_access(po, popr, buf, buf_size,
3ebea2cf 1931 popr->name, "", 0, 0);
850c9265 1932 break;
1933 }
1934
3ebea2cf 1935 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
850c9265 1936
bfa4a6ee 1937 case OPT_LABEL:
2b43685d 1938 if (popr->size_mismatch)
1939 snprintf(buf, buf_size, "%s%s%s",
1940 lmod_cast_u_ptr(po, popr->lmod),
1941 popr->is_array ? "" : "&", popr->name);
1942 else
1943 snprintf(buf, buf_size, "%s%s", popr->name,
1944 popr->is_array ? "[0]" : "");
bfa4a6ee 1945 break;
1946
91977a1c 1947 default:
1948 ferr(po, "invalid dst type: %d\n", popr->type);
1949 }
1950
1951 return buf;
1952}
c36e914d 1953
3ebea2cf 1954static char *out_src_opr_u32(char *buf, size_t buf_size,
1955 struct parsed_op *po, struct parsed_opr *popr)
1956{
1957 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1958}
1959
91977a1c 1960static void out_test_for_cc(char *buf, size_t buf_size,
940e8e66 1961 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
69a3cdfc 1962 enum opr_lenmod lmod, const char *expr)
91977a1c 1963{
69a3cdfc 1964 const char *cast, *scast;
91977a1c 1965
69a3cdfc 1966 cast = lmod_cast_u(po, lmod);
1967 scast = lmod_cast_s(po, lmod);
1968
1969 switch (pfo) {
1970 case PFO_Z:
87bf6cec 1971 case PFO_BE: // CF=1||ZF=1; CF=0
850c9265 1972 snprintf(buf, buf_size, "(%s%s %s 0)",
940e8e66 1973 cast, expr, is_inv ? "!=" : "==");
91977a1c 1974 break;
850c9265 1975
5101a5f9 1976 case PFO_S:
1977 case PFO_L: // SF!=OF; OF=0
1978 snprintf(buf, buf_size, "(%s%s %s 0)",
940e8e66 1979 scast, expr, is_inv ? ">=" : "<");
5101a5f9 1980 break;
1981
87bf6cec 1982 case PFO_LE: // ZF=1||SF!=OF; OF=0
69a3cdfc 1983 snprintf(buf, buf_size, "(%s%s %s 0)",
940e8e66 1984 scast, expr, is_inv ? ">" : "<=");
850c9265 1985 break;
1986
91977a1c 1987 default:
69a3cdfc 1988 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
91977a1c 1989 }
1990}
c36e914d 1991
850c9265 1992static void out_cmp_for_cc(char *buf, size_t buf_size,
a2c1d768 1993 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
850c9265 1994{
a2c1d768 1995 const char *cast, *scast, *cast_use;
1996 char buf1[256], buf2[256];
1997 enum opr_lenmod lmod;
1998
90307a99 1999 if (po->op != OP_DEC && po->operand[0].lmod != po->operand[1].lmod)
a2c1d768 2000 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
2001 po->operand[0].lmod, po->operand[1].lmod);
2002 lmod = po->operand[0].lmod;
850c9265 2003
69a3cdfc 2004 cast = lmod_cast_u(po, lmod);
2005 scast = lmod_cast_s(po, lmod);
850c9265 2006
a2c1d768 2007 switch (pfo) {
2008 case PFO_C:
2009 case PFO_Z:
2010 case PFO_BE: // !a
2011 cast_use = cast;
2012 break;
2013
2014 case PFO_S:
2015 case PFO_L: // !ge
2016 case PFO_LE:
2017 cast_use = scast;
2018 break;
2019
2020 default:
2021 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
2022 }
2023
2024 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
90307a99 2025 if (po->op == OP_DEC)
2026 snprintf(buf2, sizeof(buf2), "1");
2027 else
2028 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
a2c1d768 2029
69a3cdfc 2030 switch (pfo) {
5101a5f9 2031 case PFO_C:
2032 // note: must be unsigned compare
a2c1d768 2033 snprintf(buf, buf_size, "(%s %s %s)",
2034 buf1, is_inv ? ">=" : "<", buf2);
5101a5f9 2035 break;
2036
69a3cdfc 2037 case PFO_Z:
a2c1d768 2038 snprintf(buf, buf_size, "(%s %s %s)",
2039 buf1, is_inv ? "!=" : "==", buf2);
850c9265 2040 break;
2041
5101a5f9 2042 case PFO_BE: // !a
850c9265 2043 // note: must be unsigned compare
a2c1d768 2044 snprintf(buf, buf_size, "(%s %s %s)",
2045 buf1, is_inv ? ">" : "<=", buf2);
2046
2047 // annoying case
2048 if (is_inv && lmod == OPLM_BYTE
2049 && po->operand[1].type == OPT_CONST
2050 && po->operand[1].val == 0xff)
2051 {
2052 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
2053 snprintf(buf, buf_size, "(0)");
2054 }
5101a5f9 2055 break;
2056
2057 // note: must be signed compare
2058 case PFO_S:
2059 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
a2c1d768 2060 scast, buf1, buf2, is_inv ? ">=" : "<");
850c9265 2061 break;
2062
5101a5f9 2063 case PFO_L: // !ge
a2c1d768 2064 snprintf(buf, buf_size, "(%s %s %s)",
2065 buf1, is_inv ? ">=" : "<", buf2);
850c9265 2066 break;
2067
90307a99 2068 case PFO_LE: // !g
a2c1d768 2069 snprintf(buf, buf_size, "(%s %s %s)",
2070 buf1, is_inv ? ">" : "<=", buf2);
5101a5f9 2071 break;
2072
850c9265 2073 default:
a2c1d768 2074 break;
850c9265 2075 }
2076}
2077
69a3cdfc 2078static void out_cmp_test(char *buf, size_t buf_size,
940e8e66 2079 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
69a3cdfc 2080{
2081 char buf1[256], buf2[256], buf3[256];
2082
2083 if (po->op == OP_TEST) {
2084 if (IS(opr_name(po, 0), opr_name(po, 1))) {
3ebea2cf 2085 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
69a3cdfc 2086 }
2087 else {
3ebea2cf 2088 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
2089 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
69a3cdfc 2090 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
2091 }
940e8e66 2092 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
69a3cdfc 2093 po->operand[0].lmod, buf3);
2094 }
2095 else if (po->op == OP_CMP) {
a2c1d768 2096 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
69a3cdfc 2097 }
2098 else
2099 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
2100}
2101
850c9265 2102static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
91977a1c 2103 struct parsed_opr *popr2)
2104{
2105 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
2106 ferr(po, "missing lmod for both operands\n");
2107
2108 if (popr1->lmod == OPLM_UNSPEC)
2109 popr1->lmod = popr2->lmod;
2110 else if (popr2->lmod == OPLM_UNSPEC)
2111 popr2->lmod = popr1->lmod;
a3684be1 2112 else if (popr1->lmod != popr2->lmod) {
2113 if (popr1->type_from_var) {
2114 popr1->size_mismatch = 1;
2115 if (popr1->lmod < popr2->lmod)
2116 popr1->size_lt = 1;
2117 popr1->lmod = popr2->lmod;
2118 }
2119 else if (popr2->type_from_var) {
2120 popr2->size_mismatch = 1;
2121 if (popr2->lmod < popr1->lmod)
2122 popr2->size_lt = 1;
2123 popr2->lmod = popr1->lmod;
2124 }
2125 else
2126 ferr(po, "conflicting lmods: %d vs %d\n",
2127 popr1->lmod, popr2->lmod);
2128 }
91977a1c 2129}
c36e914d 2130
850c9265 2131static const char *op_to_c(struct parsed_op *po)
2132{
2133 switch (po->op)
2134 {
2135 case OP_ADD:
5101a5f9 2136 case OP_ADC:
850c9265 2137 return "+";
2138 case OP_SUB:
5101a5f9 2139 case OP_SBB:
850c9265 2140 return "-";
2141 case OP_AND:
2142 return "&";
2143 case OP_OR:
2144 return "|";
2145 case OP_XOR:
2146 return "^";
2147 case OP_SHL:
2148 return "<<";
2149 case OP_SHR:
2150 return ">>";
2151 case OP_MUL:
2152 case OP_IMUL:
2153 return "*";
2154 default:
2155 ferr(po, "op_to_c was supplied with %d\n", po->op);
2156 }
2157}
2158
7ae48d73 2159static void op_set_clear_flag(struct parsed_op *po,
2160 enum op_flags flag_set, enum op_flags flag_clear)
d4e3b5db 2161{
7ae48d73 2162 po->flags |= flag_set;
2163 po->flags &= ~flag_clear;
d4e3b5db 2164}
2165
de50b98b 2166// last op in stream - unconditional branch or ret
2167#define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
092f64e1 2168 || ((ops[_i].flags & (OPF_JMP|OPF_CJMP|OPF_RMD)) == OPF_JMP \
037f4971 2169 && ops[_i].op != OP_CALL))
de50b98b 2170
db63af51 2171#define check_i(po, i) \
2172 if ((i) < 0) \
2173 ferr(po, "bad " #i ": %d\n", i)
2174
87bf6cec 2175static int scan_for_pop(int i, int opcnt, const char *reg,
d4e3b5db 2176 int magic, int depth, int *maxdepth, int do_flags)
850c9265 2177{
89ff3147 2178 const struct parsed_proto *pp;
87bf6cec 2179 struct parsed_op *po;
2180 int ret = 0;
4c45fa73 2181 int j;
87bf6cec 2182
850c9265 2183 for (; i < opcnt; i++) {
87bf6cec 2184 po = &ops[i];
2185 if (po->cc_scratch == magic)
2186 break; // already checked
2187 po->cc_scratch = magic;
2188
89ff3147 2189 if (po->flags & OPF_TAIL) {
2190 if (po->op == OP_CALL) {
92d715b6 2191 pp = proto_parse(g_fhdr, po->operand[0].name, g_quiet_pp);
89ff3147 2192 if (pp != NULL && pp->is_noreturn)
2193 // no stack cleanup for noreturn
2194 return ret;
2195 }
87bf6cec 2196 return -1; // deadend
89ff3147 2197 }
87bf6cec 2198
5e49b270 2199 if ((po->flags & (OPF_RMD|OPF_DONE))
5f70a34f 2200 || (po->op == OP_PUSH && po->p_argnum != 0)) // arg push
850c9265 2201 continue;
2202
87bf6cec 2203 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
4c45fa73 2204 if (po->btj != NULL) {
2205 // jumptable
da87ae38 2206 for (j = 0; j < po->btj->count; j++) {
db63af51 2207 check_i(po, po->btj->d[j].bt_i);
4c45fa73 2208 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
2209 depth, maxdepth, do_flags);
2210 if (ret < 0)
2211 return ret; // dead end
2212 }
da87ae38 2213 return ret;
4c45fa73 2214 }
2215
db63af51 2216 check_i(po, po->bt_i);
5c024ef7 2217 if (po->flags & OPF_CJMP) {
d4e3b5db 2218 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
2219 depth, maxdepth, do_flags);
87bf6cec 2220 if (ret < 0)
2221 return ret; // dead end
2222 }
2223 else {
2224 i = po->bt_i - 1;
2225 }
2226 continue;
2227 }
2228
d4e3b5db 2229 if ((po->op == OP_POP || po->op == OP_PUSH)
2230 && po->operand[0].type == OPT_REG
87bf6cec 2231 && IS(po->operand[0].name, reg))
2232 {
9af2d373 2233 if (po->op == OP_PUSH && !(po->flags & OPF_FARGNR)) {
d4e3b5db 2234 depth++;
2235 if (depth > *maxdepth)
2236 *maxdepth = depth;
2237 if (do_flags)
7ae48d73 2238 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
d4e3b5db 2239 }
da87ae38 2240 else if (po->op == OP_POP) {
2241 if (depth == 0) {
2242 if (do_flags)
2243 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2244 return 1;
2245 }
2246 else {
2247 depth--;
2248 if (depth < 0) // should not happen
2249 ferr(po, "fail with depth\n");
2250 if (do_flags)
2251 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2252 }
d4e3b5db 2253 }
87bf6cec 2254 }
850c9265 2255 }
2256
87bf6cec 2257 return ret;
850c9265 2258}
2259
69a3cdfc 2260// scan for pop starting from 'ret' op (all paths)
d4e3b5db 2261static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2262 int flag_set)
850c9265 2263{
2264 int found = 0;
2265 int j;
2266
2267 for (; i < opcnt; i++) {
87bf6cec 2268 if (!(ops[i].flags & OPF_TAIL))
850c9265 2269 continue;
2270
2271 for (j = i - 1; j >= 0; j--) {
5e49b270 2272 if (ops[j].flags & (OPF_RMD|OPF_DONE))
69a3cdfc 2273 continue;
2274 if (ops[j].flags & OPF_JMP)
850c9265 2275 return -1;
2276
5e49b270 2277 if (ops[j].op == OP_POP && ops[j].datap == NULL
2278 && ops[j].operand[0].type == OPT_REG
850c9265 2279 && IS(ops[j].operand[0].name, reg))
2280 {
2281 found = 1;
d4e3b5db 2282 ops[j].flags |= flag_set;
850c9265 2283 break;
2284 }
2285
d7857c3a 2286 if (g_labels[j] != NULL)
850c9265 2287 return -1;
2288 }
2289 }
2290
2291 return found ? 0 : -1;
2292}
2293
25a330eb 2294static void scan_for_pop_const(int i, int opcnt, int *regmask_pp)
9af2d373 2295{
25a330eb 2296 struct parsed_op *po;
2297 int is_multipath = 0;
9af2d373 2298 int j;
2299
2300 for (j = i + 1; j < opcnt; j++) {
25a330eb 2301 po = &ops[j];
2302
2303 if (po->op == OP_JMP && po->btj == NULL) {
2304 ferr_assert(po, po->bt_i >= 0);
2305 j = po->bt_i - 1;
2306 continue;
2307 }
2308
2309 if ((po->flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
2310 || po->op == OP_PUSH)
9af2d373 2311 {
2312 break;
2313 }
2314
25a330eb 2315 if (g_labels[j] != NULL)
2316 is_multipath = 1;
2317
2318 if (po->op == OP_POP && !(po->flags & OPF_RMD))
9af2d373 2319 {
25a330eb 2320 is_multipath |= !!(po->flags & OPF_PPUSH);
2321 if (is_multipath) {
2322 ops[i].flags |= OPF_PPUSH | OPF_DONE;
2323 ops[i].datap = po;
2324 po->flags |= OPF_PPUSH | OPF_DONE;
2325 *regmask_pp |= 1 << po->operand[0].reg;
2326 }
2327 else {
2328 ops[i].flags |= OPF_RMD | OPF_DONE;
2329 po->flags |= OPF_DONE;
2330 po->datap = &ops[i];
2331 }
9af2d373 2332 break;
2333 }
2334 }
2335}
2336
591721d7 2337static void scan_propagate_df(int i, int opcnt)
2338{
2339 struct parsed_op *po = &ops[i];
2340 int j;
2341
2342 for (; i < opcnt; i++) {
2343 po = &ops[i];
2344 if (po->flags & OPF_DF)
2345 return; // already resolved
2346 po->flags |= OPF_DF;
2347
2348 if (po->op == OP_CALL)
2349 ferr(po, "call with DF set?\n");
2350
2351 if (po->flags & OPF_JMP) {
2352 if (po->btj != NULL) {
2353 // jumptable
db63af51 2354 for (j = 0; j < po->btj->count; j++) {
2355 check_i(po, po->btj->d[j].bt_i);
591721d7 2356 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
db63af51 2357 }
591721d7 2358 return;
2359 }
2360
db63af51 2361 check_i(po, po->bt_i);
5c024ef7 2362 if (po->flags & OPF_CJMP)
591721d7 2363 scan_propagate_df(po->bt_i, opcnt);
2364 else
2365 i = po->bt_i - 1;
2366 continue;
2367 }
2368
2369 if (po->flags & OPF_TAIL)
2370 break;
2371
2372 if (po->op == OP_CLD) {
5e49b270 2373 po->flags |= OPF_RMD | OPF_DONE;
591721d7 2374 return;
2375 }
2376 }
2377
2378 ferr(po, "missing DF clear?\n");
2379}
2380
db63af51 2381// is operand 'opr' referenced by parsed_op 'po'?
2382static int is_opr_referenced(const struct parsed_opr *opr,
2383 const struct parsed_op *po)
2384{
2385 int i, mask;
2386
2387 if (opr->type == OPT_REG) {
2388 mask = po->regmask_dst | po->regmask_src;
2389 if (po->op == OP_CALL)
2390 mask |= (1 << xAX) | (1 << xCX) | (1 << xDX);
2391 if ((1 << opr->reg) & mask)
2392 return 1;
2393 else
2394 return 0;
2395 }
2396
2397 for (i = 0; i < po->operand_cnt; i++)
2398 if (IS(po->operand[0].name, opr->name))
2399 return 1;
2400
2401 return 0;
2402}
2403
2404// is operand 'opr' read by parsed_op 'po'?
2405static int is_opr_read(const struct parsed_opr *opr,
2406 const struct parsed_op *po)
2407{
2408 int mask;
2409
2410 if (opr->type == OPT_REG) {
2411 mask = po->regmask_src;
2412 if (po->op == OP_CALL)
2413 // assume worst case
2414 mask |= (1 << xAX) | (1 << xCX) | (1 << xDX);
2415 if ((1 << opr->reg) & mask)
2416 return 1;
2417 else
2418 return 0;
2419 }
2420
2421 // yes I'm lazy
2422 return 0;
2423}
2424
1cd4a663 2425// is operand 'opr' modified by parsed_op 'po'?
5101a5f9 2426static int is_opr_modified(const struct parsed_opr *opr,
69a3cdfc 2427 const struct parsed_op *po)
2428{
89ff3147 2429 int mask;
2430
db63af51 2431 if (!(po->flags & OPF_DATA))
69a3cdfc 2432 return 0;
2433
89ff3147 2434 if (opr->type == OPT_REG) {
2435 if (po->op == OP_CALL) {
2436 mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2437 if ((1 << opr->reg) & mask)
2438 return 1;
2439 else
2440 return 0;
2441 }
2442
2443 if (po->operand[0].type == OPT_REG) {
2444 if (po->regmask_dst & (1 << opr->reg))
2445 return 1;
2446 else
2447 return 0;
2448 }
69a3cdfc 2449 }
2450
2451 return IS(po->operand[0].name, opr->name);
2452}
2453
5101a5f9 2454// is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2455static int is_any_opr_modified(const struct parsed_op *po_test,
89ff3147 2456 const struct parsed_op *po, int c_mode)
5101a5f9 2457{
89ff3147 2458 int mask;
5101a5f9 2459 int i;
2460
2461 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2462 return 0;
2463
de50b98b 2464 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2465 return 0;
2466
2467 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2468 return 1;
2469
2470 // in reality, it can wreck any register, but in decompiled C
2b43685d 2471 // version it can only overwrite eax or edx:eax
89ff3147 2472 mask = (1 << xAX) | (1 << xDX);
2473 if (!c_mode)
2474 mask |= 1 << xCX;
2475
de50b98b 2476 if (po->op == OP_CALL
89ff3147 2477 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
5101a5f9 2478 return 1;
2479
2480 for (i = 0; i < po_test->operand_cnt; i++)
2481 if (IS(po_test->operand[i].name, po->operand[0].name))
2482 return 1;
2483
2484 return 0;
2485}
2486
940e8e66 2487// scan for any po_test operand modification in range given
89ff3147 2488static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2489 int c_mode)
69a3cdfc 2490{
2b43685d 2491 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2492 return -1;
2493
69a3cdfc 2494 for (; i < opcnt; i++) {
89ff3147 2495 if (is_any_opr_modified(po_test, &ops[i], c_mode))
69a3cdfc 2496 return i;
2497 }
2498
2499 return -1;
2500}
2501
940e8e66 2502// scan for po_test operand[0] modification in range given
2503static int scan_for_mod_opr0(struct parsed_op *po_test,
2504 int i, int opcnt)
2505{
2506 for (; i < opcnt; i++) {
2507 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2508 return i;
2509 }
2510
2511 return -1;
2512}
2513
04f8a628 2514static int scan_for_flag_set(int i, int magic, int *branched,
2515 int *setters, int *setter_cnt)
69a3cdfc 2516{
04f8a628 2517 struct label_ref *lr;
2b43685d 2518 int ret;
de50b98b 2519
2520 while (i >= 0) {
04f8a628 2521 if (ops[i].cc_scratch == magic) {
04abc5d6 2522 // is this a problem?
2523 //ferr(&ops[i], "%s looped\n", __func__);
2524 return 0;
04f8a628 2525 }
2526 ops[i].cc_scratch = magic;
2527
d7857c3a 2528 if (g_labels[i] != NULL) {
2b43685d 2529 *branched = 1;
04f8a628 2530
2531 lr = &g_label_refs[i];
2532 for (; lr->next; lr = lr->next) {
92d715b6 2533 check_i(&ops[i], lr->i);
04f8a628 2534 ret = scan_for_flag_set(lr->i, magic,
2535 branched, setters, setter_cnt);
2536 if (ret < 0)
2537 return ret;
2538 }
2539
92d715b6 2540 check_i(&ops[i], lr->i);
de50b98b 2541 if (i > 0 && LAST_OP(i - 1)) {
94d447fb 2542 i = lr->i;
de50b98b 2543 continue;
2544 }
04f8a628 2545 ret = scan_for_flag_set(lr->i, magic,
2546 branched, setters, setter_cnt);
2b43685d 2547 if (ret < 0)
2548 return ret;
de50b98b 2549 }
2550 i--;
2551
2b43685d 2552 if (ops[i].flags & OPF_FLAGS) {
2553 setters[*setter_cnt] = i;
2554 (*setter_cnt)++;
2555 return 0;
2556 }
69a3cdfc 2557
5c024ef7 2558 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
69a3cdfc 2559 return -1;
69a3cdfc 2560 }
2561
2562 return -1;
2563}
2564
5101a5f9 2565// scan back for cdq, if anything modifies edx, fail
2566static int scan_for_cdq_edx(int i)
2567{
cdfaeed7 2568 while (i >= 0) {
d7857c3a 2569 if (g_labels[i] != NULL) {
cdfaeed7 2570 if (g_label_refs[i].next != NULL)
2571 return -1;
2572 if (i > 0 && LAST_OP(i - 1)) {
2573 i = g_label_refs[i].i;
2574 continue;
2575 }
2576 return -1;
2577 }
2578 i--;
2579
5101a5f9 2580 if (ops[i].op == OP_CDQ)
2581 return i;
2582
2583 if (ops[i].regmask_dst & (1 << xDX))
2584 return -1;
5101a5f9 2585 }
2586
2587 return -1;
2588}
2589
64c59faf 2590static int scan_for_reg_clear(int i, int reg)
2591{
cdfaeed7 2592 while (i >= 0) {
d7857c3a 2593 if (g_labels[i] != NULL) {
cdfaeed7 2594 if (g_label_refs[i].next != NULL)
2595 return -1;
2596 if (i > 0 && LAST_OP(i - 1)) {
2597 i = g_label_refs[i].i;
2598 continue;
2599 }
2600 return -1;
2601 }
2602 i--;
2603
64c59faf 2604 if (ops[i].op == OP_XOR
2605 && ops[i].operand[0].lmod == OPLM_DWORD
2606 && ops[i].operand[0].reg == ops[i].operand[1].reg
2607 && ops[i].operand[0].reg == reg)
2608 return i;
2609
2610 if (ops[i].regmask_dst & (1 << reg))
2611 return -1;
64c59faf 2612 }
2613
2614 return -1;
2615}
2616
ee2361b9 2617static void patch_esp_adjust(struct parsed_op *po, int adj)
2618{
2619 ferr_assert(po, po->op == OP_ADD);
2620 ferr_assert(po, IS(opr_name(po, 0), "esp"));
2621 ferr_assert(po, po->operand[1].type == OPT_CONST);
2622
2623 // this is a bit of a hack, but deals with use of
2624 // single adj for multiple calls
2625 po->operand[1].val -= adj;
2626 po->flags |= OPF_RMD;
2627 if (po->operand[1].val == 0)
2628 po->flags |= OPF_DONE;
2629 ferr_assert(po, (int)po->operand[1].val >= 0);
2630}
2631
1bafb621 2632// scan for positive, constant esp adjust
ee2361b9 2633// multipath case is preliminary
9af2d373 2634static int scan_for_esp_adjust(int i, int opcnt,
ee2361b9 2635 int adj_expect, int *adj, int *is_multipath, int do_update)
1bafb621 2636{
bfacdc83 2637 int adj_expect_unknown = 0;
7ba45c34 2638 struct parsed_op *po;
46411e6c 2639 int first_pop = -1;
bfacdc83 2640 int adj_best = 0;
4741fdfe 2641
ee2361b9 2642 *adj = *is_multipath = 0;
bfacdc83 2643 if (adj_expect < 0) {
2644 adj_expect_unknown = 1;
2645 adj_expect = 32 * 4; // enough?
2646 }
7ba45c34 2647
9af2d373 2648 for (; i < opcnt && *adj < adj_expect; i++) {
d7857c3a 2649 if (g_labels[i] != NULL)
ee2361b9 2650 *is_multipath = 1;
a2c1d768 2651
5e49b270 2652 po = &ops[i];
2653 if (po->flags & OPF_DONE)
2654 continue;
2655
7ba45c34 2656 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2657 if (po->operand[1].type != OPT_CONST)
1bafb621 2658 ferr(&ops[i], "non-const esp adjust?\n");
7ba45c34 2659 *adj += po->operand[1].val;
1bafb621 2660 if (*adj & 3)
2661 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
ee2361b9 2662 if (do_update) {
2663 if (!*is_multipath)
2664 patch_esp_adjust(po, adj_expect);
2665 else
2666 po->flags |= OPF_RMD;
2667 }
1bafb621 2668 return i;
2669 }
5e49b270 2670 else if (po->op == OP_PUSH) {
5c024ef7 2671 //if (first_pop == -1)
2672 // first_pop = -2; // none
7ba45c34 2673 *adj -= lmod_bytes(po, po->operand[0].lmod);
46411e6c 2674 }
5e49b270 2675 else if (po->op == OP_POP) {
91ca764a 2676 if (!(po->flags & OPF_DONE)) {
2677 // seems like msvc only uses 'pop ecx' for stack realignment..
2678 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2679 break;
2680 if (first_pop == -1 && *adj >= 0)
2681 first_pop = i;
2682 }
ee2361b9 2683 if (do_update && *adj >= 0) {
2684 po->flags |= OPF_RMD;
2685 if (!*is_multipath)
2686 po->flags |= OPF_DONE;
2687 }
2688
7ba45c34 2689 *adj += lmod_bytes(po, po->operand[0].lmod);
bfacdc83 2690 if (*adj > adj_best)
2691 adj_best = *adj;
46411e6c 2692 }
e56ab892 2693 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
4741fdfe 2694 if (po->op == OP_JMP && po->btj == NULL) {
5e49b270 2695 if (po->bt_i <= i)
2696 break;
4741fdfe 2697 i = po->bt_i - 1;
2698 continue;
2699 }
e56ab892 2700 if (po->op != OP_CALL)
a2c1d768 2701 break;
e56ab892 2702 if (po->operand[0].type != OPT_LABEL)
a2c1d768 2703 break;
91ca764a 2704 if (po->pp != NULL && po->pp->is_stdcall)
89ff3147 2705 break;
bfacdc83 2706 if (adj_expect_unknown && first_pop >= 0)
2707 break;
91ca764a 2708 // assume it's another cdecl call
e56ab892 2709 }
a2c1d768 2710 }
7ba45c34 2711
108e9fe3 2712 if (first_pop >= 0) {
bfacdc83 2713 // probably only 'pop ecx' was used
2714 *adj = adj_best;
46411e6c 2715 return first_pop;
1bafb621 2716 }
2717
2718 return -1;
2719}
2720
a3684be1 2721static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2722{
2723 struct parsed_op *po;
2724 int j;
2725
2726 if (i < 0)
2727 ferr(ops, "%s: followed bad branch?\n", __func__);
2728
2729 for (; i < opcnt; i++) {
2730 po = &ops[i];
2731 if (po->cc_scratch == magic)
2732 return;
2733 po->cc_scratch = magic;
2734 po->flags |= flags;
2735
2736 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2737 if (po->btj != NULL) {
2738 // jumptable
2739 for (j = 0; j < po->btj->count; j++)
2740 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2741 return;
2742 }
2743
2744 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
5c024ef7 2745 if (!(po->flags & OPF_CJMP))
a3684be1 2746 return;
2747 }
2748 if (po->flags & OPF_TAIL)
2749 return;
2750 }
2751}
2752
1cd4a663 2753static const struct parsed_proto *try_recover_pp(
da87ae38 2754 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
1cd4a663 2755{
2756 const struct parsed_proto *pp = NULL;
89ff3147 2757 char buf[256];
2758 char *p;
1cd4a663 2759
2760 // maybe an arg of g_func?
2761 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2762 {
2763 char ofs_reg[16] = { 0, };
2764 int arg, arg_s, arg_i;
2765 int stack_ra = 0;
2766 int offset = 0;
2767
9af2d373 2768 if (g_header_mode)
2769 return NULL;
2770
1cd4a663 2771 parse_stack_access(po, opr->name, ofs_reg,
037f4971 2772 &offset, &stack_ra, NULL, 0);
1cd4a663 2773 if (ofs_reg[0] != 0)
2774 ferr(po, "offset reg on arg access?\n");
da87ae38 2775 if (offset <= stack_ra) {
2776 // search who set the stack var instead
2777 if (search_instead != NULL)
2778 *search_instead = 1;
2779 return NULL;
2780 }
1cd4a663 2781
2782 arg_i = (offset - stack_ra - 4) / 4;
2783 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2784 if (g_func_pp->arg[arg].reg != NULL)
2785 continue;
2786 if (arg_s == arg_i)
2787 break;
2788 arg_s++;
2789 }
2790 if (arg == g_func_pp->argc)
2791 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2792
2793 pp = g_func_pp->arg[arg].fptr;
2794 if (pp == NULL)
46411e6c 2795 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
89ff3147 2796 check_func_pp(po, pp, "icall arg");
2797 }
2798 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2799 // label[index]
2800 p = strchr(opr->name + 1, '[');
2801 memcpy(buf, opr->name, p - opr->name);
2802 buf[p - opr->name] = 0;
92d715b6 2803 pp = proto_parse(g_fhdr, buf, g_quiet_pp);
1cd4a663 2804 }
2805 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
9af2d373 2806 pp = proto_parse(g_fhdr, opr->name, g_quiet_pp);
2807 if (pp == NULL) {
2808 if (!g_header_mode)
2809 ferr(po, "proto_parse failed for icall to '%s'\n", opr->name);
2810 }
2811 else
2812 check_func_pp(po, pp, "reg-fptr ref");
1cd4a663 2813 }
2814
2815 return pp;
2816}
2817
da87ae38 2818static void scan_for_call_type(int i, const struct parsed_opr *opr,
db63af51 2819 int magic, const struct parsed_proto **pp_found, int *pp_i,
2820 int *multi)
1cd4a663 2821{
2822 const struct parsed_proto *pp = NULL;
2823 struct parsed_op *po;
2824 struct label_ref *lr;
2825
037f4971 2826 ops[i].cc_scratch = magic;
1cd4a663 2827
037f4971 2828 while (1) {
d7857c3a 2829 if (g_labels[i] != NULL) {
1cd4a663 2830 lr = &g_label_refs[i];
92d715b6 2831 for (; lr != NULL; lr = lr->next) {
2832 check_i(&ops[i], lr->i);
db63af51 2833 scan_for_call_type(lr->i, opr, magic, pp_found, pp_i, multi);
92d715b6 2834 }
46411e6c 2835 if (i > 0 && LAST_OP(i - 1))
2836 return;
1cd4a663 2837 }
037f4971 2838
1cd4a663 2839 i--;
037f4971 2840 if (i < 0)
2841 break;
2842
2843 if (ops[i].cc_scratch == magic)
2844 return;
2845 ops[i].cc_scratch = magic;
1cd4a663 2846
2847 if (!(ops[i].flags & OPF_DATA))
2848 continue;
2849 if (!is_opr_modified(opr, &ops[i]))
2850 continue;
2851 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2852 // most probably trashed by some processing
2853 *pp_found = NULL;
2854 return;
2855 }
2856
2857 opr = &ops[i].operand[1];
2858 if (opr->type != OPT_REG)
2859 break;
2860 }
2861
2862 po = (i >= 0) ? &ops[i] : ops;
2863
2864 if (i < 0) {
2865 // reached the top - can only be an arg-reg
04abc5d6 2866 if (opr->type != OPT_REG || g_func_pp == NULL)
1cd4a663 2867 return;
2868
2869 for (i = 0; i < g_func_pp->argc; i++) {
2870 if (g_func_pp->arg[i].reg == NULL)
2871 continue;
2872 if (IS(opr->name, g_func_pp->arg[i].reg))
2873 break;
2874 }
2875 if (i == g_func_pp->argc)
2876 return;
2877 pp = g_func_pp->arg[i].fptr;
2878 if (pp == NULL)
46411e6c 2879 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2880 i + 1, g_func_pp->arg[i].reg);
89ff3147 2881 check_func_pp(po, pp, "icall reg-arg");
1cd4a663 2882 }
2883 else
da87ae38 2884 pp = try_recover_pp(po, opr, NULL);
1cd4a663 2885
89ff3147 2886 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
1cd4a663 2887 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2888 || (*pp_found)->is_stdcall != pp->is_stdcall
89ff3147 2889 || (*pp_found)->is_fptr != pp->is_fptr
1cd4a663 2890 || (*pp_found)->argc != pp->argc
2891 || (*pp_found)->argc_reg != pp->argc_reg
2892 || (*pp_found)->argc_stack != pp->argc_stack)
2893 {
2894 ferr(po, "icall: parsed_proto mismatch\n");
2895 }
89ff3147 2896 *multi = 1;
1cd4a663 2897 }
db63af51 2898 if (pp != NULL) {
1cd4a663 2899 *pp_found = pp;
db63af51 2900 *pp_i = po - ops;
2901 }
1cd4a663 2902}
2903
66bdb2b0 2904static void add_label_ref(struct label_ref *lr, int op_i)
9af2d373 2905{
66bdb2b0 2906 struct label_ref *lr_new;
9af2d373 2907
66bdb2b0 2908 if (lr->i == -1) {
2909 lr->i = op_i;
2910 return;
2911 }
9af2d373 2912
66bdb2b0 2913 lr_new = calloc(1, sizeof(*lr_new));
2914 lr_new->i = op_i;
2915 lr_new->next = lr->next;
2916 lr->next = lr_new;
2917}
2918
2919static struct parsed_data *try_resolve_jumptab(int i, int opcnt)
2920{
2921 struct parsed_op *po = &ops[i];
2922 struct parsed_data *pd;
2923 char label[NAMELEN], *p;
2924 int len, j, l;
2925
2926 p = strchr(po->operand[0].name, '[');
2927 if (p == NULL)
2928 return NULL;
2929
2930 len = p - po->operand[0].name;
2931 strncpy(label, po->operand[0].name, len);
2932 label[len] = 0;
2933
2934 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
2935 if (IS(g_func_pd[j].label, label)) {
2936 pd = &g_func_pd[j];
2937 break;
2938 }
2939 }
2940 if (pd == NULL)
2941 //ferr(po, "label '%s' not parsed?\n", label);
2942 return NULL;
2943
2944 if (pd->type != OPT_OFFSET)
2945 ferr(po, "label '%s' with non-offset data?\n", label);
2946
2947 // find all labels, link
2948 for (j = 0; j < pd->count; j++) {
2949 for (l = 0; l < opcnt; l++) {
2950 if (g_labels[l] != NULL && IS(g_labels[l], pd->d[j].u.label)) {
2951 add_label_ref(&g_label_refs[l], i);
2952 pd->d[j].bt_i = l;
2953 break;
2954 }
2955 }
2956 }
2957
2958 return pd;
2959}
2960
2961static void clear_labels(int count)
2962{
2963 int i;
2964
2965 for (i = 0; i < count; i++) {
2966 if (g_labels[i] != NULL) {
2967 free(g_labels[i]);
2968 g_labels[i] = NULL;
2969 }
2970 }
2971}
2972
2973static void resolve_branches_parse_calls(int opcnt)
2974{
2975 const struct parsed_proto *pp_c;
2976 struct parsed_proto *pp;
2977 struct parsed_data *pd;
2978 struct parsed_op *po;
2979 const char *tmpname;
2980 int i, l, ret;
2981
2982 for (i = 0; i < opcnt; i++)
2983 {
2984 po = &ops[i];
2985 po->bt_i = -1;
2986 po->btj = NULL;
2987
2988 if (po->op == OP_CALL) {
2989 pp = NULL;
2990
2991 if (po->operand[0].type == OPT_LABEL) {
2992 tmpname = opr_name(po, 0);
2993 if (IS_START(tmpname, "loc_"))
2994 ferr(po, "call to loc_*\n");
2995 pp_c = proto_parse(g_fhdr, tmpname, g_header_mode);
2996 if (!g_header_mode && pp_c == NULL)
2997 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
2998
2999 if (pp_c != NULL) {
3000 pp = proto_clone(pp_c);
3001 my_assert_not(pp, NULL);
3002 }
3003 }
3004 else if (po->datap != NULL) {
3005 pp = calloc(1, sizeof(*pp));
3006 my_assert_not(pp, NULL);
3007
3008 ret = parse_protostr(po->datap, pp);
3009 if (ret < 0)
3010 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3011 free(po->datap);
3012 po->datap = NULL;
3013 }
3014
3015 if (pp != NULL) {
3016 if (pp->is_fptr)
3017 check_func_pp(po, pp, "fptr var call");
3018 if (pp->is_noreturn)
3019 po->flags |= OPF_TAIL;
3020 }
3021 po->pp = pp;
3022 continue;
3023 }
3024
3025 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3026 continue;
3027
3028 if (po->operand[0].type == OPT_REGMEM) {
3029 pd = try_resolve_jumptab(i, opcnt);
3030 if (pd == NULL)
3031 goto tailcall;
3032
3033 po->btj = pd;
3034 continue;
3035 }
3036
3037 for (l = 0; l < opcnt; l++) {
3038 if (g_labels[l] != NULL
3039 && IS(po->operand[0].name, g_labels[l]))
3040 {
3041 if (l == i + 1 && po->op == OP_JMP) {
3042 // yet another alignment type..
3043 po->flags |= OPF_RMD|OPF_DONE;
3044 break;
3045 }
3046 add_label_ref(&g_label_refs[l], i);
3047 po->bt_i = l;
3048 break;
3049 }
3050 }
3051
3052 if (po->bt_i != -1 || (po->flags & OPF_RMD))
3053 continue;
3054
3055 if (po->operand[0].type == OPT_LABEL)
3056 // assume tail call
3057 goto tailcall;
3058
3059 ferr(po, "unhandled branch\n");
3060
3061tailcall:
3062 po->op = OP_CALL;
3063 po->flags |= OPF_TAIL;
3064 if (i > 0 && ops[i - 1].op == OP_POP)
3065 po->flags |= OPF_ATAIL;
3066 i--; // reprocess
3067 }
9af2d373 3068}
3069
3070static void scan_prologue_epilogue(int opcnt)
3071{
3072 int ecx_push = 0, esp_sub = 0;
3073 int found;
3074 int i, j, l;
3075
3076 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
3077 && ops[1].op == OP_MOV
3078 && IS(opr_name(&ops[1], 0), "ebp")
3079 && IS(opr_name(&ops[1], 1), "esp"))
3080 {
3081 g_bp_frame = 1;
5e49b270 3082 ops[0].flags |= OPF_RMD | OPF_DONE;
3083 ops[1].flags |= OPF_RMD | OPF_DONE;
9af2d373 3084 i = 2;
3085
3086 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
3087 g_stack_fsz = opr_const(&ops[2], 1);
5e49b270 3088 ops[2].flags |= OPF_RMD | OPF_DONE;
9af2d373 3089 i++;
3090 }
3091 else {
3092 // another way msvc builds stack frame..
3093 i = 2;
3094 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3095 g_stack_fsz += 4;
5e49b270 3096 ops[i].flags |= OPF_RMD | OPF_DONE;
9af2d373 3097 ecx_push++;
3098 i++;
3099 }
3100 // and another way..
3101 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
3102 && ops[i].operand[1].type == OPT_CONST
3103 && ops[i + 1].op == OP_CALL
3104 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
3105 {
3106 g_stack_fsz += ops[i].operand[1].val;
5e49b270 3107 ops[i].flags |= OPF_RMD | OPF_DONE;
9af2d373 3108 i++;
5e49b270 3109 ops[i].flags |= OPF_RMD | OPF_DONE;
9af2d373 3110 i++;
3111 }
3112 }
3113
3114 found = 0;
3115 do {
3116 for (; i < opcnt; i++)
66bdb2b0 3117 if (ops[i].flags & OPF_TAIL)
9af2d373 3118 break;
3119 j = i - 1;
3120 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
66bdb2b0 3121 if (ops[j].bt_i != -1 || ops[j].btj != NULL)
3122 break;
3123 i--;
9af2d373 3124 j--;
3125 }
3126
3127 if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
3128 || ops[j].op == OP_LEAVE)
3129 {
5e49b270 3130 ops[j].flags |= OPF_RMD | OPF_DONE;
9af2d373 3131 }
66bdb2b0 3132 else if (ops[i].op == OP_CALL && ops[i].pp != NULL
3133 && ops[i].pp->is_noreturn)
3134 {
3135 // on noreturn, msvc sometimes cleans stack, sometimes not
3136 i++;
3137 found = 1;
3138 continue;
3139 }
9af2d373 3140 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3141 ferr(&ops[j], "'pop ebp' expected\n");
3142
3143 if (g_stack_fsz != 0) {
bfacdc83 3144 if (ops[j].op == OP_LEAVE)
3145 j--;
3146 else if (ops[j].op == OP_POP
3147 && ops[j - 1].op == OP_MOV
9af2d373 3148 && IS(opr_name(&ops[j - 1], 0), "esp")
3149 && IS(opr_name(&ops[j - 1], 1), "ebp"))
3150 {
5e49b270 3151 ops[j - 1].flags |= OPF_RMD | OPF_DONE;
bfacdc83 3152 j -= 2;
9af2d373 3153 }
bfacdc83 3154 else if (!(g_ida_func_attr & IDAFA_NORETURN))
9af2d373 3155 {
bfacdc83 3156 ferr(&ops[j], "esp restore expected\n");
9af2d373 3157 }
3158
bfacdc83 3159 if (ecx_push && j >= 0 && ops[j].op == OP_POP
3160 && IS(opr_name(&ops[j], 0), "ecx"))
9af2d373 3161 {
bfacdc83 3162 ferr(&ops[j], "unexpected ecx pop\n");
9af2d373 3163 }
3164 }
3165
3166 found = 1;
3167 i++;
3168 } while (i < opcnt);
3169
66bdb2b0 3170 if (!found)
3171 ferr(ops, "missing ebp epilogue\n");
9af2d373 3172 return;
3173 }
3174
3175 // non-bp frame
3176 i = 0;
3177 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
5e49b270 3178 ops[i].flags |= OPF_RMD | OPF_DONE;
9af2d373 3179 g_stack_fsz += 4;
3180 ecx_push++;
3181 i++;
3182 }
3183
3184 for (; i < opcnt; i++) {
3185 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
3186 break;
3187 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
3188 && ops[i].operand[1].type == OPT_CONST)
3189 {
3190 g_stack_fsz = ops[i].operand[1].val;
5e49b270 3191 ops[i].flags |= OPF_RMD | OPF_DONE;
9af2d373 3192 esp_sub = 1;
3193 break;
3194 }
3195 }
3196
3197 if (ecx_push && !esp_sub) {
3198 // could actually be args for a call..
3199 for (; i < opcnt; i++)
3200 if (ops[i].op != OP_PUSH)
3201 break;
3202
3203 if (ops[i].op == OP_CALL && ops[i].operand[0].type == OPT_LABEL) {
3204 const struct parsed_proto *pp;
3205 pp = proto_parse(g_fhdr, opr_name(&ops[i], 0), 1);
3206 j = pp ? pp->argc_stack : 0;
3207 while (i > 0 && j > 0) {
3208 i--;
3209 if (ops[i].op == OP_PUSH) {
5e49b270 3210 ops[i].flags &= ~(OPF_RMD | OPF_DONE);
9af2d373 3211 j--;
3212 }
3213 }
3214 if (j != 0)
3215 ferr(&ops[i], "unhandled prologue\n");
3216
3217 // recheck
3218 i = g_stack_fsz = ecx_push = 0;
3219 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3220 if (!(ops[i].flags & OPF_RMD))
3221 break;
3222 g_stack_fsz += 4;
3223 ecx_push++;
3224 i++;
3225 }
3226 }
3227 }
3228
3229 found = 0;
3230 if (ecx_push || esp_sub)
3231 {
3232 g_sp_frame = 1;
3233
3234 i++;
3235 do {
3236 for (; i < opcnt; i++)
66bdb2b0 3237 if (ops[i].flags & OPF_TAIL)
9af2d373 3238 break;
3239 j = i - 1;
3240 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
66bdb2b0 3241 if (ops[j].bt_i != -1 || ops[j].btj != NULL)
3242 break;
3243 i--;
9af2d373 3244 j--;
3245 }
3246
3247 if (ecx_push > 0) {
3248 for (l = 0; l < ecx_push; l++) {
3249 if (ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ecx"))
3250 /* pop ecx */;
3251 else if (ops[j].op == OP_ADD
3252 && IS(opr_name(&ops[j], 0), "esp")
3253 && ops[j].operand[1].type == OPT_CONST)
3254 {
3255 /* add esp, N */
5e49b270 3256 l += ops[j].operand[1].val / 4 - 1;
9af2d373 3257 }
3258 else
3259 ferr(&ops[j], "'pop ecx' expected\n");
3260
5e49b270 3261 ops[j].flags |= OPF_RMD | OPF_DONE;
9af2d373 3262 j--;
3263 }
3264 if (l != ecx_push)
3265 ferr(&ops[j], "epilogue scan failed\n");
3266
3267 found = 1;
3268 }
3269
3270 if (esp_sub) {
3271 if (ops[j].op != OP_ADD
3272 || !IS(opr_name(&ops[j], 0), "esp")
3273 || ops[j].operand[1].type != OPT_CONST
3274 || ops[j].operand[1].val != g_stack_fsz)
3275 ferr(&ops[j], "'add esp' expected\n");
3276
5e49b270 3277 ops[j].flags |= OPF_RMD | OPF_DONE;
9af2d373 3278 ops[j].operand[1].val = 0; // hack for stack arg scanner
3279 found = 1;
3280 }
3281
3282 i++;
3283 } while (i < opcnt);
66bdb2b0 3284
3285 if (!found)
3286 ferr(ops, "missing esp epilogue\n");
9af2d373 3287 }
3288}
3289
89ff3147 3290static const struct parsed_proto *resolve_icall(int i, int opcnt,
db63af51 3291 int *pp_i, int *multi_src)
1cd4a663 3292{
3293 const struct parsed_proto *pp = NULL;
da87ae38 3294 int search_advice = 0;
1cd4a663 3295
89ff3147 3296 *multi_src = 0;
db63af51 3297 *pp_i = -1;
89ff3147 3298
1cd4a663 3299 switch (ops[i].operand[0].type) {
3300 case OPT_REGMEM:
3301 case OPT_LABEL:
3302 case OPT_OFFSET:
da87ae38 3303 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
3304 if (!search_advice)
3305 break;
3306 // fallthrough
1cd4a663 3307 default:
89ff3147 3308 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
db63af51 3309 pp_i, multi_src);
1cd4a663 3310 break;
3311 }
3312
3313 return pp;
3314}
3315
23fd0b11 3316// find an instruction that changed opr before i op
db63af51 3317// *op_i must be set to -1 by the caller
92d715b6 3318// *entry is set to 1 if one source is determined to be the caller
3319// returns 1 if found, *op_i is then set to origin
23fd0b11 3320static int resolve_origin(int i, const struct parsed_opr *opr,
92d715b6 3321 int magic, int *op_i, int *is_caller)
1f84f6b3 3322{
3323 struct label_ref *lr;
3324 int ret = 0;
3325
92d715b6 3326 if (ops[i].cc_scratch == magic)
3327 return 0;
1f84f6b3 3328 ops[i].cc_scratch = magic;
3329
3330 while (1) {
d7857c3a 3331 if (g_labels[i] != NULL) {
1f84f6b3 3332 lr = &g_label_refs[i];
92d715b6 3333 for (; lr != NULL; lr = lr->next) {
3334 check_i(&ops[i], lr->i);
3335 ret |= resolve_origin(lr->i, opr, magic, op_i, is_caller);
3336 }
1f84f6b3 3337 if (i > 0 && LAST_OP(i - 1))
3338 return ret;
3339 }
3340
3341 i--;
92d715b6 3342 if (i < 0) {
3343 if (is_caller != NULL)
3344 *is_caller = 1;
1f84f6b3 3345 return -1;
92d715b6 3346 }
1f84f6b3 3347
3348 if (ops[i].cc_scratch == magic)
ebc4dc43 3349 return ret;
1f84f6b3 3350 ops[i].cc_scratch = magic;
3351
3352 if (!(ops[i].flags & OPF_DATA))
3353 continue;
3354 if (!is_opr_modified(opr, &ops[i]))
3355 continue;
23fd0b11 3356
3357 if (*op_i >= 0) {
3358 if (*op_i == i)
ebc4dc43 3359 return ret | 1;
3360
23fd0b11 3361 // XXX: could check if the other op does the same
3362 return -1;
3363 }
3364
3365 *op_i = i;
ebc4dc43 3366 return ret | 1;
23fd0b11 3367 }
3368}
3369
db63af51 3370// find an instruction that previously referenced opr
3371// if multiple results are found - fail
3372// *op_i must be set to -1 by the caller
3373// returns 1 if found, *op_i is then set to referencer insn
3374static int resolve_last_ref(int i, const struct parsed_opr *opr,
3375 int magic, int *op_i)
3376{
3377 struct label_ref *lr;
3378 int ret = 0;
3379
3380 if (ops[i].cc_scratch == magic)
3381 return 0;
3382 ops[i].cc_scratch = magic;
3383
3384 while (1) {
3385 if (g_labels[i] != NULL) {
3386 lr = &g_label_refs[i];
3387 for (; lr != NULL; lr = lr->next) {
3388 check_i(&ops[i], lr->i);
3389 ret |= resolve_last_ref(lr->i, opr, magic, op_i);
3390 }
3391 if (i > 0 && LAST_OP(i - 1))
3392 return ret;
3393 }
3394
3395 i--;
3396 if (i < 0)
3397 return -1;
3398
3399 if (ops[i].cc_scratch == magic)
3400 return 0;
3401 ops[i].cc_scratch = magic;
3402
3403 if (!is_opr_referenced(opr, &ops[i]))
3404 continue;
3405
3406 if (*op_i >= 0)
3407 return -1;
3408
3409 *op_i = i;
3410 return 1;
3411 }
3412}
3413
3414// find next instruction that reads opr
3415// if multiple results are found - fail
3416// *op_i must be set to -1 by the caller
3417// returns 1 if found, *op_i is then set to referencer insn
3418static int find_next_read(int i, int opcnt,
3419 const struct parsed_opr *opr, int magic, int *op_i)
3420{
3421 struct parsed_op *po;
3422 int j, ret = 0;
3423
3424 for (; i < opcnt; i++)
3425 {
3426 if (ops[i].cc_scratch == magic)
3427 return 0;
3428 ops[i].cc_scratch = magic;
3429
3430 po = &ops[i];
3431 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
3432 if (po->btj != NULL) {
3433 // jumptable
3434 for (j = 0; j < po->btj->count; j++) {
3435 check_i(po, po->btj->d[j].bt_i);
3436 ret |= find_next_read(po->btj->d[j].bt_i, opcnt, opr,
3437 magic, op_i);
3438 }
3439 return ret;
3440 }
3441
3442 if (po->flags & OPF_RMD)
3443 continue;
3444 check_i(po, po->bt_i);
3445 if (po->flags & OPF_CJMP) {
3446 ret = find_next_read(po->bt_i, opcnt, opr, magic, op_i);
3447 if (ret < 0)
3448 return ret;
3449 }
3450
3451 i = po->bt_i - 1;
3452 continue;
3453 }
3454
3455 if (!is_opr_read(opr, po)) {
3456 if (is_opr_modified(opr, po))
3457 // it's overwritten
3458 return 0;
3459 if (po->flags & OPF_TAIL)
3460 return 0;
3461 continue;
3462 }
3463
3464 if (*op_i >= 0)
3465 return -1;
3466
3467 *op_i = i;
3468 return 1;
3469 }
3470
3471 return 0;
3472}
3473
23fd0b11 3474static int try_resolve_const(int i, const struct parsed_opr *opr,
3475 int magic, unsigned int *val)
3476{
3477 int s_i = -1;
92d715b6 3478 int ret;
23fd0b11 3479
92d715b6 3480 ret = resolve_origin(i, opr, magic, &s_i, NULL);
23fd0b11 3481 if (ret == 1) {
3482 i = s_i;
1f84f6b3 3483 if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
3484 return -1;
3485
3486 *val = ops[i].operand[1].val;
3487 return 1;
3488 }
23fd0b11 3489
3490 return -1;
1f84f6b3 3491}
3492
26677139 3493static struct parsed_proto *process_call_early(int i, int opcnt,
3494 int *adj_i)
3495{
3496 struct parsed_op *po = &ops[i];
3497 struct parsed_proto *pp;
3498 int multipath = 0;
3499 int adj = 0;
bfacdc83 3500 int j, ret;
26677139 3501
3502 pp = po->pp;
3503 if (pp == NULL || pp->is_vararg || pp->argc_reg != 0)
3504 // leave for later
3505 return NULL;
3506
3507 // look for and make use of esp adjust
3508 *adj_i = ret = -1;
3509 if (!pp->is_stdcall && pp->argc_stack > 0)
3510 ret = scan_for_esp_adjust(i + 1, opcnt,
ee2361b9 3511 pp->argc_stack * 4, &adj, &multipath, 0);
26677139 3512 if (ret >= 0) {
3513 if (pp->argc_stack > adj / 4)
3514 return NULL;
3515 if (multipath)
3516 return NULL;
bfacdc83 3517 if (ops[ret].op == OP_POP) {
3518 for (j = 1; j < adj / 4; j++) {
3519 if (ops[ret + j].op != OP_POP
3520 || ops[ret + j].operand[0].reg != xCX)
3521 {
3522 return NULL;
3523 }
3524 }
3525 }
26677139 3526 }
3527
3528 *adj_i = ret;
3529 return pp;
3530}
3531
9af2d373 3532static struct parsed_proto *process_call(int i, int opcnt)
3533{
3534 struct parsed_op *po = &ops[i];
3535 const struct parsed_proto *pp_c;
3536 struct parsed_proto *pp;
3537 const char *tmpname;
db63af51 3538 int call_i = -1, ref_i = -1;
26677139 3539 int adj = 0, multipath = 0;
9af2d373 3540 int ret, arg;
3541
3542 tmpname = opr_name(po, 0);
3543 pp = po->pp;
3544 if (pp == NULL)
3545 {
3546 // indirect call
db63af51 3547 pp_c = resolve_icall(i, opcnt, &call_i, &multipath);
9af2d373 3548 if (pp_c != NULL) {
3549 if (!pp_c->is_func && !pp_c->is_fptr)
3550 ferr(po, "call to non-func: %s\n", pp_c->name);
3551 pp = proto_clone(pp_c);
3552 my_assert_not(pp, NULL);
26677139 3553 if (multipath)
9af2d373 3554 // not resolved just to single func
3555 pp->is_fptr = 1;
3556
3557 switch (po->operand[0].type) {
3558 case OPT_REG:
3559 // we resolved this call and no longer need the register
3560 po->regmask_src &= ~(1 << po->operand[0].reg);
db63af51 3561
3562 if (!multipath && i != call_i && ops[call_i].op == OP_MOV
3563 && ops[call_i].operand[1].type == OPT_LABEL)
3564 {
3565 // no other source users?
3566 ret = resolve_last_ref(i, &po->operand[0], opcnt * 10,
3567 &ref_i);
3568 if (ret == 1 && call_i == ref_i) {
3569 // and nothing uses it after us?
3570 ref_i = -1;
3571 ret = find_next_read(i + 1, opcnt, &po->operand[0],
3572 opcnt * 11, &ref_i);
3573 if (ret != 1)
3574 // then also don't need the source mov
3575 ops[call_i].flags |= OPF_RMD;
3576 }
3577 }
9af2d373 3578 break;
3579 case OPT_REGMEM:
3580 pp->is_fptr = 1;
3581 break;
3582 default:
3583 break;
3584 }
3585 }
3586 if (pp == NULL) {
3587 pp = calloc(1, sizeof(*pp));
3588 my_assert_not(pp, NULL);
3589
3590 pp->is_fptr = 1;
ee2361b9 3591 ret = scan_for_esp_adjust(i + 1, opcnt,
bfacdc83 3592 -1, &adj, &multipath, 0);
26677139 3593 if (ret < 0 || adj < 0) {
9af2d373 3594 if (!g_allow_regfunc)
3595 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3596 pp->is_unresolved = 1;
26677139 3597 adj = 0;
9af2d373 3598 }
26677139 3599 adj /= 4;
3600 if (adj > ARRAY_SIZE(pp->arg))
3601 ferr(po, "esp adjust too large: %d\n", adj);
9af2d373 3602 pp->ret_type.name = strdup("int");
26677139 3603 pp->argc = pp->argc_stack = adj;
9af2d373 3604 for (arg = 0; arg < pp->argc; arg++)
3605 pp->arg[arg].type.name = strdup("int");
3606 }
3607 po->pp = pp;
3608 }
3609
3610 // look for and make use of esp adjust
91ca764a 3611 multipath = 0;
9af2d373 3612 ret = -1;
bfacdc83 3613 if (!pp->is_stdcall && pp->argc_stack > 0) {
3614 int adj_expect = pp->is_vararg ? -1 : pp->argc_stack * 4;
9af2d373 3615 ret = scan_for_esp_adjust(i + 1, opcnt,
bfacdc83 3616 adj_expect, &adj, &multipath, 0);
3617 }
9af2d373 3618 if (ret >= 0) {
3619 if (pp->is_vararg) {
26677139 3620 if (adj / 4 < pp->argc_stack) {
3621 fnote(po, "(this call)\n");
3622 ferr(&ops[ret], "esp adjust is too small: %x < %x\n",
3623 adj, pp->argc_stack * 4);
3624 }
9af2d373 3625 // modify pp to make it have varargs as normal args
3626 arg = pp->argc;
26677139 3627 pp->argc += adj / 4 - pp->argc_stack;
9af2d373 3628 for (; arg < pp->argc; arg++) {
3629 pp->arg[arg].type.name = strdup("int");
3630 pp->argc_stack++;
3631 }
3632 if (pp->argc > ARRAY_SIZE(pp->arg))
3633 ferr(po, "too many args for '%s'\n", tmpname);
3634 }
26677139 3635 if (pp->argc_stack > adj / 4) {
9af2d373 3636 fnote(po, "(this call)\n");
3637 ferr(&ops[ret], "stack tracking failed for '%s': %x %x\n",
26677139 3638 tmpname, pp->argc_stack * 4, adj);
9af2d373 3639 }
3640
ee2361b9 3641 scan_for_esp_adjust(i + 1, opcnt,
3642 pp->argc_stack * 4, &adj, &multipath, 1);
9af2d373 3643 }
3644 else if (pp->is_vararg)
3645 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3646 pp->name);
3647
3648 return pp;
3649}
3650
26677139 3651static int collect_call_args_early(struct parsed_op *po, int i,
3652 struct parsed_proto *pp, int *regmask)
3653{
3654 int arg, ret;
3655 int j;
3656
3657 for (arg = 0; arg < pp->argc; arg++)
3658 if (pp->arg[arg].reg == NULL)
3659 break;
3660
3661 // first see if it can be easily done
3662 for (j = i; j > 0 && arg < pp->argc; )
3663 {
3664 if (g_labels[j] != NULL)
3665 return -1;
3666 j--;
3667
3668 if (ops[j].op == OP_CALL)
3669 return -1;
3670 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP)
3671 return -1;
3672 else if (ops[j].op == OP_POP)
3673 return -1;
3674 else if (ops[j].flags & OPF_CJMP)
3675 return -1;
3676 else if (ops[j].op == OP_PUSH) {
3677 if (ops[j].flags & (OPF_FARG|OPF_FARGNR))
3678 return -1;
3679 ret = scan_for_mod(&ops[j], j + 1, i, 1);
3680 if (ret >= 0)
3681 return -1;
3682
3683 if (pp->arg[arg].type.is_va_list)
3684 return -1;
3685
3686 // next arg
3687 for (arg++; arg < pp->argc; arg++)
3688 if (pp->arg[arg].reg == NULL)
3689 break;
3690 }
3691 }
3692
3693 if (arg < pp->argc)
3694 return -1;
3695
3696 // now do it
3697 for (arg = 0; arg < pp->argc; arg++)
3698 if (pp->arg[arg].reg == NULL)
3699 break;
3700
3701 for (j = i; j > 0 && arg < pp->argc; )
3702 {
3703 j--;
3704
3705 if (ops[j].op == OP_PUSH)
3706 {
3707 ops[j].p_argnext = -1;
3708 ferr_assert(&ops[j], pp->arg[arg].datap == NULL);
3709 pp->arg[arg].datap = &ops[j];
3710
3711 if (ops[j].operand[0].type == OPT_REG)
3712 *regmask |= 1 << ops[j].operand[0].reg;
3713
5e49b270 3714 ops[j].flags |= OPF_RMD | OPF_DONE | OPF_FARGNR | OPF_FARG;
26677139 3715 ops[j].flags &= ~OPF_RSAVE;
3716
3717 // next arg
3718 for (arg++; arg < pp->argc; arg++)
3719 if (pp->arg[arg].reg == NULL)
3720 break;
3721 }
3722 }
3723
3724 return 0;
3725}
3726
89ff3147 3727static int collect_call_args_r(struct parsed_op *po, int i,
3a5101d7 3728 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3729 int *arg_grp, int arg, int magic, int need_op_saving, int may_reuse)
e56ab892 3730{
3731 struct parsed_proto *pp_tmp;
3a5101d7 3732 struct parsed_op *po_tmp;
e56ab892 3733 struct label_ref *lr;
2b43685d 3734 int need_to_save_current;
3a5101d7 3735 int arg_grp_current = 0;
3736 int save_args_seen = 0;
23fd0b11 3737 int save_args;
e56ab892 3738 int ret = 0;
5f70a34f 3739 int reg;
23fd0b11 3740 char buf[32];
3741 int j, k;
e56ab892 3742
a3684be1 3743 if (i < 0) {
a2c1d768 3744 ferr(po, "dead label encountered\n");
a3684be1 3745 return -1;
3746 }
e56ab892 3747
de50b98b 3748 for (; arg < pp->argc; arg++)
e56ab892 3749 if (pp->arg[arg].reg == NULL)
3750 break;
a3684be1 3751 magic = (magic & 0xffffff) | (arg << 24);
e56ab892 3752
89ff3147 3753 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
e56ab892 3754 {
a3684be1 3755 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
3756 if (ops[j].cc_scratch != magic) {
3757 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
3758 pp->name);
3759 return -1;
3760 }
3761 // ok: have already been here
3762 return 0;
3763 }
3764 ops[j].cc_scratch = magic;
3765
d7857c3a 3766 if (g_labels[j] != NULL && g_label_refs[j].i != -1) {
e56ab892 3767 lr = &g_label_refs[j];
3768 if (lr->next != NULL)
3769 need_op_saving = 1;
a652aa9f 3770 for (; lr->next; lr = lr->next) {
92d715b6 3771 check_i(&ops[j], lr->i);
5c024ef7 3772 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
a652aa9f 3773 may_reuse = 1;
89ff3147 3774 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3a5101d7 3775 arg_grp, arg, magic, need_op_saving, may_reuse);
a3684be1 3776 if (ret < 0)
3777 return ret;
a652aa9f 3778 }
e56ab892 3779
92d715b6 3780 check_i(&ops[j], lr->i);
5c024ef7 3781 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
a652aa9f 3782 may_reuse = 1;
de50b98b 3783 if (j > 0 && LAST_OP(j - 1)) {
e56ab892 3784 // follow last branch in reverse
3785 j = lr->i;
3786 continue;
3787 }
3788 need_op_saving = 1;
89ff3147 3789 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
3a5101d7 3790 arg_grp, arg, magic, need_op_saving, may_reuse);
a3684be1 3791 if (ret < 0)
3792 return ret;
e56ab892 3793 }
3794 j--;
3795
3796 if (ops[j].op == OP_CALL)
3797 {
89ff3147 3798 if (pp->is_unresolved)
3799 break;
3800
092f64e1 3801 pp_tmp = ops[j].pp;
e56ab892 3802 if (pp_tmp == NULL)
7ae48d73 3803 ferr(po, "arg collect hit unparsed call '%s'\n",
3804 ops[j].operand[0].name);
a652aa9f 3805 if (may_reuse && pp_tmp->argc_stack > 0)
de50b98b 3806 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
3807 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
e56ab892 3808 }
fdd5548a 3809 // esp adjust of 0 means we collected it before
3810 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP
3811 && (ops[j].operand[1].type != OPT_CONST
3812 || ops[j].operand[1].val != 0))
3813 {
89ff3147 3814 if (pp->is_unresolved)
3815 break;
3816
2b70f6d3 3817 fnote(po, "(this call)\n");
3818 ferr(&ops[j], "arg collect %d/%d hit esp adjust of %d\n",
fdd5548a 3819 arg, pp->argc, ops[j].operand[1].val);
de50b98b 3820 }
5e49b270 3821 else if (ops[j].op == OP_POP && !(ops[j].flags & OPF_DONE))
9af2d373 3822 {
89ff3147 3823 if (pp->is_unresolved)
3824 break;
3825
2b70f6d3 3826 fnote(po, "(this call)\n");
3827 ferr(&ops[j], "arg collect %d/%d hit pop\n", arg, pp->argc);
de50b98b 3828 }
5c024ef7 3829 else if (ops[j].flags & OPF_CJMP)
de50b98b 3830 {
89ff3147 3831 if (pp->is_unresolved)
3832 break;
3833
a652aa9f 3834 may_reuse = 1;
de50b98b 3835 }
91ca764a 3836 else if (ops[j].op == OP_PUSH
3837 && !(ops[j].flags & (OPF_FARGNR|OPF_DONE)))
e56ab892 3838 {
89ff3147 3839 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
3840 break;
3841
3a5101d7 3842 ops[j].p_argnext = -1;
3843 po_tmp = pp->arg[arg].datap;
3844 if (po_tmp != NULL)
3845 ops[j].p_argnext = po_tmp - ops;
e56ab892 3846 pp->arg[arg].datap = &ops[j];
3a5101d7 3847
2b43685d 3848 need_to_save_current = 0;
23fd0b11 3849 save_args = 0;
5f70a34f 3850 reg = -1;
3851 if (ops[j].operand[0].type == OPT_REG)
3852 reg = ops[j].operand[0].reg;
3853
e56ab892 3854 if (!need_op_saving) {
89ff3147 3855 ret = scan_for_mod(&ops[j], j + 1, i, 1);
2b43685d 3856 need_to_save_current = (ret >= 0);
e56ab892 3857 }
2b43685d 3858 if (need_op_saving || need_to_save_current) {
e56ab892 3859 // mark this push as one that needs operand saving
3860 ops[j].flags &= ~OPF_RMD;
5f70a34f 3861 if (ops[j].p_argnum == 0) {
3862 ops[j].p_argnum = arg + 1;
23fd0b11 3863 save_args |= 1 << arg;
de50b98b 3864 }
fdd5548a 3865 else if (ops[j].p_argnum < arg + 1) {
3866 // XXX: might kill valid var..
3867 //*save_arg_vars &= ~(1 << (ops[j].p_argnum - 1));
3868 ops[j].p_argnum = arg + 1;
3869 save_args |= 1 << arg;
3870 }
3a5101d7 3871
3872 if (save_args_seen & (1 << (ops[j].p_argnum - 1))) {
3873 save_args_seen = 0;
3874 arg_grp_current++;
3875 if (arg_grp_current >= MAX_ARG_GRP)
3876 ferr(&ops[j], "out of arg groups (arg%d), f %s\n",
3877 ops[j].p_argnum, pp->name);
3878 }
e56ab892 3879 }
5f70a34f 3880 else if (ops[j].p_argnum == 0)
e56ab892 3881 ops[j].flags |= OPF_RMD;
3882
a652aa9f 3883 // some PUSHes are reused by different calls on other branches,
de50b98b 3884 // but that can't happen if we didn't branch, so they
3885 // can be removed from future searches (handles nested calls)
a652aa9f 3886 if (!may_reuse)
9af2d373 3887 ops[j].flags |= OPF_FARGNR;
de50b98b 3888
9af2d373 3889 ops[j].flags |= OPF_FARG;
da87ae38 3890 ops[j].flags &= ~OPF_RSAVE;
3891
23fd0b11 3892 // check for __VALIST
04abc5d6 3893 if (!pp->is_unresolved && g_func_pp != NULL
3894 && pp->arg[arg].type.is_va_list)
3895 {
23fd0b11 3896 k = -1;
92d715b6 3897 ret = resolve_origin(j, &ops[j].operand[0],
3898 magic + 1, &k, NULL);
5f70a34f 3899 if (ret == 1 && k >= 0)
23fd0b11 3900 {
5f70a34f 3901 if (ops[k].op == OP_LEA) {
3902 snprintf(buf, sizeof(buf), "arg_%X",
3903 g_func_pp->argc_stack * 4);
3904 if (!g_func_pp->is_vararg
3905 || strstr(ops[k].operand[1].name, buf))
3906 {
5e49b270 3907 ops[k].flags |= OPF_RMD | OPF_DONE;
5f70a34f 3908 ops[j].flags |= OPF_RMD | OPF_VAPUSH;
3909 save_args &= ~(1 << arg);
3910 reg = -1;
3911 }
3912 else
3913 ferr(&ops[j], "lea va_list used, but no vararg?\n");
3914 }
3915 // check for va_list from g_func_pp arg too
3916 else if (ops[k].op == OP_MOV
3917 && is_stack_access(&ops[k], &ops[k].operand[1]))
3918 {
3919 ret = stack_frame_access(&ops[k], &ops[k].operand[1],
3920 buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
3921 if (ret >= 0) {
5e49b270 3922 ops[k].flags |= OPF_RMD | OPF_DONE;
5f70a34f 3923 ops[j].flags |= OPF_RMD;
3924 ops[j].p_argpass = ret + 1;
3925 save_args &= ~(1 << arg);
3926 reg = -1;
3927 }
3928 }
23fd0b11 3929 }
3930 }
3931
3932 *save_arg_vars |= save_args;
3933
3934 // tracking reg usage
5f70a34f 3935 if (reg >= 0)
3936 *regmask |= 1 << reg;
23fd0b11 3937
89ff3147 3938 arg++;
3939 if (!pp->is_unresolved) {
3940 // next arg
3941 for (; arg < pp->argc; arg++)
3942 if (pp->arg[arg].reg == NULL)
3943 break;
3944 }
a3684be1 3945 magic = (magic & 0xffffff) | (arg << 24);
e56ab892 3946 }
3a5101d7 3947
3948 if (ops[j].p_arggrp > arg_grp_current) {
3949 save_args_seen = 0;
3950 arg_grp_current = ops[j].p_arggrp;
3951 }
3952 if (ops[j].p_argnum > 0)
3953 save_args_seen |= 1 << (ops[j].p_argnum - 1);
e56ab892 3954 }
3955
3956 if (arg < pp->argc) {
3957 ferr(po, "arg collect failed for '%s': %d/%d\n",
3958 pp->name, arg, pp->argc);
89ff3147 3959 return -1;
e56ab892 3960 }
89ff3147 3961
3a5101d7 3962 if (arg_grp_current > *arg_grp)
3963 *arg_grp = arg_grp_current;
3964
89ff3147 3965 return arg;
3966}
3967
3968static int collect_call_args(struct parsed_op *po, int i,
3969 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
3970 int magic)
3971{
3a5101d7 3972 // arg group is for cases when pushes for
3973 // multiple funcs are going on
3974 struct parsed_op *po_tmp;
3975 int save_arg_vars_current = 0;
3976 int arg_grp = 0;
89ff3147 3977 int ret;
3978 int a;
3979
3a5101d7 3980 ret = collect_call_args_r(po, i, pp, regmask,
3981 &save_arg_vars_current, &arg_grp, 0, magic, 0, 0);
89ff3147 3982 if (ret < 0)
3983 return ret;
3984
3a5101d7 3985 if (arg_grp != 0) {
3986 // propagate arg_grp
3987 for (a = 0; a < pp->argc; a++) {
3988 if (pp->arg[a].reg != NULL)
3989 continue;
3990
3991 po_tmp = pp->arg[a].datap;
3992 while (po_tmp != NULL) {
3993 po_tmp->p_arggrp = arg_grp;
3994 if (po_tmp->p_argnext > 0)
3995 po_tmp = &ops[po_tmp->p_argnext];
3996 else
3997 po_tmp = NULL;
3998 }
3999 }
4000 }
4001 save_arg_vars[arg_grp] |= save_arg_vars_current;
4002
89ff3147 4003 if (pp->is_unresolved) {
4004 pp->argc += ret;
4005 pp->argc_stack += ret;
4006 for (a = 0; a < pp->argc; a++)
4007 if (pp->arg[a].type.name == NULL)
4008 pp->arg[a].type.name = strdup("int");
4009 }
4010
e56ab892 4011 return ret;
4012}
4013
89ff3147 4014static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
4015{
4016 int i;
4017
4018 for (i = 0; i < pp->argc; i++)
4019 if (pp->arg[i].reg == NULL)
4020 break;
4021
4022 if (pp->argc_stack)
4023 memmove(&pp->arg[i + 1], &pp->arg[i],
4024 sizeof(pp->arg[0]) * pp->argc_stack);
4025 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
4026 pp->arg[i].reg = strdup(reg);
4027 pp->arg[i].type.name = strdup("int");
4028 pp->argc++;
4029 pp->argc_reg++;
4030}
4031
04f8a628 4032static void output_std_flags(FILE *fout, struct parsed_op *po,
4033 int *pfomask, const char *dst_opr_text)
4034{
4035 if (*pfomask & (1 << PFO_Z)) {
4036 fprintf(fout, "\n cond_z = (%s%s == 0);",
4037 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
4038 *pfomask &= ~(1 << PFO_Z);
4039 }
4040 if (*pfomask & (1 << PFO_S)) {
4041 fprintf(fout, "\n cond_s = (%s%s < 0);",
4042 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
4043 *pfomask &= ~(1 << PFO_S);
4044 }
4045}
4046
c0de9015 4047enum {
4048 OPP_FORCE_NORETURN = (1 << 0),
4049 OPP_SIMPLE_ARGS = (1 << 1),
4050 OPP_ALIGN = (1 << 2),
4051};
4052
c0050df6 4053static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
c0de9015 4054 int flags)
c0050df6 4055{
c0de9015 4056 const char *cconv = "";
4057
c0050df6 4058 if (pp->is_fastcall)
c0de9015 4059 cconv = "__fastcall ";
c0050df6 4060 else if (pp->is_stdcall && pp->argc_reg == 0)
c0de9015 4061 cconv = "__stdcall ";
4062
4063 fprintf(fout, (flags & OPP_ALIGN) ? "%-16s" : "%s", cconv);
4064
4065 if (pp->is_noreturn || (flags & OPP_FORCE_NORETURN))
c0050df6 4066 fprintf(fout, "noreturn ");
4067}
4068
c0de9015 4069static void output_pp(FILE *fout, const struct parsed_proto *pp,
4070 int flags)
4071{
4072 int i;
4073
4074 fprintf(fout, (flags & OPP_ALIGN) ? "%-5s" : "%s ",
4075 pp->ret_type.name);
4076 if (pp->is_fptr)
4077 fprintf(fout, "(");
4078 output_pp_attrs(fout, pp, flags);
4079 if (pp->is_fptr)
4080 fprintf(fout, "*");
4081 fprintf(fout, "%s", pp->name);
4082 if (pp->is_fptr)
4083 fprintf(fout, ")");
4084
4085 fprintf(fout, "(");
4086 for (i = 0; i < pp->argc; i++) {
4087 if (i > 0)
4088 fprintf(fout, ", ");
4089 if (pp->arg[i].fptr != NULL && !(flags & OPP_SIMPLE_ARGS)) {
4090 // func pointer
4091 output_pp(fout, pp->arg[i].fptr, 0);
4092 }
4093 else if (pp->arg[i].type.is_retreg) {
4094 fprintf(fout, "u32 *r_%s", pp->arg[i].reg);
4095 }
4096 else {
4097 fprintf(fout, "%s", pp->arg[i].type.name);
4098 if (!pp->is_fptr)
4099 fprintf(fout, " a%d", i + 1);
4100 }
4101 }
4102 if (pp->is_vararg) {
4103 if (i > 0)
4104 fprintf(fout, ", ");
4105 fprintf(fout, "...");
4106 }
4107 fprintf(fout, ")");
4108}
4109
9af2d373 4110static int get_pp_arg_regmask(const struct parsed_proto *pp)
4111{
4112 int regmask = 0;
4113 int i, reg;
4114
4115 for (i = 0; i < pp->argc; i++) {
4116 if (pp->arg[i].reg != NULL) {
4117 reg = char_array_i(regs_r32,
4118 ARRAY_SIZE(regs_r32), pp->arg[i].reg);
4119 if (reg < 0)
4120 ferr(ops, "arg '%s' of func '%s' is not a reg?\n",
4121 pp->arg[i].reg, pp->name);
4122 regmask |= 1 << reg;
4123 }
4124 }
4125
4126 return regmask;
4127}
4128
3a5101d7 4129static char *saved_arg_name(char *buf, size_t buf_size, int grp, int num)
4130{
4131 char buf1[16];
4132
4133 buf1[0] = 0;
4134 if (grp > 0)
4135 snprintf(buf1, sizeof(buf1), "%d", grp);
4136 snprintf(buf, buf_size, "s%s_a%d", buf1, num);
4137
4138 return buf;
4139}
4140
9af2d373 4141static void gen_x_cleanup(int opcnt);
4142
91977a1c 4143static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
4144{
69a3cdfc 4145 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
850c9265 4146 struct parsed_opr *last_arith_dst = NULL;
3ebea2cf 4147 char buf1[256], buf2[256], buf3[256], cast[64];
ddaf8bd7 4148 struct parsed_proto *pp, *pp_tmp;
4c45fa73 4149 struct parsed_data *pd;
1f84f6b3 4150 unsigned int uval;
3a5101d7 4151 int save_arg_vars[MAX_ARG_GRP] = { 0, };
cb090db0 4152 int cond_vars = 0;
108e9fe3 4153 int need_tmp_var = 0;
2fe80fdb 4154 int need_tmp64 = 0;
91977a1c 4155 int had_decl = 0;
3ebea2cf 4156 int label_pending = 0;
25a330eb 4157 int regmask_save = 0; // regs saved/restored in this func
4158 int regmask_arg = 0; // regs carrying function args (fastcall, etc)
4159 int regmask_now; // temp
4160 int regmask_init = 0; // regs that need zero initialization
4161 int regmask_pp = 0; // regs used in complex push-pop graph
4162 int regmask = 0; // used regs
940e8e66 4163 int pfomask = 0;
64c59faf 4164 int found = 0;
d4e3b5db 4165 int depth = 0;
91977a1c 4166 int no_output;
4c45fa73 4167 int i, j, l;
91977a1c 4168 int arg;
91977a1c 4169 int reg;
4170 int ret;
4171
1bafb621 4172 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
a2c1d768 4173 g_stack_frame_used = 0;
91977a1c 4174
36595fd2 4175 g_func_pp = proto_parse(fhdr, funcn, 0);
bd96f656 4176 if (g_func_pp == NULL)
91977a1c 4177 ferr(ops, "proto_parse failed for '%s'\n", funcn);
4178
9af2d373 4179 regmask_arg = get_pp_arg_regmask(g_func_pp);
91977a1c 4180
4181 // pass1:
87bf6cec 4182 // - resolve all branches
66bdb2b0 4183 // - parse calls with labels
4184 resolve_branches_parse_calls(opcnt);
840257f6 4185
66bdb2b0 4186 // pass2:
4187 // - handle ebp/esp frame, remove ops related to it
4188 scan_prologue_epilogue(opcnt);
87bf6cec 4189
4190 // pass3:
a2c1d768 4191 // - remove dead labels
1bafb621 4192 for (i = 0; i < opcnt; i++)
4193 {
d7857c3a 4194 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
4195 free(g_labels[i]);
4196 g_labels[i] = NULL;
4197 }
66bdb2b0 4198 }
a2c1d768 4199
66bdb2b0 4200 // pass4:
4201 // - process trivial calls
4202 for (i = 0; i < opcnt; i++)
4203 {
69a3cdfc 4204 po = &ops[i];
5e49b270 4205 if (po->flags & (OPF_RMD|OPF_DONE))
91977a1c 4206 continue;
850c9265 4207
d4e3b5db 4208 if (po->op == OP_CALL)
26677139 4209 {
4210 pp = process_call_early(i, opcnt, &j);
4211 if (pp != NULL) {
4212 if (!(po->flags & OPF_ATAIL))
4213 // since we know the args, try to collect them
4214 if (collect_call_args_early(po, i, pp, &regmask) != 0)
4215 pp = NULL;
4216 }
4217
4218 if (pp != NULL) {
4219 if (j >= 0) {
4220 // commit esp adjust
5e49b270 4221 if (ops[j].op != OP_POP)
4222 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
bfacdc83 4223 else {
4224 for (l = 0; l < pp->argc_stack; l++)
4225 ops[j + l].flags |= OPF_DONE | OPF_RMD;
4226 }
26677139 4227 }
4228
4229 if (strstr(pp->ret_type.name, "int64"))
4230 need_tmp64 = 1;
4231
4232 po->flags |= OPF_DONE;
4233 }
4234 }
4235 }
4236
66bdb2b0 4237 // pass5:
26677139 4238 // - process calls
ee2361b9 4239 // - handle push <const>/pop pairs
26677139 4240 for (i = 0; i < opcnt; i++)
4241 {
4242 po = &ops[i];
5e49b270 4243 if (po->flags & (OPF_RMD|OPF_DONE))
26677139 4244 continue;
4245
4246 if (po->op == OP_CALL && !(po->flags & OPF_DONE))
69a3cdfc 4247 {
9af2d373 4248 pp = process_call(i, opcnt);
91977a1c 4249
2fe80fdb 4250 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
89ff3147 4251 // since we know the args, collect them
3a5101d7 4252 collect_call_args(po, i, pp, &regmask, save_arg_vars,
89ff3147 4253 i + opcnt * 2);
4254 }
2b43685d 4255
4256 if (strstr(pp->ret_type.name, "int64"))
2fe80fdb 4257 need_tmp64 = 1;
91977a1c 4258 }
ee2361b9 4259 else if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
4260 && !(po->flags & OPF_RSAVE) && po->operand[0].type == OPT_CONST)
25a330eb 4261 scan_for_pop_const(i, opcnt, &regmask_pp);
d4e3b5db 4262 }
4263
66bdb2b0 4264 // pass6:
d4e3b5db 4265 // - find POPs for PUSHes, rm both
591721d7 4266 // - scan for STD/CLD, propagate DF
d4e3b5db 4267 // - scan for all used registers
4268 // - find flag set ops for their users
89ff3147 4269 // - do unreselved calls
1bafb621 4270 // - declare indirect functions
26677139 4271 for (i = 0; i < opcnt; i++)
4272 {
d4e3b5db 4273 po = &ops[i];
5e49b270 4274 if (po->flags & (OPF_RMD|OPF_DONE))
d4e3b5db 4275 continue;
4276
7ae48d73 4277 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
4278 reg = po->operand[0].reg;
4279 if (!(regmask & (1 << reg)))
4280 // not a reg save after all, rerun scan_for_pop
4281 po->flags &= ~OPF_RSAVE;
4282 else
4283 regmask_save |= 1 << reg;
4284 }
4285
9af2d373 4286 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)
1f84f6b3 4287 && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
d4e3b5db 4288 {
5c024ef7 4289 if (po->operand[0].type == OPT_REG)
4290 {
4291 reg = po->operand[0].reg;
4292 if (reg < 0)
4293 ferr(po, "reg not set for push?\n");
4294
4295 depth = 0;
4296 ret = scan_for_pop(i + 1, opcnt,
4297 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
4298 if (ret == 1) {
4299 if (depth > 1)
4300 ferr(po, "too much depth: %d\n", depth);
4301
4302 po->flags |= OPF_RMD;
4303 scan_for_pop(i + 1, opcnt, po->operand[0].name,
4304 i + opcnt * 4, 0, &depth, 1);
4305 continue;
4306 }
4307 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
4308 if (ret == 0) {
4309 arg = OPF_RMD;
4310 if (regmask & (1 << reg)) {
4311 if (regmask_save & (1 << reg))
4312 ferr(po, "%s already saved?\n", po->operand[0].name);
4313 arg = OPF_RSAVE;
4314 }
4315 po->flags |= arg;
4316 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
4317 continue;
4318 }
d4e3b5db 4319 }
d4e3b5db 4320 }
4321
591721d7 4322 if (po->op == OP_STD) {
5e49b270 4323 po->flags |= OPF_DF | OPF_RMD | OPF_DONE;
591721d7 4324 scan_propagate_df(i + 1, opcnt);
4325 }
4326
a3684be1 4327 regmask_now = po->regmask_src | po->regmask_dst;
4328 if (regmask_now & (1 << xBP)) {
4329 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
4330 if (po->regmask_dst & (1 << xBP))
4331 // compiler decided to drop bp frame and use ebp as scratch
037f4971 4332 scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
a3684be1 4333 else
4334 regmask_now &= ~(1 << xBP);
4335 }
4336 }
4337
4338 regmask |= regmask_now;
d4e3b5db 4339
4340 if (po->flags & OPF_CC)
4341 {
2b43685d 4342 int setters[16], cnt = 0, branched = 0;
4343
04f8a628 4344 ret = scan_for_flag_set(i, i + opcnt * 6,
4345 &branched, setters, &cnt);
2b43685d 4346 if (ret < 0 || cnt <= 0)
4347 ferr(po, "unable to trace flag setter(s)\n");
4348 if (cnt > ARRAY_SIZE(setters))
4349 ferr(po, "too many flag setters\n");
d4e3b5db 4350
2b43685d 4351 for (j = 0; j < cnt; j++)
4352 {
4353 tmp_op = &ops[setters[j]]; // flag setter
4354 pfomask = 0;
4355
4356 // to get nicer code, we try to delay test and cmp;
4357 // if we can't because of operand modification, or if we
591721d7 4358 // have arith op, or branch, make it calculate flags explicitly
4359 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
4360 {
89ff3147 4361 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
092f64e1 4362 pfomask = 1 << po->pfo;
2b43685d 4363 }
4741fdfe 4364 else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
092f64e1 4365 pfomask = 1 << po->pfo;
591721d7 4366 }
2b43685d 4367 else {
04f8a628 4368 // see if we'll be able to handle based on op result
4369 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
092f64e1 4370 && po->pfo != PFO_Z && po->pfo != PFO_S
4371 && po->pfo != PFO_P)
04f8a628 4372 || branched
2b43685d 4373 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
092f64e1 4374 {
4375 pfomask = 1 << po->pfo;
4376 }
2fe80fdb 4377
c8dbc5be 4378 if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
4379 propagate_lmod(tmp_op, &tmp_op->operand[0],
4380 &tmp_op->operand[1]);
4381 if (tmp_op->operand[0].lmod == OPLM_DWORD)
4382 need_tmp64 = 1;
4383 }
2b43685d 4384 }
4385 if (pfomask) {
4386 tmp_op->pfomask |= pfomask;
cb090db0 4387 cond_vars |= pfomask;
2b43685d 4388 }
04f8a628 4389 // note: may overwrite, currently not a problem
4390 po->datap = tmp_op;
d4e3b5db 4391 }
4392
cb090db0 4393 if (po->op == OP_RCL || po->op == OP_RCR
4394 || po->op == OP_ADC || po->op == OP_SBB)
4395 cond_vars |= 1 << PFO_C;
d4e3b5db 4396 }
092f64e1 4397
4398 if (po->op == OP_CMPS || po->op == OP_SCAS) {
cb090db0 4399 cond_vars |= 1 << PFO_Z;
591721d7 4400 }
87bf6cec 4401 else if (po->op == OP_MUL
4402 || (po->op == OP_IMUL && po->operand_cnt == 1))
4403 {
c8dbc5be 4404 if (po->operand[0].lmod == OPLM_DWORD)
4405 need_tmp64 = 1;
87bf6cec 4406 }
89ff3147 4407 else if (po->op == OP_CALL) {
26677139 4408 // note: resolved non-reg calls are OPF_DONE already
092f64e1 4409 pp = po->pp;
89ff3147 4410 if (pp == NULL)
4411 ferr(po, "NULL pp\n");
4412
4413 if (pp->is_unresolved) {
ddaf8bd7 4414 int regmask_stack = 0;
3a5101d7 4415 collect_call_args(po, i, pp, &regmask, save_arg_vars,
89ff3147 4416 i + opcnt * 2);
4417
b74c31e3 4418 // this is pretty rough guess:
4419 // see ecx and edx were pushed (and not their saved versions)
4420 for (arg = 0; arg < pp->argc; arg++) {
4421 if (pp->arg[arg].reg != NULL)
4422 continue;
4423
4424 tmp_op = pp->arg[arg].datap;
4425 if (tmp_op == NULL)
4426 ferr(po, "parsed_op missing for arg%d\n", arg);
5f70a34f 4427 if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
b74c31e3 4428 regmask_stack |= 1 << tmp_op->operand[0].reg;
4429 }
4430
ddaf8bd7 4431 if (!((regmask_stack & (1 << xCX))
4432 && (regmask_stack & (1 << xDX))))
89ff3147 4433 {
4434 if (pp->argc_stack != 0
c0050df6 4435 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
89ff3147 4436 {
4437 pp_insert_reg_arg(pp, "ecx");
c0050df6 4438 pp->is_fastcall = 1;
ddaf8bd7 4439 regmask_init |= 1 << xCX;
89ff3147 4440 regmask |= 1 << xCX;
4441 }
4442 if (pp->argc_stack != 0
4443 || ((regmask | regmask_arg) & (1 << xDX)))
4444 {
4445 pp_insert_reg_arg(pp, "edx");
ddaf8bd7 4446 regmask_init |= 1 << xDX;
89ff3147 4447 regmask |= 1 << xDX;
4448 }
4449 }
c0050df6 4450
4451 // note: __cdecl doesn't fall into is_unresolved category
4452 if (pp->argc_stack > 0)
4453 pp->is_stdcall = 1;
ddaf8bd7 4454 }
4455
4456 for (arg = 0; arg < pp->argc; arg++) {
4457 if (pp->arg[arg].reg != NULL) {
4458 reg = char_array_i(regs_r32,
4459 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
4460 if (reg < 0)
4461 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
4462 if (!(regmask & (1 << reg))) {
4463 regmask_init |= 1 << reg;
4464 regmask |= 1 << reg;
4465 }
4466 }
89ff3147 4467 }
1bafb621 4468 }
27ebfaed 4469 else if (po->op == OP_MOV && po->operand[0].pp != NULL
4470 && po->operand[1].pp != NULL)
4471 {
4472 // <var> = offset <something>
4473 if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
4474 && !IS_START(po->operand[1].name, "off_"))
4475 {
4476 if (!po->operand[0].pp->is_fptr)
4477 ferr(po, "%s not declared as fptr when it should be\n",
4478 po->operand[0].name);
4479 if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
4480 pp_print(buf1, sizeof(buf1), po->operand[0].pp);
4481 pp_print(buf2, sizeof(buf2), po->operand[1].pp);
4482 fnote(po, "var: %s\n", buf1);
4483 fnote(po, "func: %s\n", buf2);
4484 ferr(po, "^ mismatch\n");
4485 }
4486 }
4487 }
75ad0378 4488 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
4489 regmask |= 1 << xAX;
cb090db0 4490 else if (po->op == OP_DIV || po->op == OP_IDIV) {
4491 // 32bit division is common, look for it
4492 if (po->op == OP_DIV)
4493 ret = scan_for_reg_clear(i, xDX);
4494 else
4495 ret = scan_for_cdq_edx(i);
4496 if (ret >= 0)
4497 po->flags |= OPF_32BIT;
4498 else
4499 need_tmp64 = 1;
4500 }
037f4971 4501 else if (po->op == OP_CLD)
5e49b270 4502 po->flags |= OPF_RMD | OPF_DONE;
cb090db0 4503
4504 if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
4505 need_tmp_var = 1;
4506 }
91977a1c 4507 }
4508
66bdb2b0 4509 // pass7:
da87ae38 4510 // - confirm regmask_save, it might have been reduced
4511 if (regmask_save != 0)
4512 {
4513 regmask_save = 0;
4514 for (i = 0; i < opcnt; i++) {
4515 po = &ops[i];
4516 if (po->flags & OPF_RMD)
4517 continue;
4518
4519 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
4520 regmask_save |= 1 << po->operand[0].reg;
4521 }
4522 }
4523
60fe410c 4524 // output starts here
4525
4526 // define userstack size
4527 if (g_func_pp->is_userstack) {
4528 fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
4529 fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
4530 fprintf(fout, "#endif\n");
4531 }
4532
4533 // the function itself
c0de9015 4534 ferr_assert(ops, !g_func_pp->is_fptr);
4535 output_pp(fout, g_func_pp,
4536 (g_ida_func_attr & IDAFA_NORETURN) ? OPP_FORCE_NORETURN : 0);
4537 fprintf(fout, "\n{\n");
60fe410c 4538
4539 // declare indirect functions
4540 for (i = 0; i < opcnt; i++) {
4541 po = &ops[i];
4542 if (po->flags & OPF_RMD)
4543 continue;
4544
4545 if (po->op == OP_CALL) {
4546 pp = po->pp;
4547 if (pp == NULL)
4548 ferr(po, "NULL pp\n");
4549
4550 if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
4551 if (pp->name[0] != 0) {
4552 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
4553 memcpy(pp->name, "i_", 2);
4554
4555 // might be declared already
4556 found = 0;
4557 for (j = 0; j < i; j++) {
4558 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
4559 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
4560 found = 1;
4561 break;
4562 }
4563 }
4564 }
4565 if (found)
4566 continue;
4567 }
4568 else
4569 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
4570
c0de9015 4571 fprintf(fout, " ");
4572 output_pp(fout, pp, OPP_SIMPLE_ARGS);
4573 fprintf(fout, ";\n");
60fe410c 4574 }
4575 }
4576 }
da87ae38 4577
4c45fa73 4578 // output LUTs/jumptables
4579 for (i = 0; i < g_func_pd_cnt; i++) {
4580 pd = &g_func_pd[i];
4581 fprintf(fout, " static const ");
4582 if (pd->type == OPT_OFFSET) {
4583 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
4584
4585 for (j = 0; j < pd->count; j++) {
4586 if (j > 0)
4587 fprintf(fout, ", ");
4588 fprintf(fout, "&&%s", pd->d[j].u.label);
4589 }
4590 }
4591 else {
4592 fprintf(fout, "%s %s[] =\n { ",
4593 lmod_type_u(ops, pd->lmod), pd->label);
4594
4595 for (j = 0; j < pd->count; j++) {
4596 if (j > 0)
4597 fprintf(fout, ", ");
4598 fprintf(fout, "%u", pd->d[j].u.val);
4599 }
4600 }
4601 fprintf(fout, " };\n");
1f84f6b3 4602 had_decl = 1;
4c45fa73 4603 }
4604
4f12f671 4605 // declare stack frame, va_arg
1f84f6b3 4606 if (g_stack_fsz) {
850c9265 4607 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
1bafb621 4608 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
1f84f6b3 4609 had_decl = 1;
4610 }
4611
4612 if (g_func_pp->is_userstack) {
60fe410c 4613 fprintf(fout, " u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
4614 fprintf(fout, " u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
1f84f6b3 4615 had_decl = 1;
4616 }
850c9265 4617
1f84f6b3 4618 if (g_func_pp->is_vararg) {
4f12f671 4619 fprintf(fout, " va_list ap;\n");
1f84f6b3 4620 had_decl = 1;
4621 }
4f12f671 4622
940e8e66 4623 // declare arg-registers
bd96f656 4624 for (i = 0; i < g_func_pp->argc; i++) {
4625 if (g_func_pp->arg[i].reg != NULL) {
91977a1c 4626 reg = char_array_i(regs_r32,
bd96f656 4627 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
75ad0378 4628 if (regmask & (1 << reg)) {
1f84f6b3 4629 if (g_func_pp->arg[i].type.is_retreg)
4630 fprintf(fout, " u32 %s = *r_%s;\n",
4631 g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
4632 else
4633 fprintf(fout, " u32 %s = (u32)a%d;\n",
4634 g_func_pp->arg[i].reg, i + 1);
75ad0378 4635 }
1f84f6b3 4636 else {
4637 if (g_func_pp->arg[i].type.is_retreg)
4638 ferr(ops, "retreg '%s' is unused?\n",
4639 g_func_pp->arg[i].reg);
75ad0378 4640 fprintf(fout, " // %s = a%d; // unused\n",
4641 g_func_pp->arg[i].reg, i + 1);
1f84f6b3 4642 }
91977a1c 4643 had_decl = 1;
4644 }
4645 }
4646
25a330eb 4647 // declare normal registers
75ad0378 4648 regmask_now = regmask & ~regmask_arg;
4649 regmask_now &= ~(1 << xSP);
90307a99 4650 if (regmask_now & 0x00ff) {
91977a1c 4651 for (reg = 0; reg < 8; reg++) {
75ad0378 4652 if (regmask_now & (1 << reg)) {
ddaf8bd7 4653 fprintf(fout, " u32 %s", regs_r32[reg]);
4654 if (regmask_init & (1 << reg))
4655 fprintf(fout, " = 0");
4656 fprintf(fout, ";\n");
91977a1c 4657 had_decl = 1;
4658 }
4659 }
4660 }
90307a99 4661 if (regmask_now & 0xff00) {
4662 for (reg = 8; reg < 16; reg++) {
4663 if (regmask_now & (1 << reg)) {
4664 fprintf(fout, " mmxr %s", regs_r32[reg]);
4665 if (regmask_init & (1 << reg))
4666 fprintf(fout, " = { 0, }");
4667 fprintf(fout, ";\n");
4668 had_decl = 1;
4669 }
4670 }
4671 }
91977a1c 4672
d4e3b5db 4673 if (regmask_save) {
4674 for (reg = 0; reg < 8; reg++) {
4675 if (regmask_save & (1 << reg)) {
4676 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
4677 had_decl = 1;
4678 }
4679 }
4680 }
4681
3a5101d7 4682 for (i = 0; i < ARRAY_SIZE(save_arg_vars); i++) {
4683 if (save_arg_vars[i] == 0)
4684 continue;
69a3cdfc 4685 for (reg = 0; reg < 32; reg++) {
3a5101d7 4686 if (save_arg_vars[i] & (1 << reg)) {
4687 fprintf(fout, " u32 %s;\n",
4688 saved_arg_name(buf1, sizeof(buf1), i, reg + 1));
69a3cdfc 4689 had_decl = 1;
4690 }
4691 }
4692 }
4693
25a330eb 4694 // declare push-pop temporaries
4695 if (regmask_pp) {
4696 for (reg = 0; reg < 8; reg++) {
4697 if (regmask_pp & (1 << reg)) {
4698 fprintf(fout, " u32 pp_%s;\n", regs_r32[reg]);
4699 had_decl = 1;
4700 }
4701 }
4702 }
4703
cb090db0 4704 if (cond_vars) {
69a3cdfc 4705 for (i = 0; i < 8; i++) {
cb090db0 4706 if (cond_vars & (1 << i)) {
69a3cdfc 4707 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
4708 had_decl = 1;
4709 }
4710 }
4711 }
4712
108e9fe3 4713 if (need_tmp_var) {
4714 fprintf(fout, " u32 tmp;\n");
4715 had_decl = 1;
4716 }
4717
2fe80fdb 4718 if (need_tmp64) {
4719 fprintf(fout, " u64 tmp64;\n");
87bf6cec 4720 had_decl = 1;
4721 }
4722
91977a1c 4723 if (had_decl)
4724 fprintf(fout, "\n");
4725
bd96f656 4726 if (g_func_pp->is_vararg) {
4727 if (g_func_pp->argc_stack == 0)
4f12f671 4728 ferr(ops, "vararg func without stack args?\n");
bd96f656 4729 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
4f12f671 4730 }
4731
91977a1c 4732 // output ops
69a3cdfc 4733 for (i = 0; i < opcnt; i++)
4734 {
d7857c3a 4735 if (g_labels[i] != NULL) {
91977a1c 4736 fprintf(fout, "\n%s:\n", g_labels[i]);
3ebea2cf 4737 label_pending = 1;
2b43685d 4738
4739 delayed_flag_op = NULL;
4740 last_arith_dst = NULL;
3ebea2cf 4741 }
91977a1c 4742
69a3cdfc 4743 po = &ops[i];
4744 if (po->flags & OPF_RMD)
91977a1c 4745 continue;
4746
4747 no_output = 0;
4748
91977a1c 4749 #define assert_operand_cnt(n_) \
850c9265 4750 if (po->operand_cnt != n_) \
4751 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
4752
69a3cdfc 4753 // conditional/flag using op?
4754 if (po->flags & OPF_CC)
850c9265 4755 {
940e8e66 4756 int is_delayed = 0;
69a3cdfc 4757
04f8a628 4758 tmp_op = po->datap;
850c9265 4759
69a3cdfc 4760 // we go through all this trouble to avoid using parsed_flag_op,
4761 // which makes generated code much nicer
4762 if (delayed_flag_op != NULL)
850c9265 4763 {
092f64e1 4764 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
4765 po->pfo, po->pfo_inv);
940e8e66 4766 is_delayed = 1;
91977a1c 4767 }
850c9265 4768 else if (last_arith_dst != NULL
092f64e1 4769 && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
04f8a628 4770 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
4771 ))
850c9265 4772 {
3ebea2cf 4773 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
092f64e1 4774 out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
850c9265 4775 last_arith_dst->lmod, buf3);
940e8e66 4776 is_delayed = 1;
850c9265 4777 }
04f8a628 4778 else if (tmp_op != NULL) {
7ba45c34 4779 // use preprocessed flag calc results
092f64e1 4780 if (!(tmp_op->pfomask & (1 << po->pfo)))
4781 ferr(po, "not prepared for pfo %d\n", po->pfo);
69a3cdfc 4782
092f64e1 4783 // note: pfo_inv was not yet applied
69a3cdfc 4784 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
092f64e1 4785 po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
69a3cdfc 4786 }
4787 else {
4788 ferr(po, "all methods of finding comparison failed\n");
4789 }
850c9265 4790
69a3cdfc 4791 if (po->flags & OPF_JMP) {
092f64e1 4792 fprintf(fout, " if %s", buf1);
850c9265 4793 }
cb090db0 4794 else if (po->op == OP_RCL || po->op == OP_RCR
4795 || po->op == OP_ADC || po->op == OP_SBB)
4796 {
940e8e66 4797 if (is_delayed)
4798 fprintf(fout, " cond_%s = %s;\n",
092f64e1 4799 parsed_flag_op_names[po->pfo], buf1);
850c9265 4800 }
5101a5f9 4801 else if (po->flags & OPF_DATA) { // SETcc
850c9265 4802 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
4803 fprintf(fout, " %s = %s;", buf2, buf1);
91977a1c 4804 }
69a3cdfc 4805 else {
4806 ferr(po, "unhandled conditional op\n");
4807 }
91977a1c 4808 }
4809
940e8e66 4810 pfomask = po->pfomask;
4811
4741fdfe 4812 if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
1f84f6b3 4813 struct parsed_opr opr = {0,};
4814 opr.type = OPT_REG;
4815 opr.reg = xCX;
4816 opr.lmod = OPLM_DWORD;
4817 ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
4818
4819 if (ret != 1 || uval == 0) {
4820 // we need initial flags for ecx=0 case..
4821 if (i > 0 && ops[i - 1].op == OP_XOR
4822 && IS(ops[i - 1].operand[0].name,
4823 ops[i - 1].operand[1].name))
4824 {
4825 fprintf(fout, " cond_z = ");
4826 if (pfomask & (1 << PFO_C))
4827 fprintf(fout, "cond_c = ");
4828 fprintf(fout, "0;\n");
4829 }
4830 else if (last_arith_dst != NULL) {
4831 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
4832 out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
4833 last_arith_dst->lmod, buf3);
4834 fprintf(fout, " cond_z = %s;\n", buf1);
4835 }
4836 else
4837 ferr(po, "missing initial ZF\n");
4741fdfe 4838 }
4741fdfe 4839 }
4840
850c9265 4841 switch (po->op)
91977a1c 4842 {
4843 case OP_MOV:
4844 assert_operand_cnt(2);
850c9265 4845 propagate_lmod(po, &po->operand[0], &po->operand[1]);
de50b98b 4846 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
c7ed83dd 4847 default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
de50b98b 4848 fprintf(fout, " %s = %s;", buf1,
3ebea2cf 4849 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
c7ed83dd 4850 buf3, 0));
850c9265 4851 break;
4852
4853 case OP_LEA:
4854 assert_operand_cnt(2);
87bf6cec 4855 po->operand[1].lmod = OPLM_DWORD; // always
850c9265 4856 fprintf(fout, " %s = %s;",
4857 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3ebea2cf 4858 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4859 NULL, 1));
850c9265 4860 break;
4861
4862 case OP_MOVZX:
4863 assert_operand_cnt(2);
91977a1c 4864 fprintf(fout, " %s = %s;",
850c9265 4865 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3ebea2cf 4866 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
850c9265 4867 break;
4868
4869 case OP_MOVSX:
4870 assert_operand_cnt(2);
4871 switch (po->operand[1].lmod) {
4872 case OPLM_BYTE:
4873 strcpy(buf3, "(s8)");
4874 break;
4875 case OPLM_WORD:
4876 strcpy(buf3, "(s16)");
4877 break;
4878 default:
4879 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
4880 }
a2c1d768 4881 fprintf(fout, " %s = %s;",
850c9265 4882 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
a2c1d768 4883 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4884 buf3, 0));
850c9265 4885 break;
4886
108e9fe3 4887 case OP_XCHG:
4888 assert_operand_cnt(2);
4889 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4890 fprintf(fout, " tmp = %s;",
4891 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
4892 fprintf(fout, " %s = %s;",
4893 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
c7ed83dd 4894 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4895 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4896 fprintf(fout, " %s = %stmp;",
4897 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
4898 default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
108e9fe3 4899 snprintf(g_comment, sizeof(g_comment), "xchg");
4900 break;
4901
850c9265 4902 case OP_NOT:
4903 assert_operand_cnt(1);
4904 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4905 fprintf(fout, " %s = ~%s;", buf1, buf1);
4906 break;
4907
04abc5d6 4908 case OP_XLAT:
4909 assert_operand_cnt(2);
4910 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4911 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4912 fprintf(fout, " %s = *(u8 *)(%s + %s);", buf1, buf2, buf1);
4913 strcpy(g_comment, "xlat");
4914 break;
4915
5101a5f9 4916 case OP_CDQ:
4917 assert_operand_cnt(2);
4918 fprintf(fout, " %s = (s32)%s >> 31;",
4919 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3ebea2cf 4920 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
5101a5f9 4921 strcpy(g_comment, "cdq");
4922 break;
4923
092f64e1 4924 case OP_LODS:
4925 assert_operand_cnt(3);
4926 if (po->flags & OPF_REP) {
4927 // hmh..
4928 ferr(po, "TODO\n");
4929 }
4930 else {
05381e4a 4931 fprintf(fout, " eax = %sesi; esi %c= %d;",
092f64e1 4932 lmod_cast_u_ptr(po, po->operand[0].lmod),
4933 (po->flags & OPF_DF) ? '-' : '+',
4934 lmod_bytes(po, po->operand[0].lmod));
4935 strcpy(g_comment, "lods");
4936 }
4937 break;
4938
33c35af6 4939 case OP_STOS:
33c35af6 4940 assert_operand_cnt(3);
4941 if (po->flags & OPF_REP) {
591721d7 4942 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
4943 (po->flags & OPF_DF) ? '-' : '+',
33c35af6 4944 lmod_bytes(po, po->operand[0].lmod));
d4e3b5db 4945 fprintf(fout, " %sedi = eax;",
4946 lmod_cast_u_ptr(po, po->operand[0].lmod));
33c35af6 4947 strcpy(g_comment, "rep stos");
4948 }
4949 else {
092f64e1 4950 fprintf(fout, " %sedi = eax; edi %c= %d;",
d4e3b5db 4951 lmod_cast_u_ptr(po, po->operand[0].lmod),
591721d7 4952 (po->flags & OPF_DF) ? '-' : '+',
33c35af6 4953 lmod_bytes(po, po->operand[0].lmod));
4954 strcpy(g_comment, "stos");
4955 }
4956 break;
4957
d4e3b5db 4958 case OP_MOVS:
d4e3b5db 4959 assert_operand_cnt(3);
4960 j = lmod_bytes(po, po->operand[0].lmod);
4961 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
591721d7 4962 l = (po->flags & OPF_DF) ? '-' : '+';
d4e3b5db 4963 if (po->flags & OPF_REP) {
4964 fprintf(fout,
591721d7 4965 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
4966 l, j, l, j);
d4e3b5db 4967 fprintf(fout,
4968 " %sedi = %sesi;", buf1, buf1);
4969 strcpy(g_comment, "rep movs");
4970 }
4971 else {
092f64e1 4972 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
591721d7 4973 buf1, buf1, l, j, l, j);
d4e3b5db 4974 strcpy(g_comment, "movs");
4975 }
4976 break;
4977
7ba45c34 4978 case OP_CMPS:
7ba45c34 4979 // repe ~ repeat while ZF=1
4980 assert_operand_cnt(3);
4981 j = lmod_bytes(po, po->operand[0].lmod);
4982 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
591721d7 4983 l = (po->flags & OPF_DF) ? '-' : '+';
7ba45c34 4984 if (po->flags & OPF_REP) {
4985 fprintf(fout,
1f84f6b3 4986 " for (; ecx != 0; ecx--) {\n");
4741fdfe 4987 if (pfomask & (1 << PFO_C)) {
4988 // ugh..
4989 fprintf(fout,
05381e4a 4990 " cond_c = %sesi < %sedi;\n", buf1, buf1);
4741fdfe 4991 pfomask &= ~(1 << PFO_C);
4992 }
7ba45c34 4993 fprintf(fout,
05381e4a 4994 " cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
1f84f6b3 4995 buf1, buf1, l, j, l, j);
4996 fprintf(fout,
4997 " if (cond_z %s 0) break;\n",
4998 (po->flags & OPF_REPZ) ? "==" : "!=");
7ba45c34 4999 fprintf(fout,
4741fdfe 5000 " }");
7ba45c34 5001 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
5002 (po->flags & OPF_REPZ) ? "e" : "ne");
5003 }
5004 else {
5005 fprintf(fout,
05381e4a 5006 " cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
591721d7 5007 buf1, buf1, l, j, l, j);
7ba45c34 5008 strcpy(g_comment, "cmps");
5009 }
5010 pfomask &= ~(1 << PFO_Z);
5011 last_arith_dst = NULL;
5012 delayed_flag_op = NULL;
5013 break;
5014
591721d7 5015 case OP_SCAS:
5016 // only does ZF (for now)
5017 // repe ~ repeat while ZF=1
5018 assert_operand_cnt(3);
5019 j = lmod_bytes(po, po->operand[0].lmod);
5020 l = (po->flags & OPF_DF) ? '-' : '+';
5021 if (po->flags & OPF_REP) {
5022 fprintf(fout,
1f84f6b3 5023 " for (; ecx != 0; ecx--) {\n");
591721d7 5024 fprintf(fout,
1f84f6b3 5025 " cond_z = (%seax == %sedi); edi %c= %d;\n",
591721d7 5026 lmod_cast_u(po, po->operand[0].lmod),
1f84f6b3 5027 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
5028 fprintf(fout,
5029 " if (cond_z %s 0) break;\n",
591721d7 5030 (po->flags & OPF_REPZ) ? "==" : "!=");
5031 fprintf(fout,
1f84f6b3 5032 " }");
591721d7 5033 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
5034 (po->flags & OPF_REPZ) ? "e" : "ne");
5035 }
5036 else {
05381e4a 5037 fprintf(fout, " cond_z = (%seax == %sedi); edi %c= %d;",
591721d7 5038 lmod_cast_u(po, po->operand[0].lmod),
5039 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
5040 strcpy(g_comment, "scas");
5041 }
5042 pfomask &= ~(1 << PFO_Z);
5043 last_arith_dst = NULL;
5044 delayed_flag_op = NULL;
5045 break;
5046
850c9265 5047 // arithmetic w/flags
850c9265 5048 case OP_AND:
2b70f6d3 5049 if (po->operand[1].type == OPT_CONST && !po->operand[1].val)
5050 goto dualop_arith_const;
5051 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5052 goto dualop_arith;
5053
850c9265 5054 case OP_OR:
5101a5f9 5055 propagate_lmod(po, &po->operand[0], &po->operand[1]);
2b70f6d3 5056 if (po->operand[1].type == OPT_CONST) {
5057 j = lmod_bytes(po, po->operand[0].lmod);
5058 if (((1ull << j * 8) - 1) == po->operand[1].val)
5059 goto dualop_arith_const;
5060 }
5061 goto dualop_arith;
5062
850c9265 5063 dualop_arith:
5064 assert_operand_cnt(2);
850c9265 5065 fprintf(fout, " %s %s= %s;",
5066 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5067 op_to_c(po),
3ebea2cf 5068 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
04f8a628 5069 output_std_flags(fout, po, &pfomask, buf1);
5070 last_arith_dst = &po->operand[0];
5071 delayed_flag_op = NULL;
5072 break;
5073
2b70f6d3 5074 dualop_arith_const:
5075 // and 0, or ~0 used instead mov
5076 assert_operand_cnt(2);
5077 fprintf(fout, " %s = %s;",
5078 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5079 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
5080 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5081 output_std_flags(fout, po, &pfomask, buf1);
5082 last_arith_dst = &po->operand[0];
5083 delayed_flag_op = NULL;
5084 break;
5085
04f8a628 5086 case OP_SHL:
5087 case OP_SHR:
5088 assert_operand_cnt(2);
5089 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5090 if (pfomask & (1 << PFO_C)) {
5091 if (po->operand[1].type == OPT_CONST) {
5092 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5093 j = po->operand[1].val;
5094 j %= l;
5095 if (j != 0) {
5096 if (po->op == OP_SHL)
5097 j = l - j;
5098 else
5099 j -= 1;
cb090db0 5100 fprintf(fout, " cond_c = (%s >> %d) & 1;\n",
5101 buf1, j);
04f8a628 5102 }
5103 else
5104 ferr(po, "zero shift?\n");
5105 }
5106 else
5107 ferr(po, "TODO\n");
5108 pfomask &= ~(1 << PFO_C);
840257f6 5109 }
04abc5d6 5110 fprintf(fout, " %s %s= %s", buf1, op_to_c(po),
04f8a628 5111 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
04abc5d6 5112 if (po->operand[1].type != OPT_CONST)
5113 fprintf(fout, " & 0x1f");
5114 fprintf(fout, ";");
04f8a628 5115 output_std_flags(fout, po, &pfomask, buf1);
850c9265 5116 last_arith_dst = &po->operand[0];
69a3cdfc 5117 delayed_flag_op = NULL;
850c9265 5118 break;
5119
d4e3b5db 5120 case OP_SAR:
5121 assert_operand_cnt(2);
5122 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5123 fprintf(fout, " %s = %s%s >> %s;", buf1,
5124 lmod_cast_s(po, po->operand[0].lmod), buf1,
3ebea2cf 5125 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
04f8a628 5126 output_std_flags(fout, po, &pfomask, buf1);
d4e3b5db 5127 last_arith_dst = &po->operand[0];
5128 delayed_flag_op = NULL;
5129 break;
5130
04abc5d6 5131 case OP_SHLD:
3b2f4044 5132 case OP_SHRD:
5133 assert_operand_cnt(3);
5134 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5135 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5136 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5137 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5138 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[2]);
04abc5d6 5139 if (po->operand[2].type != OPT_CONST)
5140 ferr(po, "TODO: masking\n");
5141 if (po->op == OP_SHLD) {
5142 fprintf(fout, " %s <<= %s; %s |= %s >> (%d - %s);",
5143 buf1, buf3, buf1, buf2, l, buf3);
5144 strcpy(g_comment, "shld");
5145 }
5146 else {
5147 fprintf(fout, " %s >>= %s; %s |= %s << (%d - %s);",
5148 buf1, buf3, buf1, buf2, l, buf3);
5149 strcpy(g_comment, "shrd");
5150 }
3b2f4044 5151 output_std_flags(fout, po, &pfomask, buf1);
5152 last_arith_dst = &po->operand[0];
5153 delayed_flag_op = NULL;
5154 break;
5155
d4e3b5db 5156 case OP_ROL:
5157 case OP_ROR:
5158 assert_operand_cnt(2);
5159 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5160 if (po->operand[1].type == OPT_CONST) {
5161 j = po->operand[1].val;
5162 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
5163 fprintf(fout, po->op == OP_ROL ?
5164 " %s = (%s << %d) | (%s >> %d);" :
5165 " %s = (%s >> %d) | (%s << %d);",
5166 buf1, buf1, j, buf1,
5167 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
5168 }
5169 else
5170 ferr(po, "TODO\n");
04f8a628 5171 output_std_flags(fout, po, &pfomask, buf1);
d4e3b5db 5172 last_arith_dst = &po->operand[0];
5173 delayed_flag_op = NULL;
5174 break;
5175
cb090db0 5176 case OP_RCL:
5177 case OP_RCR:
5178 assert_operand_cnt(2);
5179 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
5180 l = lmod_bytes(po, po->operand[0].lmod) * 8;
5181 if (po->operand[1].type == OPT_CONST) {
5182 j = po->operand[1].val % l;
5183 if (j == 0)
5184 ferr(po, "zero rotate\n");
5185 fprintf(fout, " tmp = (%s >> %d) & 1;\n",
5186 buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
5187 if (po->op == OP_RCL) {
5188 fprintf(fout,
5189 " %s = (%s << %d) | (cond_c << %d)",
5190 buf1, buf1, j, j - 1);
5191 if (j != 1)
5192 fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
5193 }
5194 else {
5195 fprintf(fout,
5196 " %s = (%s >> %d) | (cond_c << %d)",
5197 buf1, buf1, j, l - j);
5198 if (j != 1)
5199 fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
5200 }
5201 fprintf(fout, ";\n");
5202 fprintf(fout, " cond_c = tmp;");
5203 }
5204 else
5205 ferr(po, "TODO\n");
5206 strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
5207 output_std_flags(fout, po, &pfomask, buf1);
5208 last_arith_dst = &po->operand[0];
5209 delayed_flag_op = NULL;
5210 break;
5211
5101a5f9 5212 case OP_XOR:
850c9265 5213 assert_operand_cnt(2);
5214 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5101a5f9 5215 if (IS(opr_name(po, 0), opr_name(po, 1))) {
5216 // special case for XOR
2fe80fdb 5217 if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
5218 fprintf(fout, " cond_be = 1;\n");
5219 pfomask &= ~(1 << PFO_BE);
5220 }
5101a5f9 5221 fprintf(fout, " %s = 0;",
5222 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5223 last_arith_dst = &po->operand[0];
5224 delayed_flag_op = NULL;
850c9265 5225 break;
850c9265 5226 }
5101a5f9 5227 goto dualop_arith;
5228
2fe80fdb 5229 case OP_ADD:
5230 assert_operand_cnt(2);
5231 propagate_lmod(po, &po->operand[0], &po->operand[1]);
5232 if (pfomask & (1 << PFO_C)) {
c8dbc5be 5233 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5234 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5235 if (po->operand[0].lmod == OPLM_DWORD) {
5236 fprintf(fout, " tmp64 = (u64)%s + %s;\n", buf1, buf2);
5237 fprintf(fout, " cond_c = tmp64 >> 32;\n");
5238 fprintf(fout, " %s = (u32)tmp64;",
5239 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
5240 strcat(g_comment, "add64");
5241 }
5242 else {
5243 fprintf(fout, " cond_c = ((u32)%s + %s) >> %d;\n",
5244 buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
5245 fprintf(fout, " %s += %s;",
5246 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5247 buf2);
5248 }
2fe80fdb 5249 pfomask &= ~(1 << PFO_C);
5250 output_std_flags(fout, po, &pfomask, buf1);
5251 last_arith_dst = &po->operand[0];
5252 delayed_flag_op = NULL;
5253 break;
5254 }
5255 goto dualop_arith;
5256
5257 case OP_SUB:
5258 assert_operand_cnt(2);
5259 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3b2f4044 5260 if (pfomask & ~((1 << PFO_Z) | (1 << PFO_S))) {
5261 for (j = 0; j <= PFO_LE; j++) {
5262 if (!(pfomask & (1 << j)))
5263 continue;
5264 if (j == PFO_Z || j == PFO_S)
5265 continue;
5266
5267 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5268 fprintf(fout, " cond_%s = %s;\n",
5269 parsed_flag_op_names[j], buf1);
5270 pfomask &= ~(1 << j);
5271 }
2fe80fdb 5272 }
5273 goto dualop_arith;
5274
5101a5f9 5275 case OP_ADC:
850c9265 5276 case OP_SBB:
5101a5f9 5277 assert_operand_cnt(2);
5278 propagate_lmod(po, &po->operand[0], &po->operand[1]);
a2c1d768 5279 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
840257f6 5280 if (po->op == OP_SBB
5281 && IS(po->operand[0].name, po->operand[1].name))
5282 {
5283 // avoid use of unitialized var
a2c1d768 5284 fprintf(fout, " %s = -cond_c;", buf1);
94d447fb 5285 // carry remains what it was
5286 pfomask &= ~(1 << PFO_C);
840257f6 5287 }
5288 else {
a2c1d768 5289 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
3ebea2cf 5290 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
840257f6 5291 }
a2c1d768 5292 output_std_flags(fout, po, &pfomask, buf1);
5101a5f9 5293 last_arith_dst = &po->operand[0];
5294 delayed_flag_op = NULL;
850c9265 5295 break;
5296
1f84f6b3 5297 case OP_BSF:
5298 assert_operand_cnt(2);
5299 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
5300 fprintf(fout, " %s = %s ? __builtin_ffs(%s) - 1 : 0;",
5301 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
5302 buf2, buf2);
5303 output_std_flags(fout, po, &pfomask, buf1);
5304 last_arith_dst = &po->operand[0];
5305 delayed_flag_op = NULL;
5306 strcat(g_comment, "bsf");
5307 break;
5308
850c9265 5309 case OP_DEC:
90307a99 5310 if (pfomask & ~(PFOB_S | PFOB_S | PFOB_C)) {
5311 for (j = 0; j <= PFO_LE; j++) {
5312 if (!(pfomask & (1 << j)))
5313 continue;
5314 if (j == PFO_Z || j == PFO_S || j == PFO_C)
5315 continue;
5316
5317 out_cmp_for_cc(buf1, sizeof(buf1), po, j, 0);
5318 fprintf(fout, " cond_%s = %s;\n",
5319 parsed_flag_op_names[j], buf1);
5320 pfomask &= ~(1 << j);
5321 }
5322 }
5323 // fallthrough
5324
5325 case OP_INC:
5326 if (pfomask & (1 << PFO_C))
5327 // carry is unaffected by inc/dec.. wtf?
5328 ferr(po, "carry propagation needed\n");
5329
850c9265 5330 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
1bafb621 5331 if (po->operand[0].type == OPT_REG) {
5332 strcpy(buf2, po->op == OP_INC ? "++" : "--");
5333 fprintf(fout, " %s%s;", buf1, buf2);
5334 }
5335 else {
5336 strcpy(buf2, po->op == OP_INC ? "+" : "-");
5337 fprintf(fout, " %s %s= 1;", buf1, buf2);
5338 }
a2c1d768 5339 output_std_flags(fout, po, &pfomask, buf1);
5101a5f9 5340 last_arith_dst = &po->operand[0];
5341 delayed_flag_op = NULL;
5342 break;
5343
5344 case OP_NEG:
5345 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3ebea2cf 5346 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
5101a5f9 5347 fprintf(fout, " %s = -%s%s;", buf1,
5348 lmod_cast_s(po, po->operand[0].lmod), buf2);
850c9265 5349 last_arith_dst = &po->operand[0];
69a3cdfc 5350 delayed_flag_op = NULL;
940e8e66 5351 if (pfomask & (1 << PFO_C)) {
5352 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
5353 pfomask &= ~(1 << PFO_C);
5354 }
850c9265 5355 break;
5356
5357 case OP_IMUL:
de50b98b 5358 if (po->operand_cnt == 2) {
5359 propagate_lmod(po, &po->operand[0], &po->operand[1]);
850c9265 5360 goto dualop_arith;
de50b98b 5361 }
87bf6cec 5362 if (po->operand_cnt == 3)
5363 ferr(po, "TODO imul3\n");
5364 // fallthrough
5365 case OP_MUL:
5366 assert_operand_cnt(1);
c8dbc5be 5367 switch (po->operand[0].lmod) {
5368 case OPLM_DWORD:
5369 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
5370 fprintf(fout, " tmp64 = %seax * %s%s;\n", buf1, buf1,
5371 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
5372 fprintf(fout, " edx = tmp64 >> 32;\n");
5373 fprintf(fout, " eax = tmp64;");
5374 break;
5375 case OPLM_BYTE:
5376 strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
5377 fprintf(fout, " LOWORD(eax) = %seax * %s;", buf1,
5378 out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
5379 buf1, 0));
5380 break;
5381 default:
5382 ferr(po, "TODO: unhandled mul type\n");
5383 break;
5384 }
87bf6cec 5385 last_arith_dst = NULL;
69a3cdfc 5386 delayed_flag_op = NULL;
91977a1c 5387 break;
5388
5101a5f9 5389 case OP_DIV:
5390 case OP_IDIV:
5391 assert_operand_cnt(1);
5392 if (po->operand[0].lmod != OPLM_DWORD)
5393 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
5394
cb090db0 5395 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5396 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
5397 po->op == OP_IDIV));
5398 switch (po->operand[0].lmod) {
5399 case OPLM_DWORD:
5400 if (po->flags & OPF_32BIT)
5401 snprintf(buf3, sizeof(buf3), "%seax", buf2);
5402 else {
5403 fprintf(fout, " tmp64 = ((u64)edx << 32) | eax;\n");
5404 snprintf(buf3, sizeof(buf3), "%stmp64",
5405 (po->op == OP_IDIV) ? "(s64)" : "");
5406 }
5407 if (po->operand[0].type == OPT_REG
5408 && po->operand[0].reg == xDX)
5409 {
5410 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5411 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5412 }
5413 else {
5414 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
5415 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
5416 }
5417 break;
5418 default:
5419 ferr(po, "unhandled division type\n");
5101a5f9 5420 }
87bf6cec 5421 last_arith_dst = NULL;
5422 delayed_flag_op = NULL;
5101a5f9 5423 break;
5424
91977a1c 5425 case OP_TEST:
5426 case OP_CMP:
850c9265 5427 propagate_lmod(po, &po->operand[0], &po->operand[1]);
940e8e66 5428 if (pfomask != 0) {
69a3cdfc 5429 for (j = 0; j < 8; j++) {
940e8e66 5430 if (pfomask & (1 << j)) {
69a3cdfc 5431 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
5432 fprintf(fout, " cond_%s = %s;",
5433 parsed_flag_op_names[j], buf1);
5434 }
5435 }
940e8e66 5436 pfomask = 0;
69a3cdfc 5437 }
5438 else
5439 no_output = 1;
7ba45c34 5440 last_arith_dst = NULL;
69a3cdfc 5441 delayed_flag_op = po;
91977a1c 5442 break;
5443
092f64e1 5444 case OP_SCC:
5445 // SETcc - should already be handled
5446 break;
5447
69a3cdfc 5448 // note: we reuse OP_Jcc for SETcc, only flags differ
092f64e1 5449 case OP_JCC:
5450 fprintf(fout, "\n goto %s;", po->operand[0].name);
850c9265 5451 break;
5452
5c024ef7 5453 case OP_JECXZ:
5454 fprintf(fout, " if (ecx == 0)\n");
5455 fprintf(fout, " goto %s;", po->operand[0].name);
5456 strcat(g_comment, "jecxz");
5457 break;
5458
04abc5d6 5459 case OP_LOOP:
5460 fprintf(fout, " if (--ecx == 0)\n");
5461 fprintf(fout, " goto %s;", po->operand[0].name);
5462 strcat(g_comment, "loop");
5463 break;
5464
850c9265 5465 case OP_JMP:
87bf6cec 5466 assert_operand_cnt(1);
de50b98b 5467 last_arith_dst = NULL;
5468 delayed_flag_op = NULL;
5469
4c45fa73 5470 if (po->operand[0].type == OPT_REGMEM) {
5471 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
5472 buf1, buf2);
5473 if (ret != 2)
5474 ferr(po, "parse failure for jmp '%s'\n",
5475 po->operand[0].name);
5476 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
5477 break;
5478 }
5479 else if (po->operand[0].type != OPT_LABEL)
5480 ferr(po, "unhandled jmp type\n");
87bf6cec 5481
850c9265 5482 fprintf(fout, " goto %s;", po->operand[0].name);
91977a1c 5483 break;
5484
5485 case OP_CALL:
5101a5f9 5486 assert_operand_cnt(1);
092f64e1 5487 pp = po->pp;
89ff3147 5488 my_assert_not(pp, NULL);
91977a1c 5489
092f64e1 5490 strcpy(buf3, " ");
5491 if (po->flags & OPF_CC) {
5492 // we treat conditional branch to another func
5493 // (yes such code exists..) as conditional tailcall
5494 strcat(buf3, " ");
5495 fprintf(fout, " {\n");
5496 }
5497
8eb12e72 5498 if (pp->is_fptr && !pp->is_arg) {
092f64e1 5499 fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
1cd4a663 5500 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
5501 "(void *)", 0));
8eb12e72 5502 if (pp->is_unresolved)
5503 fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
5504 buf3, asmfn, po->asmln, pp->name);
5505 }
1bafb621 5506
092f64e1 5507 fprintf(fout, "%s", buf3);
2b43685d 5508 if (strstr(pp->ret_type.name, "int64")) {
87bf6cec 5509 if (po->flags & OPF_TAIL)
2b43685d 5510 ferr(po, "int64 and tail?\n");
2fe80fdb 5511 fprintf(fout, "tmp64 = ");
2b43685d 5512 }
5513 else if (!IS(pp->ret_type.name, "void")) {
5514 if (po->flags & OPF_TAIL) {
840257f6 5515 if (!IS(g_func_pp->ret_type.name, "void")) {
5516 fprintf(fout, "return ");
5517 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
5518 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
5519 }
2b43685d 5520 }
75ad0378 5521 else if (regmask & (1 << xAX)) {
87bf6cec 5522 fprintf(fout, "eax = ");
2b43685d 5523 if (pp->ret_type.is_ptr)
5524 fprintf(fout, "(u32)");
5525 }
91977a1c 5526 }
87bf6cec 5527
ddaf8bd7 5528 if (pp->name[0] == 0)
5529 ferr(po, "missing pp->name\n");
5530 fprintf(fout, "%s%s(", pp->name,
5531 pp->has_structarg ? "_sa" : "");
39b168b8 5532
2fe80fdb 5533 if (po->flags & OPF_ATAIL) {
5534 if (pp->argc_stack != g_func_pp->argc_stack
5535 || (pp->argc_stack > 0
5536 && pp->is_stdcall != g_func_pp->is_stdcall))
5537 ferr(po, "incompatible tailcall\n");
1f84f6b3 5538 if (g_func_pp->has_retreg)
5539 ferr(po, "TODO: retreg+tailcall\n");
87bf6cec 5540
2fe80fdb 5541 for (arg = j = 0; arg < pp->argc; arg++) {
5542 if (arg > 0)
5543 fprintf(fout, ", ");
87bf6cec 5544
2fe80fdb 5545 cast[0] = 0;
5546 if (pp->arg[arg].type.is_ptr)
5547 snprintf(cast, sizeof(cast), "(%s)",
5548 pp->arg[arg].type.name);
91977a1c 5549
2fe80fdb 5550 if (pp->arg[arg].reg != NULL) {
5551 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
5552 continue;
5553 }
5554 // stack arg
5555 for (; j < g_func_pp->argc; j++)
5556 if (g_func_pp->arg[j].reg == NULL)
5557 break;
5558 fprintf(fout, "%sa%d", cast, j + 1);
5559 j++;
69a3cdfc 5560 }
2fe80fdb 5561 }
5562 else {
5563 for (arg = 0; arg < pp->argc; arg++) {
5564 if (arg > 0)
5565 fprintf(fout, ", ");
5566
5567 cast[0] = 0;
5568 if (pp->arg[arg].type.is_ptr)
5569 snprintf(cast, sizeof(cast), "(%s)",
5570 pp->arg[arg].type.name);
5571
5572 if (pp->arg[arg].reg != NULL) {
1f84f6b3 5573 if (pp->arg[arg].type.is_retreg)
5574 fprintf(fout, "&%s", pp->arg[arg].reg);
5575 else
5576 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
2fe80fdb 5577 continue;
5578 }
5579
5580 // stack arg
5581 tmp_op = pp->arg[arg].datap;
5582 if (tmp_op == NULL)
5583 ferr(po, "parsed_op missing for arg%d\n", arg);
23fd0b11 5584
5585 if (tmp_op->flags & OPF_VAPUSH) {
5586 fprintf(fout, "ap");
5587 }
5f70a34f 5588 else if (tmp_op->p_argpass != 0) {
5589 fprintf(fout, "a%d", tmp_op->p_argpass);
5590 }
5591 else if (tmp_op->p_argnum != 0) {
3a5101d7 5592 fprintf(fout, "%s%s", cast,
5593 saved_arg_name(buf1, sizeof(buf1),
5594 tmp_op->p_arggrp, tmp_op->p_argnum));
2fe80fdb 5595 }
5596 else {
5597 fprintf(fout, "%s",
5598 out_src_opr(buf1, sizeof(buf1),
5599 tmp_op, &tmp_op->operand[0], cast, 0));
5600 }
69a3cdfc 5601 }
91977a1c 5602 }
5603 fprintf(fout, ");");
87bf6cec 5604
2b43685d 5605 if (strstr(pp->ret_type.name, "int64")) {
5606 fprintf(fout, "\n");
092f64e1 5607 fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
5608 fprintf(fout, "%seax = tmp64;", buf3);
2b43685d 5609 }
5610
89ff3147 5611 if (pp->is_unresolved) {
8eb12e72 5612 snprintf(buf2, sizeof(buf2), " unresolved %dreg",
89ff3147 5613 pp->argc_reg);
092f64e1 5614 strcat(g_comment, buf2);
89ff3147 5615 }
5616
87bf6cec 5617 if (po->flags & OPF_TAIL) {
840257f6 5618 ret = 0;
ddaf8bd7 5619 if (i == opcnt - 1 || pp->is_noreturn)
840257f6 5620 ret = 0;
5621 else if (IS(pp->ret_type.name, "void"))
5622 ret = 1;
5623 else if (IS(g_func_pp->ret_type.name, "void"))
5624 ret = 1;
5625 // else already handled as 'return f()'
5626
5627 if (ret) {
da87ae38 5628 if (!IS(g_func_pp->ret_type.name, "void")) {
ddaf8bd7 5629 ferr(po, "int func -> void func tailcall?\n");
da87ae38 5630 }
5631 else {
092f64e1 5632 fprintf(fout, "\n%sreturn;", buf3);
ddaf8bd7 5633 strcat(g_comment, " ^ tailcall");
da87ae38 5634 }
3ebea2cf 5635 }
89ff3147 5636 else
ddaf8bd7 5637 strcat(g_comment, " tailcall");
87bf6cec 5638 }
ddaf8bd7 5639 if (pp->is_noreturn)
5640 strcat(g_comment, " noreturn");
2fe80fdb 5641 if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
5642 strcat(g_comment, " argframe");
092f64e1 5643 if (po->flags & OPF_CC)
5644 strcat(g_comment, " cond");
5645
5646 if (po->flags & OPF_CC)
5647 fprintf(fout, "\n }");
5648
87bf6cec 5649 delayed_flag_op = NULL;
5650 last_arith_dst = NULL;
91977a1c 5651 break;
5652
5653 case OP_RET:
bd96f656 5654 if (g_func_pp->is_vararg)
4f12f671 5655 fprintf(fout, " va_end(ap);\n");
1f84f6b3 5656 if (g_func_pp->has_retreg) {
5657 for (arg = 0; arg < g_func_pp->argc; arg++)
5658 if (g_func_pp->arg[arg].type.is_retreg)
5659 fprintf(fout, " *r_%s = %s;\n",
5660 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
5661 }
4f12f671 5662
bd96f656 5663 if (IS(g_func_pp->ret_type.name, "void")) {
3ebea2cf 5664 if (i != opcnt - 1 || label_pending)
5665 fprintf(fout, " return;");
5666 }
bd96f656 5667 else if (g_func_pp->ret_type.is_ptr) {
d4e3b5db 5668 fprintf(fout, " return (%s)eax;",
bd96f656 5669 g_func_pp->ret_type.name);
3ebea2cf 5670 }
2fe80fdb 5671 else if (IS(g_func_pp->ret_type.name, "__int64"))
5672 fprintf(fout, " return ((u64)edx << 32) | eax;");
91977a1c 5673 else
5674 fprintf(fout, " return eax;");
de50b98b 5675
5676 last_arith_dst = NULL;
5677 delayed_flag_op = NULL;
91977a1c 5678 break;
5679
5680 case OP_PUSH:
1f84f6b3 5681 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
5f70a34f 5682 if (po->p_argnum != 0) {
69a3cdfc 5683 // special case - saved func arg
3a5101d7 5684 fprintf(fout, " %s = %s;",
5685 saved_arg_name(buf2, sizeof(buf2),
5686 po->p_arggrp, po->p_argnum), buf1);
69a3cdfc 5687 break;
5688 }
d4e3b5db 5689 else if (po->flags & OPF_RSAVE) {
d4e3b5db 5690 fprintf(fout, " s_%s = %s;", buf1, buf1);
5691 break;
5692 }
25a330eb 5693 else if (po->flags & OPF_PPUSH) {
5694 tmp_op = po->datap;
5695 ferr_assert(po, tmp_op != NULL);
5696 out_dst_opr(buf2, sizeof(buf2), po, &tmp_op->operand[0]);
5697 fprintf(fout, " pp_%s = %s;", buf2, buf1);
5698 break;
5699 }
1f84f6b3 5700 else if (g_func_pp->is_userstack) {
5701 fprintf(fout, " *(--esp) = %s;", buf1);
5702 break;
5703 }
e56ab892 5704 if (!(g_ida_func_attr & IDAFA_NORETURN))
5705 ferr(po, "stray push encountered\n");
5706 no_output = 1;
91977a1c 5707 break;
5708
5709 case OP_POP:
25a330eb 5710 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
d4e3b5db 5711 if (po->flags & OPF_RSAVE) {
d4e3b5db 5712 fprintf(fout, " %s = s_%s;", buf1, buf1);
5713 break;
5714 }
25a330eb 5715 else if (po->flags & OPF_PPUSH) {
5716 // push/pop graph
5717 ferr_assert(po, po->datap == NULL);
5718 fprintf(fout, " %s = pp_%s;", buf1, buf1);
5719 break;
5720 }
5c024ef7 5721 else if (po->datap != NULL) {
5722 // push/pop pair
5723 tmp_op = po->datap;
5c024ef7 5724 fprintf(fout, " %s = %s;", buf1,
5725 out_src_opr(buf2, sizeof(buf2),
5726 tmp_op, &tmp_op->operand[0],
c7ed83dd 5727 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
5c024ef7 5728 break;
5729 }
1f84f6b3 5730 else if (g_func_pp->is_userstack) {
25a330eb 5731 fprintf(fout, " %s = *esp++;", buf1);
1f84f6b3 5732 break;
5733 }
5734 else
5735 ferr(po, "stray pop encountered\n");
91977a1c 5736 break;
5737
33c35af6 5738 case OP_NOP:
2b43685d 5739 no_output = 1;
33c35af6 5740 break;
5741
90307a99 5742 // mmx
5743 case OP_EMMS:
5744 strcpy(g_comment, "(emms)");
5745 break;
5746
91977a1c 5747 default:
5748 no_output = 1;
69a3cdfc 5749 ferr(po, "unhandled op type %d, flags %x\n",
5750 po->op, po->flags);
91977a1c 5751 break;
5752 }
5753
5754 if (g_comment[0] != 0) {
ddaf8bd7 5755 char *p = g_comment;
5756 while (my_isblank(*p))
5757 p++;
5758 fprintf(fout, " // %s", p);
91977a1c 5759 g_comment[0] = 0;
5760 no_output = 0;
5761 }
5762 if (!no_output)
5763 fprintf(fout, "\n");
5101a5f9 5764
2b43685d 5765 // some sanity checking
591721d7 5766 if (po->flags & OPF_REP) {
5767 if (po->op != OP_STOS && po->op != OP_MOVS
5768 && po->op != OP_CMPS && po->op != OP_SCAS)
5769 ferr(po, "unexpected rep\n");
5770 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
5771 && (po->op == OP_CMPS || po->op == OP_SCAS))
5772 ferr(po, "cmps/scas with plain rep\n");
5773 }
5774 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
5775 && po->op != OP_CMPS && po->op != OP_SCAS)
2b43685d 5776 ferr(po, "unexpected repz/repnz\n");
5777
940e8e66 5778 if (pfomask != 0)
7ba45c34 5779 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
940e8e66 5780
5101a5f9 5781 // see is delayed flag stuff is still valid
5782 if (delayed_flag_op != NULL && delayed_flag_op != po) {
89ff3147 5783 if (is_any_opr_modified(delayed_flag_op, po, 0))
5101a5f9 5784 delayed_flag_op = NULL;
5785 }
5786
5787 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
5788 if (is_opr_modified(last_arith_dst, po))
5789 last_arith_dst = NULL;
5790 }
3ebea2cf 5791
5792 label_pending = 0;
91977a1c 5793 }
5794
a2c1d768 5795 if (g_stack_fsz && !g_stack_frame_used)
5796 fprintf(fout, " (void)sf;\n");
5797
91977a1c 5798 fprintf(fout, "}\n\n");
5799
9af2d373 5800 gen_x_cleanup(opcnt);
5801}
5802
5803static void gen_x_cleanup(int opcnt)
5804{
5805 int i;
5806
91977a1c 5807 for (i = 0; i < opcnt; i++) {
4c45fa73 5808 struct label_ref *lr, *lr_del;
5809
5810 lr = g_label_refs[i].next;
5811 while (lr != NULL) {
5812 lr_del = lr;
5813 lr = lr->next;
5814 free(lr_del);
5815 }
5816 g_label_refs[i].i = -1;
5817 g_label_refs[i].next = NULL;
5818
91977a1c 5819 if (ops[i].op == OP_CALL) {
092f64e1 5820 if (ops[i].pp)
5821 proto_release(ops[i].pp);
91977a1c 5822 }
5823 }
bd96f656 5824 g_func_pp = NULL;
91977a1c 5825}
c36e914d 5826
92d715b6 5827struct func_proto_dep;
5828
5829struct func_prototype {
5830 char name[NAMELEN];
5831 int id;
5832 int argc_stack;
5833 int regmask_dep;
91ca764a 5834 int has_ret:3; // -1, 0, 1: unresolved, no, yes
92d715b6 5835 unsigned int dep_resolved:1;
5836 unsigned int is_stdcall:1;
5837 struct func_proto_dep *dep_func;
5838 int dep_func_cnt;
91ca764a 5839 const struct parsed_proto *pp; // seed pp, if any
92d715b6 5840};
5841
5842struct func_proto_dep {
5843 char *name;
5844 struct func_prototype *proto;
5845 int regmask_live; // .. at the time of call
5846 unsigned int ret_dep:1; // return from this is caller's return
5847};
5848
5849static struct func_prototype *hg_fp;
5850static int hg_fp_cnt;
5851
5fa1256f 5852static struct scanned_var {
5853 char name[NAMELEN];
5854 enum opr_lenmod lmod;
5855 unsigned int is_seeded:1;
61e29183 5856 unsigned int is_c_str:1;
c0de9015 5857 const struct parsed_proto *pp; // seed pp, if any
5fa1256f 5858} *hg_vars;
5859static int hg_var_cnt;
5860
9af2d373 5861static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
5862 int count);
5863
ebc4dc43 5864struct func_prototype *hg_fp_add(const char *funcn)
5865{
5866 struct func_prototype *fp;
5867
5868 if ((hg_fp_cnt & 0xff) == 0) {
5869 hg_fp = realloc(hg_fp, sizeof(hg_fp[0]) * (hg_fp_cnt + 0x100));
5870 my_assert_not(hg_fp, NULL);
5871 memset(hg_fp + hg_fp_cnt, 0, sizeof(hg_fp[0]) * 0x100);
5872 }
5873
5874 fp = &hg_fp[hg_fp_cnt];
5875 snprintf(fp->name, sizeof(fp->name), "%s", funcn);
5876 fp->id = hg_fp_cnt;
5877 fp->argc_stack = -1;
5878 hg_fp_cnt++;
5879
5880 return fp;
5881}
5882
92d715b6 5883static struct func_proto_dep *hg_fp_find_dep(struct func_prototype *fp,
5884 const char *name)
5885{
5886 int i;
5887
5888 for (i = 0; i < fp->dep_func_cnt; i++)
5889 if (IS(fp->dep_func[i].name, name))
5890 return &fp->dep_func[i];
5891
5892 return NULL;
5893}
5894
5895static void hg_fp_add_dep(struct func_prototype *fp, const char *name)
5896{
5897 // is it a dupe?
5898 if (hg_fp_find_dep(fp, name))
5899 return;
5900
5901 if ((fp->dep_func_cnt & 0xff) == 0) {
5902 fp->dep_func = realloc(fp->dep_func,
5903 sizeof(fp->dep_func[0]) * (fp->dep_func_cnt + 0x100));
5904 my_assert_not(fp->dep_func, NULL);
5905 memset(&fp->dep_func[fp->dep_func_cnt], 0,
5906 sizeof(fp->dep_func[0]) * 0x100);
5907 }
5908 fp->dep_func[fp->dep_func_cnt].name = strdup(name);
5909 fp->dep_func_cnt++;
5910}
5911
5912static int hg_fp_cmp_name(const void *p1_, const void *p2_)
5913{
5914 const struct func_prototype *p1 = p1_, *p2 = p2_;
5915 return strcmp(p1->name, p2->name);
5916}
5917
5918#if 0
5919static int hg_fp_cmp_id(const void *p1_, const void *p2_)
5920{
5921 const struct func_prototype *p1 = p1_, *p2 = p2_;
5922 return p1->id - p2->id;
5923}
5924#endif
5925
91ca764a 5926// recursive register dep pass
5927// - track saved regs (part 2)
5928// - try to figure out arg-regs
5929// - calculate reg deps
5930static void gen_hdr_dep_pass(int i, int opcnt, unsigned char *cbits,
5931 struct func_prototype *fp, int regmask_save, int regmask_dst,
5932 int *regmask_dep, int *has_ret)
5933{
5934 struct func_proto_dep *dep;
5935 struct parsed_op *po;
5936 int from_caller = 0;
5937 int depth;
5938 int j, l;
5939 int reg;
5940 int ret;
5941
5942 for (; i < opcnt; i++)
5943 {
5944 if (cbits[i >> 3] & (1 << (i & 7)))
5945 return;
5946 cbits[i >> 3] |= (1 << (i & 7));
5947
5948 po = &ops[i];
5949
5950 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
04abc5d6 5951 if (po->flags & OPF_RMD)
5952 continue;
5953
91ca764a 5954 if (po->btj != NULL) {
5955 // jumptable
5956 for (j = 0; j < po->btj->count; j++) {
db63af51 5957 check_i(po, po->btj->d[j].bt_i);
91ca764a 5958 gen_hdr_dep_pass(po->btj->d[j].bt_i, opcnt, cbits, fp,
5959 regmask_save, regmask_dst, regmask_dep, has_ret);
5960 }
5961 return;
5962 }
5963
db63af51 5964 check_i(po, po->bt_i);
91ca764a 5965 if (po->flags & OPF_CJMP) {
5966 gen_hdr_dep_pass(po->bt_i, opcnt, cbits, fp,
5967 regmask_save, regmask_dst, regmask_dep, has_ret);
5968 }
5969 else {
5970 i = po->bt_i - 1;
5971 }
5972 continue;
5973 }
5974
5975 if (po->flags & OPF_FARG)
5976 /* (just calculate register deps) */;
5977 else if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
5978 {
5979 reg = po->operand[0].reg;
5980 if (reg < 0)
5981 ferr(po, "reg not set for push?\n");
5982
5983 if (po->flags & OPF_RSAVE) {
5984 regmask_save |= 1 << reg;
5985 continue;
5986 }
5987 if (po->flags & OPF_DONE)
5988 continue;
5989
5990 depth = 0;
5991 ret = scan_for_pop(i + 1, opcnt,
5992 po->operand[0].name, i + opcnt * 2, 0, &depth, 0);
5993 if (ret == 1) {
5994 regmask_save |= 1 << reg;
5995 po->flags |= OPF_RMD;
5996 scan_for_pop(i + 1, opcnt,
5997 po->operand[0].name, i + opcnt * 3, 0, &depth, 1);
5998 continue;
5999 }
6000 }
6001 else if (po->flags & OPF_RMD)
6002 continue;
6003 else if (po->op == OP_CALL) {
6004 po->regmask_dst |= 1 << xAX;
6005
6006 dep = hg_fp_find_dep(fp, po->operand[0].name);
6007 if (dep != NULL)
6008 dep->regmask_live = regmask_save | regmask_dst;
6009 }
6010 else if (po->op == OP_RET) {
6011 if (po->operand_cnt > 0) {
6012 fp->is_stdcall = 1;
6013 if (fp->argc_stack >= 0
6014 && fp->argc_stack != po->operand[0].val / 4)
6015 ferr(po, "ret mismatch? (%d)\n", fp->argc_stack * 4);
6016 fp->argc_stack = po->operand[0].val / 4;
6017 }
6018 }
6019
ebc4dc43 6020 // if has_ret is 0, there is uninitialized eax path,
6021 // which means it's most likely void func
91ca764a 6022 if (*has_ret != 0 && (po->flags & OPF_TAIL)) {
6023 if (po->op == OP_CALL) {
6024 j = i;
6025 ret = 1;
6026 }
6027 else {
6028 struct parsed_opr opr = { 0, };
6029 opr.type = OPT_REG;
6030 opr.reg = xAX;
6031 j = -1;
6032 from_caller = 0;
6033 ret = resolve_origin(i, &opr, i + opcnt * 4, &j, &from_caller);
6034 }
6035
ebc4dc43 6036 if (ret != 1 && from_caller) {
91ca764a 6037 // unresolved eax - probably void func
6038 *has_ret = 0;
6039 }
6040 else {
ebc4dc43 6041 if (j >= 0 && ops[j].op == OP_CALL) {
6042 dep = hg_fp_find_dep(fp, ops[j].operand[0].name);
91ca764a 6043 if (dep != NULL)
6044 dep->ret_dep = 1;
6045 else
6046 *has_ret = 1;
6047 }
6048 else
6049 *has_ret = 1;
6050 }
6051 }
6052
6053 l = regmask_save | regmask_dst;
6054 if (g_bp_frame && !(po->flags & OPF_EBP_S))
6055 l |= 1 << xBP;
6056
6057 l = po->regmask_src & ~l;
6058#if 0
6059 if (l)
6060 fnote(po, "dep |= %04x, dst %04x, save %04x (f %x)\n",
6061 l, regmask_dst, regmask_save, po->flags);
6062#endif
6063 *regmask_dep |= l;
6064 regmask_dst |= po->regmask_dst;
6065
6066 if (po->flags & OPF_TAIL)
6067 return;
6068 }
6069}
6070
92d715b6 6071static void gen_hdr(const char *funcn, int opcnt)
6072{
26677139 6073 int save_arg_vars[MAX_ARG_GRP] = { 0, };
91ca764a 6074 unsigned char cbits[MAX_OPS / 8];
ebc4dc43 6075 const struct parsed_proto *pp_c;
9af2d373 6076 struct parsed_proto *pp;
92d715b6 6077 struct func_prototype *fp;
92d715b6 6078 struct parsed_op *po;
26677139 6079 int regmask_dummy = 0;
91ca764a 6080 int regmask_dep;
92d715b6 6081 int max_bp_offset = 0;
91ca764a 6082 int has_ret;
bfacdc83 6083 int i, j, l;
6084 int ret;
92d715b6 6085
ebc4dc43 6086 pp_c = proto_parse(g_fhdr, funcn, 1);
6087 if (pp_c != NULL)
6088 // already in seed, will add to hg_fp later
9af2d373 6089 return;
ebc4dc43 6090
6091 fp = hg_fp_add(funcn);
9af2d373 6092
6093 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
6094 g_stack_frame_used = 0;
6095
92d715b6 6096 // pass1:
66bdb2b0 6097 // - resolve all branches
6098 // - parse calls with labels
6099 resolve_branches_parse_calls(opcnt);
6100
6101 // pass2:
9af2d373 6102 // - handle ebp/esp frame, remove ops related to it
6103 scan_prologue_epilogue(opcnt);
6104
66bdb2b0 6105 // pass3:
6106 // - remove dead labels
92d715b6 6107 // - collect calls
92d715b6 6108 for (i = 0; i < opcnt; i++)
6109 {
66bdb2b0 6110 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
6111 free(g_labels[i]);
6112 g_labels[i] = NULL;
6113 }
92d715b6 6114
66bdb2b0 6115 po = &ops[i];
5e49b270 6116 if (po->flags & (OPF_RMD|OPF_DONE))
92d715b6 6117 continue;
6118
6119 if (po->op == OP_CALL) {
66bdb2b0 6120 if (po->operand[0].type == OPT_LABEL)
6121 hg_fp_add_dep(fp, opr_name(po, 0));
6122 else if (po->pp != NULL)
6123 hg_fp_add_dep(fp, po->pp->name);
92d715b6 6124 }
92d715b6 6125 }
6126
66bdb2b0 6127 // pass4:
92d715b6 6128 // - remove dead labels
9af2d373 6129 // - handle push <const>/pop pairs
92d715b6 6130 for (i = 0; i < opcnt; i++)
6131 {
d7857c3a 6132 if (g_labels[i] != NULL && g_label_refs[i].i == -1) {
6133 free(g_labels[i]);
6134 g_labels[i] = NULL;
6135 }
9af2d373 6136
91ca764a 6137 po = &ops[i];
6138 if (po->flags & (OPF_RMD|OPF_DONE))
6139 continue;
6140
6141 if (po->op == OP_PUSH && po->operand[0].type == OPT_CONST)
25a330eb 6142 scan_for_pop_const(i, opcnt, &regmask_dummy);
91ca764a 6143 }
6144
66bdb2b0 6145 // pass5:
91ca764a 6146 // - process trivial calls
6147 for (i = 0; i < opcnt; i++)
6148 {
9af2d373 6149 po = &ops[i];
5e49b270 6150 if (po->flags & (OPF_RMD|OPF_DONE))
9af2d373 6151 continue;
6152
26677139 6153 if (po->op == OP_CALL)
6154 {
6155 pp = process_call_early(i, opcnt, &j);
6156 if (pp != NULL) {
6157 if (!(po->flags & OPF_ATAIL))
6158 // since we know the args, try to collect them
6159 if (collect_call_args_early(po, i, pp, &regmask_dummy) != 0)
6160 pp = NULL;
6161 }
6162
6163 if (pp != NULL) {
6164 if (j >= 0) {
6165 // commit esp adjust
5e49b270 6166 if (ops[j].op != OP_POP)
6167 patch_esp_adjust(&ops[j], pp->argc_stack * 4);
bfacdc83 6168 else {
6169 for (l = 0; l < pp->argc_stack; l++)
6170 ops[j + l].flags |= OPF_DONE | OPF_RMD;
6171 }
26677139 6172 }
6173
6174 po->flags |= OPF_DONE;
6175 }
6176 }
26677139 6177 }
6178
66bdb2b0 6179 // pass6:
5e49b270 6180 // - track saved regs (simple)
26677139 6181 // - process calls
6182 for (i = 0; i < opcnt; i++)
6183 {
6184 po = &ops[i];
5e49b270 6185 if (po->flags & (OPF_RMD|OPF_DONE))
26677139 6186 continue;
6187
5e49b270 6188 if (po->op == OP_PUSH && po->operand[0].type == OPT_REG)
6189 {
6190 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
6191 if (ret == 0) {
91ca764a 6192 // regmask_save |= 1 << po->operand[0].reg; // do it later
6193 po->flags |= OPF_RSAVE | OPF_RMD | OPF_DONE;
5e49b270 6194 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, OPF_RMD);
6195 }
6196 }
6197 else if (po->op == OP_CALL && !(po->flags & OPF_DONE))
26677139 6198 {
9af2d373 6199 pp = process_call(i, opcnt);
6200
6201 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
9af2d373 6202 // since we know the args, collect them
91ca764a 6203 ret = collect_call_args(po, i, pp, &regmask_dummy, save_arg_vars,
5e49b270 6204 i + opcnt * 1);
9af2d373 6205 }
6206 }
92d715b6 6207 }
6208
66bdb2b0 6209 // pass7
91ca764a 6210 memset(cbits, 0, sizeof(cbits));
6211 regmask_dep = 0;
6212 has_ret = -1;
6213
6214 gen_hdr_dep_pass(0, opcnt, cbits, fp, 0, 0, &regmask_dep, &has_ret);
6215
6216 // find unreachable code - must be fixed in IDA
92d715b6 6217 for (i = 0; i < opcnt; i++)
6218 {
91ca764a 6219 if (cbits[i >> 3] & (1 << (i & 7)))
9af2d373 6220 continue;
92d715b6 6221
04abc5d6 6222 if (g_labels[i] == NULL && i > 0 && ops[i - 1].op == OP_CALL
6223 && ops[i - 1].pp != NULL && ops[i - 1].pp->is_osinc)
6224 {
6225 // the compiler sometimes still generates code after
6226 // noreturn OS functions
6227 break;
6228 }
91ca764a 6229 if (ops[i].op != OP_NOP)
6230 ferr(&ops[i], "unreachable code\n");
92d715b6 6231 }
6232
9af2d373 6233 for (i = 0; i < g_eqcnt; i++) {
92d715b6 6234 if (g_eqs[i].offset > max_bp_offset && g_eqs[i].offset < 4*32)
6235 max_bp_offset = g_eqs[i].offset;
9af2d373 6236 }
92d715b6 6237
9af2d373 6238 if (fp->argc_stack < 0) {
92d715b6 6239 max_bp_offset = (max_bp_offset + 3) & ~3;
9af2d373 6240 fp->argc_stack = max_bp_offset / 4;
6241 if ((g_ida_func_attr & IDAFA_BP_FRAME) && fp->argc_stack > 0)
92d715b6 6242 fp->argc_stack--;
6243 }
6244
6245 fp->regmask_dep = regmask_dep & ~(1 << xSP);
6246 fp->has_ret = has_ret;
91ca764a 6247#if 0
6248 printf("// has_ret %d, regmask_dep %x\n",
6249 fp->has_ret, fp->regmask_dep);
6250 output_hdr_fp(stdout, fp, 1);
ebc4dc43 6251 if (IS(funcn, "sub_10007F72")) exit(1);
91ca764a 6252#endif
9af2d373 6253
6254 gen_x_cleanup(opcnt);
92d715b6 6255}
6256
6257static void hg_fp_resolve_deps(struct func_prototype *fp)
6258{
6259 struct func_prototype fp_s;
91ca764a 6260 int dep;
92d715b6 6261 int i;
6262
6263 // this thing is recursive, so mark first..
6264 fp->dep_resolved = 1;
6265
6266 for (i = 0; i < fp->dep_func_cnt; i++) {
6267 strcpy(fp_s.name, fp->dep_func[i].name);
6268 fp->dep_func[i].proto = bsearch(&fp_s, hg_fp, hg_fp_cnt,
6269 sizeof(hg_fp[0]), hg_fp_cmp_name);
6270 if (fp->dep_func[i].proto != NULL) {
6271 if (!fp->dep_func[i].proto->dep_resolved)
6272 hg_fp_resolve_deps(fp->dep_func[i].proto);
6273
91ca764a 6274 dep = ~fp->dep_func[i].regmask_live
6275 & fp->dep_func[i].proto->regmask_dep;
6276 fp->regmask_dep |= dep;
6277 // printf("dep %s %s |= %x\n", fp->name,
6278 // fp->dep_func[i].name, dep);
92d715b6 6279
ebc4dc43 6280 if (fp->has_ret == -1 && fp->dep_func[i].ret_dep)
92d715b6 6281 fp->has_ret = fp->dep_func[i].proto->has_ret;
6282 }
6283 }
6284}
6285
9af2d373 6286static void output_hdr_fp(FILE *fout, const struct func_prototype *fp,
6287 int count)
92d715b6 6288{
61e29183 6289 const struct parsed_proto *pp;
6290 char *p, namebuf[NAMELEN];
6291 const char *name;
92d715b6 6292 int regmask_dep;
6293 int argc_stack;
9af2d373 6294 int j, arg;
92d715b6 6295
9af2d373 6296 for (; count > 0; count--, fp++) {
92d715b6 6297 if (fp->has_ret == -1)
6298 fprintf(fout, "// ret unresolved\n");
6299#if 0
6300 fprintf(fout, "// dep:");
6301 for (j = 0; j < fp->dep_func_cnt; j++) {
6302 fprintf(fout, " %s/", fp->dep_func[j].name);
6303 if (fp->dep_func[j].proto != NULL)
6304 fprintf(fout, "%04x/%d", fp->dep_func[j].proto->regmask_dep,
6305 fp->dep_func[j].proto->has_ret);
6306 }
6307 fprintf(fout, "\n");
6308#endif
6309
61e29183 6310 p = strchr(fp->name, '@');
6311 if (p != NULL) {
6312 memcpy(namebuf, fp->name, p - fp->name);
6313 namebuf[p - fp->name] = 0;
6314 name = namebuf;
6315 }
6316 else
6317 name = fp->name;
6318 if (name[0] == '_')
6319 name++;
6320
6321 pp = proto_parse(g_fhdr, name, 1);
6322 if (pp != NULL && pp->is_include)
6323 continue;
6324
c0de9015 6325 if (fp->pp != NULL) {
4e81a3a2 6326 // part of seed, output later
6327 continue;
c0de9015 6328 }
6329
92d715b6 6330 regmask_dep = fp->regmask_dep;
6331 argc_stack = fp->argc_stack;
6332
91ca764a 6333 fprintf(fout, "%-5s", fp->pp ? fp->pp->ret_type.name :
6334 (fp->has_ret ? "int" : "void"));
92d715b6 6335 if (regmask_dep && (fp->is_stdcall || argc_stack == 0)
6336 && (regmask_dep & ~((1 << xCX) | (1 << xDX))) == 0)
6337 {
9af2d373 6338 fprintf(fout, " __fastcall ");
92d715b6 6339 if (!(regmask_dep & (1 << xDX)) && argc_stack == 0)
6340 argc_stack = 1;
6341 else
6342 argc_stack += 2;
6343 regmask_dep = 0;
6344 }
6345 else if (regmask_dep && !fp->is_stdcall) {
6346 fprintf(fout, "/*__usercall*/ ");
92d715b6 6347 }
6348 else if (regmask_dep) {
6349 fprintf(fout, "/*__userpurge*/ ");
92d715b6 6350 }
6351 else if (fp->is_stdcall)
9af2d373 6352 fprintf(fout, " __stdcall ");
92d715b6 6353 else
9af2d373 6354 fprintf(fout, " __cdecl ");
92d715b6 6355
61e29183 6356 fprintf(fout, "%s(", name);
92d715b6 6357
6358 arg = 0;
6359 for (j = 0; j < xSP; j++) {
6360 if (regmask_dep & (1 << j)) {
6361 arg++;
6362 if (arg != 1)
6363 fprintf(fout, ", ");
91ca764a 6364 if (fp->pp != NULL)
6365 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6366 else
6367 fprintf(fout, "int");
6368 fprintf(fout, " a%d/*<%s>*/", arg, regs_r32[j]);
92d715b6 6369 }
6370 }
6371
6372 for (j = 0; j < argc_stack; j++) {
6373 arg++;
6374 if (arg != 1)
6375 fprintf(fout, ", ");
91ca764a 6376 if (fp->pp != NULL) {
6377 fprintf(fout, "%s", fp->pp->arg[arg - 1].type.name);
6378 if (!fp->pp->arg[arg - 1].type.is_ptr)
6379 fprintf(fout, " ");
6380 }
6381 else
6382 fprintf(fout, "int ");
6383 fprintf(fout, "a%d", arg);
92d715b6 6384 }
6385
6386 fprintf(fout, ");\n");
6387 }
6388}
6389
9af2d373 6390static void output_hdr(FILE *fout)
6391{
5fa1256f 6392 static const char *lmod_c_names[] = {
6393 [OPLM_UNSPEC] = "???",
6394 [OPLM_BYTE] = "uint8_t",
6395 [OPLM_WORD] = "uint16_t",
6396 [OPLM_DWORD] = "uint32_t",
6397 [OPLM_QWORD] = "uint64_t",
6398 };
6399 const struct scanned_var *var;
ebc4dc43 6400 struct func_prototype *fp;
c0de9015 6401 char line[256] = { 0, };
ebc4dc43 6402 char name[256];
9af2d373 6403 int i;
6404
ebc4dc43 6405 // add stuff from headers
6406 for (i = 0; i < pp_cache_size; i++) {
6407 if (pp_cache[i].is_cinc && !pp_cache[i].is_stdcall)
6408 snprintf(name, sizeof(name), "_%s", pp_cache[i].name);
6409 else
6410 snprintf(name, sizeof(name), "%s", pp_cache[i].name);
6411 fp = hg_fp_add(name);
6412 fp->pp = &pp_cache[i];
6413 fp->argc_stack = fp->pp->argc_stack;
6414 fp->is_stdcall = fp->pp->is_stdcall;
6415 fp->regmask_dep = get_pp_arg_regmask(fp->pp);
6416 fp->has_ret = !IS(fp->pp->ret_type.name, "void");
6417 }
6418
9af2d373 6419 // resolve deps
6420 qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_name);
6421 for (i = 0; i < hg_fp_cnt; i++)
6422 hg_fp_resolve_deps(&hg_fp[i]);
6423
6424 // note: messes up .proto ptr, don't use
6425 //qsort(hg_fp, hg_fp_cnt, sizeof(hg_fp[0]), hg_fp_cmp_id);
6426
5fa1256f 6427 // output variables
6428 for (i = 0; i < hg_var_cnt; i++) {
6429 var = &hg_vars[i];
6430
4e81a3a2 6431 if (var->pp != NULL)
6432 // part of seed
6433 continue;
c0de9015 6434 else if (var->is_c_str)
61e29183 6435 fprintf(fout, "extern %-8s %s[];", "char", var->name);
6436 else
6437 fprintf(fout, "extern %-8s %s;",
6438 lmod_c_names[var->lmod], var->name);
5fa1256f 6439
6440 if (var->is_seeded)
6441 fprintf(fout, " // seeded");
6442 fprintf(fout, "\n");
6443 }
6444
6445 fprintf(fout, "\n");
6446
6447 // output function prototypes
9af2d373 6448 output_hdr_fp(fout, hg_fp, hg_fp_cnt);
c0de9015 6449
4e81a3a2 6450 // seed passthrough
6451 fprintf(fout, "\n// - seed -\n");
c0de9015 6452
6453 rewind(g_fhdr);
4e81a3a2 6454 while (fgets(line, sizeof(line), g_fhdr))
6455 fwrite(line, 1, strlen(line), fout);
9af2d373 6456}
6457
61e29183 6458// '=' needs special treatment
6459// also ' quote
bfa4a6ee 6460static char *next_word_s(char *w, size_t wsize, char *s)
6461{
61e29183 6462 size_t i;
bfa4a6ee 6463
61e29183 6464 s = sskip(s);
bfa4a6ee 6465
61e29183 6466 i = 0;
6467 if (*s == '\'') {
6468 w[0] = s[0];
6469 for (i = 1; i < wsize - 1; i++) {
6470 if (s[i] == 0) {
6471 printf("warning: missing closing quote: \"%s\"\n", s);
6472 break;
6473 }
6474 if (s[i] == '\'')
6475 break;
6476 w[i] = s[i];
6477 }
6478 }
bfa4a6ee 6479
61e29183 6480 for (; i < wsize - 1; i++) {
6481 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
6482 break;
6483 w[i] = s[i];
6484 }
6485 w[i] = 0;
6486
6487 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
6488 printf("warning: '%s' truncated\n", w);
bfa4a6ee 6489
61e29183 6490 return s + i;
bfa4a6ee 6491}
6492
5fa1256f 6493static void scan_variables(FILE *fasm)
6494{
5fa1256f 6495 struct scanned_var *var;
6496 char line[256] = { 0, };
61e29183 6497 char words[3][256];
5fa1256f 6498 char *p = NULL;
6499 int wordc;
61e29183 6500 int l;
5fa1256f 6501
6502 while (!feof(fasm))
6503 {
6504 // skip to next data section
6505 while (my_fgets(line, sizeof(line), fasm))
6506 {
6507 asmln++;
6508
6509 p = sskip(line);
6510 if (*p == 0 || *p == ';')
6511 continue;
6512
6513 p = sskip(next_word_s(words[0], sizeof(words[0]), p));
6514 if (*p == 0 || *p == ';')
6515 continue;
6516
6517 if (*p != 's' || !IS_START(p, "segment para public"))
6518 continue;
6519
6520 break;
6521 }
6522
6523 if (p == NULL || !IS_START(p, "segment para public"))
6524 break;
6525 p = sskip(p + 19);
6526
6527 if (!IS_START(p, "'DATA'"))
6528 continue;
6529
6530 // now process it
6531 while (my_fgets(line, sizeof(line), fasm))
6532 {
6533 asmln++;
6534
6535 p = line;
6536 if (my_isblank(*p))
6537 continue;
6538
6539 p = sskip(p);
6540 if (*p == 0 || *p == ';')
6541 continue;
6542
6543 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6544 words[wordc][0] = 0;
6545 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6546 if (*p == 0 || *p == ';') {
6547 wordc++;
6548 break;
6549 }
6550 }
6551
6552 if (wordc == 2 && IS(words[1], "ends"))
6553 break;
61e29183 6554 if (wordc < 2)
6555 continue;
5fa1256f 6556
9ea60b8d 6557 if (IS_START(words[0], "__IMPORT_DESCRIPTOR_")) {
6558 // when this starts, we don't need anything from this section
6559 break;
6560 }
6561
5fa1256f 6562 if ((hg_var_cnt & 0xff) == 0) {
6563 hg_vars = realloc(hg_vars, sizeof(hg_vars[0])
6564 * (hg_var_cnt + 0x100));
6565 my_assert_not(hg_vars, NULL);
6566 memset(hg_vars + hg_var_cnt, 0, sizeof(hg_vars[0]) * 0x100);
6567 }
6568
6569 var = &hg_vars[hg_var_cnt++];
6570 snprintf(var->name, sizeof(var->name), "%s", words[0]);
6571
6572 // maybe already in seed header?
c0de9015 6573 var->pp = proto_parse(g_fhdr, var->name, 1);
6574 if (var->pp != NULL) {
6575 if (var->pp->is_fptr) {
5fa1256f 6576 var->lmod = OPLM_DWORD;
6577 //var->is_ptr = 1;
6578 }
c0de9015 6579 else if (var->pp->is_func)
6580 aerr("func?\n");
6581 else if (!guess_lmod_from_c_type(&var->lmod, &var->pp->type))
5fa1256f 6582 aerr("unhandled C type '%s' for '%s'\n",
c0de9015 6583 var->pp->type.name, var->name);
5fa1256f 6584
6585 var->is_seeded = 1;
6586 continue;
6587 }
6588
6589 if (IS(words[1], "dd"))
6590 var->lmod = OPLM_DWORD;
6591 else if (IS(words[1], "dw"))
6592 var->lmod = OPLM_WORD;
61e29183 6593 else if (IS(words[1], "db")) {
5fa1256f 6594 var->lmod = OPLM_BYTE;
61e29183 6595 if (wordc >= 3 && (l = strlen(words[2])) > 4) {
6596 if (words[2][0] == '\'' && IS(words[2] + l - 2, ",0"))
6597 var->is_c_str = 1;
6598 }
6599 }
5fa1256f 6600 else if (IS(words[1], "dq"))
6601 var->lmod = OPLM_QWORD;
6602 //else if (IS(words[1], "dt"))
6603 else
6604 aerr("type '%s' not known\n", words[1]);
6605 }
6606 }
6607
6608 rewind(fasm);
6609 asmln = 0;
6610}
6611
6612static void set_label(int i, const char *name)
6613{
6614 const char *p;
6615 int len;
6616
6617 len = strlen(name);
6618 p = strchr(name, ':');
6619 if (p != NULL)
6620 len = p - name;
6621
6622 if (g_labels[i] != NULL && !IS_START(g_labels[i], "algn_"))
6623 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
6624 g_labels[i] = realloc(g_labels[i], len + 1);
6625 my_assert_not(g_labels[i], NULL);
6626 memcpy(g_labels[i], name, len);
6627 g_labels[i][len] = 0;
6628}
6629
e56ab892 6630struct chunk_item {
6631 char *name;
6632 long fptr;
de50b98b 6633 int asmln;
e56ab892 6634};
6635
cdfaeed7 6636static struct chunk_item *func_chunks;
6637static int func_chunk_cnt;
6638static int func_chunk_alloc;
6639
6640static void add_func_chunk(FILE *fasm, const char *name, int line)
6641{
6642 if (func_chunk_cnt >= func_chunk_alloc) {
6643 func_chunk_alloc *= 2;
6644 func_chunks = realloc(func_chunks,
6645 func_chunk_alloc * sizeof(func_chunks[0]));
6646 my_assert_not(func_chunks, NULL);
6647 }
6648 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
6649 func_chunks[func_chunk_cnt].name = strdup(name);
6650 func_chunks[func_chunk_cnt].asmln = line;
6651 func_chunk_cnt++;
6652}
6653
e56ab892 6654static int cmp_chunks(const void *p1, const void *p2)
6655{
6656 const struct chunk_item *c1 = p1, *c2 = p2;
6657 return strcmp(c1->name, c2->name);
6658}
6659
bfa4a6ee 6660static int cmpstringp(const void *p1, const void *p2)
6661{
6662 return strcmp(*(char * const *)p1, *(char * const *)p2);
6663}
6664
cdfaeed7 6665static void scan_ahead(FILE *fasm)
6666{
6667 char words[2][256];
6668 char line[256];
6669 long oldpos;
6670 int oldasmln;
6671 int wordc;
6672 char *p;
6673 int i;
6674
6675 oldpos = ftell(fasm);
6676 oldasmln = asmln;
6677
5fa1256f 6678 while (my_fgets(line, sizeof(line), fasm))
cdfaeed7 6679 {
6680 wordc = 0;
6681 asmln++;
6682
6683 p = sskip(line);
6684 if (*p == 0)
6685 continue;
6686
6687 if (*p == ';')
6688 {
6689 // get rid of random tabs
6690 for (i = 0; line[i] != 0; i++)
6691 if (line[i] == '\t')
6692 line[i] = ' ';
6693
6694 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6695 {
6696 p += 30;
6697 next_word(words[0], sizeof(words[0]), p);
6698 if (words[0][0] == 0)
6699 aerr("missing name for func chunk?\n");
6700
6701 add_func_chunk(fasm, words[0], asmln);
6702 }
46b388c2 6703 else if (IS_START(p, "; sctend"))
6704 break;
6705
cdfaeed7 6706 continue;
6707 } // *p == ';'
6708
6709 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
6710 words[wordc][0] = 0;
6711 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
6712 if (*p == 0 || *p == ';') {
6713 wordc++;
6714 break;
6715 }
6716 }
6717
6718 if (wordc == 2 && IS(words[1], "ends"))
6719 break;
6720 }
6721
6722 fseek(fasm, oldpos, SEEK_SET);
6723 asmln = oldasmln;
6724}
6725
91977a1c 6726int main(int argc, char *argv[])
6727{
06c5d854 6728 FILE *fout, *fasm, *frlist;
4c45fa73 6729 struct parsed_data *pd = NULL;
6730 int pd_alloc = 0;
6731 char **rlist = NULL;
6732 int rlist_len = 0;
6733 int rlist_alloc = 0;
e56ab892 6734 int func_chunks_used = 0;
6735 int func_chunks_sorted = 0;
e56ab892 6736 int func_chunk_i = -1;
6737 long func_chunk_ret = 0;
de50b98b 6738 int func_chunk_ret_ln = 0;
cdfaeed7 6739 int scanned_ahead = 0;
91977a1c 6740 char line[256];
a2c1d768 6741 char words[20][256];
4c45fa73 6742 enum opr_lenmod lmod;
ddaf8bd7 6743 char *sctproto = NULL;
91977a1c 6744 int in_func = 0;
4c45fa73 6745 int pending_endp = 0;
bfa4a6ee 6746 int skip_func = 0;
940e8e66 6747 int skip_warned = 0;
91977a1c 6748 int eq_alloc;
bfa4a6ee 6749 int verbose = 0;
1f84f6b3 6750 int multi_seg = 0;
46b388c2 6751 int end = 0;
bfa4a6ee 6752 int arg_out;
89ff3147 6753 int arg;
91977a1c 6754 int pi = 0;
e56ab892 6755 int i, j;
6756 int ret, len;
91977a1c 6757 char *p;
6758 int wordc;
6759
89ff3147 6760 for (arg = 1; arg < argc; arg++) {
6761 if (IS(argv[arg], "-v"))
6762 verbose = 1;
6763 else if (IS(argv[arg], "-rf"))
6764 g_allow_regfunc = 1;
1f84f6b3 6765 else if (IS(argv[arg], "-m"))
6766 multi_seg = 1;
92d715b6 6767 else if (IS(argv[arg], "-hdr"))
9af2d373 6768 g_header_mode = g_quiet_pp = g_allow_regfunc = 1;
89ff3147 6769 else
6770 break;
bfa4a6ee 6771 }
6772
6773 if (argc < arg + 3) {
315b77eb 6774 printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdr.h> [rlist]*\n"
6775 "%s -hdr <out.h> <.asm> <seed.h> [rlist]*\n"
6776 "options:\n"
6777 " -hdr - header generation mode\n"
6778 " -rf - allow unannotated indirect calls\n"
6779 " -m - allow multiple .text sections\n"
6780 "[rlist] is a file with function names to skip,"
6781 " one per line\n",
92d715b6 6782 argv[0], argv[0]);
91977a1c 6783 return 1;
6784 }
6785
bfa4a6ee 6786 arg_out = arg++;
91977a1c 6787
bfa4a6ee 6788 asmfn = argv[arg++];
91977a1c 6789 fasm = fopen(asmfn, "r");
6790 my_assert_not(fasm, NULL);
6791
bfa4a6ee 6792 hdrfn = argv[arg++];
06c5d854 6793 g_fhdr = fopen(hdrfn, "r");
6794 my_assert_not(g_fhdr, NULL);
bfa4a6ee 6795
6796 rlist_alloc = 64;
6797 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
6798 my_assert_not(rlist, NULL);
6799 // needs special handling..
6800 rlist[rlist_len++] = "__alloca_probe";
6801
e56ab892 6802 func_chunk_alloc = 32;
6803 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
6804 my_assert_not(func_chunks, NULL);
6805
a2c1d768 6806 memset(words, 0, sizeof(words));
6807
bfa4a6ee 6808 for (; arg < argc; arg++) {
6809 frlist = fopen(argv[arg], "r");
6810 my_assert_not(frlist, NULL);
6811
5fa1256f 6812 while (my_fgets(line, sizeof(line), frlist)) {
bfa4a6ee 6813 p = sskip(line);
1cd4a663 6814 if (*p == 0 || *p == ';')
6815 continue;
6816 if (*p == '#') {
89ff3147 6817 if (IS_START(p, "#if 0")
6818 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
6819 {
1cd4a663 6820 skip_func = 1;
89ff3147 6821 }
1cd4a663 6822 else if (IS_START(p, "#endif"))
6823 skip_func = 0;
6824 continue;
6825 }
6826 if (skip_func)
bfa4a6ee 6827 continue;
6828
6829 p = next_word(words[0], sizeof(words[0]), p);
6830 if (words[0][0] == 0)
6831 continue;
6832
6833 if (rlist_len >= rlist_alloc) {
6834 rlist_alloc = rlist_alloc * 2 + 64;
6835 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
6836 my_assert_not(rlist, NULL);
6837 }
6838 rlist[rlist_len++] = strdup(words[0]);
6839 }
1cd4a663 6840 skip_func = 0;
bfa4a6ee 6841
6842 fclose(frlist);
6843 frlist = NULL;
6844 }
6845
6846 if (rlist_len > 0)
6847 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
6848
6849 fout = fopen(argv[arg_out], "w");
91977a1c 6850 my_assert_not(fout, NULL);
6851
6852 eq_alloc = 128;
6853 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
6854 my_assert_not(g_eqs, NULL);
6855
4c45fa73 6856 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
6857 g_label_refs[i].i = -1;
6858 g_label_refs[i].next = NULL;
6859 }
6860
5fa1256f 6861 if (g_header_mode)
6862 scan_variables(fasm);
6863
6864 while (my_fgets(line, sizeof(line), fasm))
91977a1c 6865 {
4c45fa73 6866 wordc = 0;
91977a1c 6867 asmln++;
6868
6869 p = sskip(line);
1bafb621 6870 if (*p == 0)
91977a1c 6871 continue;
6872
de50b98b 6873 // get rid of random tabs
6874 for (i = 0; line[i] != 0; i++)
6875 if (line[i] == '\t')
6876 line[i] = ' ';
6877
e56ab892 6878 if (*p == ';')
6879 {
e56ab892 6880 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
6881 goto do_pending_endp; // eww..
6882
6883 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
6884 {
6885 static const char *attrs[] = {
6886 "bp-based frame",
6887 "library function",
6888 "static",
6889 "noreturn",
6890 "thunk",
6891 "fpd=",
6892 };
6893
6894 // parse IDA's attribute-list comment
6895 g_ida_func_attr = 0;
6896 p = sskip(p + 13);
6897
6898 for (; *p != 0; p = sskip(p)) {
6899 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
6900 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
6901 g_ida_func_attr |= 1 << i;
6902 p += strlen(attrs[i]);
6903 break;
6904 }
6905 }
6906 if (i == ARRAY_SIZE(attrs)) {
6907 anote("unparsed IDA attr: %s\n", p);
1bafb621 6908 break;
6909 }
e56ab892 6910 if (IS(attrs[i], "fpd=")) {
6911 p = next_word(words[0], sizeof(words[0]), p);
6912 // ignore for now..
6913 }
1bafb621 6914 }
e56ab892 6915 }
6916 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
6917 {
6918 p += 30;
6919 next_word(words[0], sizeof(words[0]), p);
6920 if (words[0][0] == 0)
cdfaeed7 6921 aerr("missing name for func chunk?\n");
6922
6923 if (!scanned_ahead) {
6924 add_func_chunk(fasm, words[0], asmln);
6925 func_chunks_sorted = 0;
e56ab892 6926 }
e56ab892 6927 }
6928 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
6929 {
6930 if (func_chunk_i >= 0) {
6931 if (func_chunk_i < func_chunk_cnt
6932 && IS(func_chunks[func_chunk_i].name, g_func))
6933 {
6934 // move on to next chunk
6935 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
6936 if (ret)
6937 aerr("seek failed for '%s' chunk #%d\n",
6938 g_func, func_chunk_i);
de50b98b 6939 asmln = func_chunks[func_chunk_i].asmln;
e56ab892 6940 func_chunk_i++;
6941 }
6942 else {
6943 if (func_chunk_ret == 0)
6944 aerr("no return from chunk?\n");
6945 fseek(fasm, func_chunk_ret, SEEK_SET);
de50b98b 6946 asmln = func_chunk_ret_ln;
e56ab892 6947 func_chunk_ret = 0;
6948 pending_endp = 1;
6949 }
1bafb621 6950 }
e56ab892 6951 }
6952 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
6953 func_chunks_used = 1;
6954 p += 20;
6955 if (IS_START(g_func, "sub_")) {
6956 unsigned long addr = strtoul(p, NULL, 16);
6957 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
cdfaeed7 6958 if (addr > f_addr && !scanned_ahead) {
94d447fb 6959 anote("scan_ahead caused by '%s', addr %lx\n",
6960 g_func, addr);
cdfaeed7 6961 scan_ahead(fasm);
6962 scanned_ahead = 1;
6963 func_chunks_sorted = 0;
6964 }
1bafb621 6965 }
6966 }
6967 continue;
e56ab892 6968 } // *p == ';'
1bafb621 6969
06c5d854 6970parse_words:
a2c1d768 6971 for (i = wordc; i < ARRAY_SIZE(words); i++)
6972 words[i][0] = 0;
cdfaeed7 6973 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
bfa4a6ee 6974 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
91977a1c 6975 if (*p == 0 || *p == ';') {
6976 wordc++;
6977 break;
6978 }
6979 }
a2c1d768 6980 if (*p != 0 && *p != ';')
6981 aerr("too many words\n");
91977a1c 6982
06c5d854 6983 // alow asm patches in comments
ddaf8bd7 6984 if (*p == ';') {
6985 if (IS_START(p, "; sctpatch:")) {
6986 p = sskip(p + 11);
6987 if (*p == 0 || *p == ';')
6988 continue;
6989 goto parse_words; // lame
6990 }
6991 if (IS_START(p, "; sctproto:")) {
6992 sctproto = strdup(p + 11);
6993 }
46b388c2 6994 else if (IS_START(p, "; sctend")) {
6995 end = 1;
6996 if (!pending_endp)
6997 break;
6998 }
06c5d854 6999 }
7000
91977a1c 7001 if (wordc == 0) {
7002 // shouldn't happen
7003 awarn("wordc == 0?\n");
7004 continue;
7005 }
7006
7007 // don't care about this:
7008 if (words[0][0] == '.'
7009 || IS(words[0], "include")
7010 || IS(words[0], "assume") || IS(words[1], "segment")
7011 || IS(words[0], "align"))
7012 {
7013 continue;
7014 }
7015
4c45fa73 7016do_pending_endp:
7017 // do delayed endp processing to collect switch jumptables
7018 if (pending_endp) {
30c8c549 7019 if (in_func && !g_skip_func && !end && wordc >= 2
4c45fa73 7020 && ((words[0][0] == 'd' && words[0][2] == 0)
7021 || (words[1][0] == 'd' && words[1][2] == 0)))
7022 {
7023 i = 1;
7024 if (words[1][0] == 'd' && words[1][2] == 0) {
7025 // label
7026 if (g_func_pd_cnt >= pd_alloc) {
7027 pd_alloc = pd_alloc * 2 + 16;
7028 g_func_pd = realloc(g_func_pd,
7029 sizeof(g_func_pd[0]) * pd_alloc);
7030 my_assert_not(g_func_pd, NULL);
7031 }
7032 pd = &g_func_pd[g_func_pd_cnt];
7033 g_func_pd_cnt++;
7034 memset(pd, 0, sizeof(*pd));
7035 strcpy(pd->label, words[0]);
7036 pd->type = OPT_CONST;
7037 pd->lmod = lmod_from_directive(words[1]);
7038 i = 2;
7039 }
7040 else {
da87ae38 7041 if (pd == NULL) {
7042 if (verbose)
7043 anote("skipping alignment byte?\n");
7044 continue;
7045 }
4c45fa73 7046 lmod = lmod_from_directive(words[0]);
7047 if (lmod != pd->lmod)
7048 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
7049 }
7050
7051 if (pd->count_alloc < pd->count + wordc) {
7052 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
7053 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
7054 my_assert_not(pd->d, NULL);
7055 }
7056 for (; i < wordc; i++) {
7057 if (IS(words[i], "offset")) {
7058 pd->type = OPT_OFFSET;
7059 i++;
7060 }
7061 p = strchr(words[i], ',');
7062 if (p != NULL)
7063 *p = 0;
7064 if (pd->type == OPT_OFFSET)
7065 pd->d[pd->count].u.label = strdup(words[i]);
7066 else
7067 pd->d[pd->count].u.val = parse_number(words[i]);
7068 pd->d[pd->count].bt_i = -1;
7069 pd->count++;
7070 }
7071 continue;
7072 }
7073
30c8c549 7074 if (in_func && !g_skip_func) {
9af2d373 7075 if (g_header_mode)
92d715b6 7076 gen_hdr(g_func, pi);
7077 else
7078 gen_func(fout, g_fhdr, g_func, pi);
7079 }
4c45fa73 7080
7081 pending_endp = 0;
7082 in_func = 0;
7083 g_ida_func_attr = 0;
7084 skip_warned = 0;
30c8c549 7085 g_skip_func = 0;
4c45fa73 7086 g_func[0] = 0;
e56ab892 7087 func_chunks_used = 0;
7088 func_chunk_i = -1;
4c45fa73 7089 if (pi != 0) {
7090 memset(&ops, 0, pi * sizeof(ops[0]));
d7857c3a 7091 clear_labels(pi);
4c45fa73 7092 pi = 0;
7093 }
7094 g_eqcnt = 0;
7095 for (i = 0; i < g_func_pd_cnt; i++) {
7096 pd = &g_func_pd[i];
7097 if (pd->type == OPT_OFFSET) {
7098 for (j = 0; j < pd->count; j++)
7099 free(pd->d[j].u.label);
7100 }
7101 free(pd->d);
7102 pd->d = NULL;
7103 }
7104 g_func_pd_cnt = 0;
7105 pd = NULL;
46b388c2 7106
7107 if (end)
7108 break;
4c45fa73 7109 if (wordc == 0)
7110 continue;
7111 }
7112
91977a1c 7113 if (IS(words[1], "proc")) {
7114 if (in_func)
7115 aerr("proc '%s' while in_func '%s'?\n",
7116 words[0], g_func);
bfa4a6ee 7117 p = words[0];
ddaf8bd7 7118 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
30c8c549 7119 g_skip_func = 1;
91977a1c 7120 strcpy(g_func, words[0]);
d4e3b5db 7121 set_label(0, words[0]);
91977a1c 7122 in_func = 1;
7123 continue;
7124 }
7125
e56ab892 7126 if (IS(words[1], "endp"))
7127 {
91977a1c 7128 if (!in_func)
7129 aerr("endp '%s' while not in_func?\n", words[0]);
7130 if (!IS(g_func, words[0]))
7131 aerr("endp '%s' while in_func '%s'?\n",
7132 words[0], g_func);
bfa4a6ee 7133
ddaf8bd7 7134 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
7135 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
7136 {
7137 // import jump
30c8c549 7138 g_skip_func = 1;
ddaf8bd7 7139 }
7140
30c8c549 7141 if (!g_skip_func && func_chunks_used) {
e56ab892 7142 // start processing chunks
7143 struct chunk_item *ci, key = { g_func, 0 };
7144
7145 func_chunk_ret = ftell(fasm);
de50b98b 7146 func_chunk_ret_ln = asmln;
e56ab892 7147 if (!func_chunks_sorted) {
7148 qsort(func_chunks, func_chunk_cnt,
7149 sizeof(func_chunks[0]), cmp_chunks);
7150 func_chunks_sorted = 1;
7151 }
7152 ci = bsearch(&key, func_chunks, func_chunk_cnt,
7153 sizeof(func_chunks[0]), cmp_chunks);
7154 if (ci == NULL)
7155 aerr("'%s' needs chunks, but none found\n", g_func);
7156 func_chunk_i = ci - func_chunks;
7157 for (; func_chunk_i > 0; func_chunk_i--)
7158 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
7159 break;
7160
7161 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
7162 if (ret)
7163 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
de50b98b 7164 asmln = func_chunks[func_chunk_i].asmln;
e56ab892 7165 func_chunk_i++;
7166 continue;
7167 }
4c45fa73 7168 pending_endp = 1;
91977a1c 7169 continue;
7170 }
7171
1f84f6b3 7172 if (wordc == 2 && IS(words[1], "ends")) {
46b388c2 7173 if (!multi_seg) {
7174 end = 1;
7175 if (pending_endp)
7176 goto do_pending_endp;
1f84f6b3 7177 break;
46b388c2 7178 }
1f84f6b3 7179
7180 // scan for next text segment
5fa1256f 7181 while (my_fgets(line, sizeof(line), fasm)) {
1f84f6b3 7182 asmln++;
7183 p = sskip(line);
7184 if (*p == 0 || *p == ';')
7185 continue;
7186
7187 if (strstr(p, "segment para public 'CODE' use32"))
7188 break;
7189 }
7190
7191 continue;
7192 }
a2c1d768 7193
bfa4a6ee 7194 p = strchr(words[0], ':');
7195 if (p != NULL) {
d4e3b5db 7196 set_label(pi, words[0]);
bfa4a6ee 7197 continue;
7198 }
7199
30c8c549 7200 if (!in_func || g_skip_func) {
7201 if (!skip_warned && !g_skip_func && g_labels[pi] != NULL) {
bfa4a6ee 7202 if (verbose)
7203 anote("skipping from '%s'\n", g_labels[pi]);
7204 skip_warned = 1;
7205 }
d7857c3a 7206 free(g_labels[pi]);
7207 g_labels[pi] = NULL;
bfa4a6ee 7208 continue;
7209 }
7210
ddaf8bd7 7211 if (wordc > 1 && IS(words[1], "="))
7212 {
91977a1c 7213 if (wordc != 5)
7214 aerr("unhandled equ, wc=%d\n", wordc);
7215 if (g_eqcnt >= eq_alloc) {
7216 eq_alloc *= 2;
7217 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
7218 my_assert_not(g_eqs, NULL);
7219 }
7220
7221 len = strlen(words[0]);
7222 if (len > sizeof(g_eqs[0].name) - 1)
7223 aerr("equ name too long: %d\n", len);
7224 strcpy(g_eqs[g_eqcnt].name, words[0]);
7225
7226 if (!IS(words[3], "ptr"))
7227 aerr("unhandled equ\n");
7228 if (IS(words[2], "dword"))
7229 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
7230 else if (IS(words[2], "word"))
7231 g_eqs[g_eqcnt].lmod = OPLM_WORD;
7232 else if (IS(words[2], "byte"))
7233 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
90307a99 7234 else if (IS(words[2], "qword"))
7235 g_eqs[g_eqcnt].lmod = OPLM_QWORD;
91977a1c 7236 else
7237 aerr("bad lmod: '%s'\n", words[2]);
7238
7239 g_eqs[g_eqcnt].offset = parse_number(words[4]);
7240 g_eqcnt++;
7241 continue;
7242 }
7243
7244 if (pi >= ARRAY_SIZE(ops))
7245 aerr("too many ops\n");
7246
91977a1c 7247 parse_op(&ops[pi], words, wordc);
ddaf8bd7 7248
7249 if (sctproto != NULL) {
8eb12e72 7250 if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
ddaf8bd7 7251 ops[pi].datap = sctproto;
7252 sctproto = NULL;
7253 }
91977a1c 7254 pi++;
91977a1c 7255 }
7256
9af2d373 7257 if (g_header_mode)
92d715b6 7258 output_hdr(fout);
7259
91977a1c 7260 fclose(fout);
7261 fclose(fasm);
06c5d854 7262 fclose(g_fhdr);
91977a1c 7263
7264 return 0;
c36e914d 7265}
91977a1c 7266
7267// vim:ts=2:shiftwidth=2:expandtab