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