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