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