some more stdc syms
[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 && lmod_bytes(po, tmp_lmod)
1500 < lmod_bytes(po, popr->lmod) + (offset & 3))))
1501 {
1502 ferr(po, "bp_arg arg%d/w offset %d and type '%s' is too small\n",
1503 i + 1, offset, g_func_pp->arg[i].type.name);
1504 }
1505 // can't check this because msvc likes to reuse
1506 // arg space for scratch..
1507 //if (popr->is_ptr && popr->lmod != OPLM_DWORD)
1508 // ferr(po, "bp_arg arg%d: non-dword ptr access\n", i + 1);
1509 }
1510 else
1511 {
1512 if (g_stack_fsz == 0)
1513 ferr(po, "stack var access without stackframe\n");
1514 g_stack_frame_used = 1;
1515
1516 sf_ofs = g_stack_fsz + offset;
1517 lim = (ofs_reg[0] != 0) ? -4 : 0;
1518 if (offset > 0 || sf_ofs < lim)
1519 ferr(po, "bp_stack offset %d/%d\n", offset, g_stack_fsz);
1520
1521 if (is_lea)
1522 prefix = "(u32)&";
1523 else
1524 prefix = cast;
1525
1526 switch (popr->lmod)
1527 {
1528 case OPLM_BYTE:
1529 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1530 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1531 break;
1532
1533 case OPLM_WORD:
1534 if ((sf_ofs & 1) || ofs_reg[0] != 0) {
1535 // known unaligned or possibly unaligned
1536 strcat(g_comment, " unaligned");
1537 if (prefix[0] == 0)
1538 prefix = "*(u16 *)&";
1539 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1540 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1541 break;
1542 }
1543 snprintf(buf, buf_size, "%ssf.w[%d]", prefix, sf_ofs / 2);
1544 break;
1545
1546 case OPLM_DWORD:
1547 if ((sf_ofs & 3) || ofs_reg[0] != 0) {
1548 // known unaligned or possibly unaligned
1549 strcat(g_comment, " unaligned");
1550 if (prefix[0] == 0)
1551 prefix = "*(u32 *)&";
1552 snprintf(buf, buf_size, "%ssf.b[%d%s%s]",
1553 prefix, sf_ofs, ofs_reg[0] ? "+" : "", ofs_reg);
1554 break;
1555 }
1556 snprintf(buf, buf_size, "%ssf.d[%d]", prefix, sf_ofs / 4);
1557 break;
1558
1559 default:
1560 ferr(po, "bp_stack bad lmod: %d\n", popr->lmod);
1561 }
1562 }
1563
1564 return retval;
1565}
1566
1567static void check_func_pp(struct parsed_op *po,
1568 const struct parsed_proto *pp, const char *pfx)
1569{
1570 enum opr_lenmod tmp_lmod;
1571 char buf[256];
1572 int ret, i;
1573
1574 if (pp->argc_reg != 0) {
1575 if (/*!g_allow_regfunc &&*/ !pp->is_fastcall) {
1576 pp_print(buf, sizeof(buf), pp);
1577 ferr(po, "%s: unexpected reg arg in icall: %s\n", pfx, buf);
1578 }
1579 if (pp->argc_stack > 0 && pp->argc_reg != 2)
1580 ferr(po, "%s: %d reg arg(s) with %d stack arg(s)\n",
1581 pfx, pp->argc_reg, pp->argc_stack);
1582 }
1583
1584 // fptrs must use 32bit args, callsite might have no information and
1585 // lack a cast to smaller types, which results in incorrectly masked
1586 // args passed (callee may assume masked args, it does on ARM)
1587 if (!pp->is_oslib) {
1588 for (i = 0; i < pp->argc; i++) {
1589 ret = guess_lmod_from_c_type(&tmp_lmod, &pp->arg[i].type);
1590 if (ret && tmp_lmod != OPLM_DWORD)
1591 ferr(po, "reference to %s with arg%d '%s'\n", pp->name,
1592 i + 1, pp->arg[i].type.name);
1593 }
1594 }
1595}
1596
1597static const char *check_label_read_ref(struct parsed_op *po,
1598 const char *name)
1599{
1600 const struct parsed_proto *pp;
1601
1602 pp = proto_parse(g_fhdr, name, 0);
1603 if (pp == NULL)
1604 ferr(po, "proto_parse failed for ref '%s'\n", name);
1605
1606 if (pp->is_func)
1607 check_func_pp(po, pp, "ref");
1608
1609 return pp->name;
1610}
1611
1612static char *out_src_opr(char *buf, size_t buf_size,
1613 struct parsed_op *po, struct parsed_opr *popr, const char *cast,
1614 int is_lea)
1615{
1616 char tmp1[256], tmp2[256];
1617 char expr[256];
1618 const char *name;
1619 char *p;
1620 int ret;
1621
1622 if (cast == NULL)
1623 cast = "";
1624
1625 switch (popr->type) {
1626 case OPT_REG:
1627 if (is_lea)
1628 ferr(po, "lea from reg?\n");
1629
1630 switch (popr->lmod) {
1631 case OPLM_DWORD:
1632 snprintf(buf, buf_size, "%s%s", cast, opr_reg_p(po, popr));
1633 break;
1634 case OPLM_WORD:
1635 snprintf(buf, buf_size, "%s%s",
1636 simplify_cast(cast, "(u16)"), opr_reg_p(po, popr));
1637 break;
1638 case OPLM_BYTE:
1639 if (popr->name[1] == 'h') // XXX..
1640 snprintf(buf, buf_size, "%s(%s >> 8)",
1641 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1642 else
1643 snprintf(buf, buf_size, "%s%s",
1644 simplify_cast(cast, "(u8)"), opr_reg_p(po, popr));
1645 break;
1646 default:
1647 ferr(po, "invalid src lmod: %d\n", popr->lmod);
1648 }
1649 break;
1650
1651 case OPT_REGMEM:
1652 if (is_stack_access(po, popr)) {
1653 stack_frame_access(po, popr, buf, buf_size,
1654 popr->name, cast, 1, is_lea);
1655 break;
1656 }
1657
1658 strcpy(expr, popr->name);
1659 if (strchr(expr, '[')) {
1660 // special case: '[' can only be left for label[reg] form
1661 ret = sscanf(expr, "%[^[][%[^]]]", tmp1, tmp2);
1662 if (ret != 2)
1663 ferr(po, "parse failure for '%s'\n", expr);
1664 if (tmp1[0] == '(') {
1665 // (off_4FFF50+3)[eax]
1666 p = strchr(tmp1 + 1, ')');
1667 if (p == NULL || p[1] != 0)
1668 ferr(po, "parse failure (2) for '%s'\n", expr);
1669 *p = 0;
1670 memmove(tmp1, tmp1 + 1, strlen(tmp1));
1671 }
1672 snprintf(expr, sizeof(expr), "(u32)&%s + %s", tmp1, tmp2);
1673 }
1674
1675 // XXX: do we need more parsing?
1676 if (is_lea) {
1677 snprintf(buf, buf_size, "%s", expr);
1678 break;
1679 }
1680
1681 snprintf(buf, buf_size, "%s(%s)",
1682 simplify_cast(cast, lmod_cast_u_ptr(po, popr->lmod)), expr);
1683 break;
1684
1685 case OPT_LABEL:
1686 name = check_label_read_ref(po, popr->name);
1687 if (cast[0] == 0 && popr->is_ptr)
1688 cast = "(u32)";
1689
1690 if (is_lea)
1691 snprintf(buf, buf_size, "(u32)&%s", name);
1692 else if (popr->size_lt)
1693 snprintf(buf, buf_size, "%s%s%s%s", cast,
1694 lmod_cast_u_ptr(po, popr->lmod),
1695 popr->is_array ? "" : "&", name);
1696 else
1697 snprintf(buf, buf_size, "%s%s%s", cast, name,
1698 popr->is_array ? "[0]" : "");
1699 break;
1700
1701 case OPT_OFFSET:
1702 name = check_label_read_ref(po, popr->name);
1703 if (cast[0] == 0)
1704 cast = "(u32)";
1705 if (is_lea)
1706 ferr(po, "lea an offset?\n");
1707 snprintf(buf, buf_size, "%s&%s", cast, name);
1708 break;
1709
1710 case OPT_CONST:
1711 if (is_lea)
1712 ferr(po, "lea from const?\n");
1713
1714 printf_number(tmp1, sizeof(tmp1), popr->val);
1715 if (popr->val == 0 && strchr(cast, '*'))
1716 snprintf(buf, buf_size, "NULL");
1717 else
1718 snprintf(buf, buf_size, "%s%s",
1719 simplify_cast_num(cast, popr->val), tmp1);
1720 break;
1721
1722 default:
1723 ferr(po, "invalid src type: %d\n", popr->type);
1724 }
1725
1726 return buf;
1727}
1728
1729// note: may set is_ptr (we find that out late for ebp frame..)
1730static char *out_dst_opr(char *buf, size_t buf_size,
1731 struct parsed_op *po, struct parsed_opr *popr)
1732{
1733 switch (popr->type) {
1734 case OPT_REG:
1735 switch (popr->lmod) {
1736 case OPLM_DWORD:
1737 snprintf(buf, buf_size, "%s", opr_reg_p(po, popr));
1738 break;
1739 case OPLM_WORD:
1740 // ugh..
1741 snprintf(buf, buf_size, "LOWORD(%s)", opr_reg_p(po, popr));
1742 break;
1743 case OPLM_BYTE:
1744 // ugh..
1745 if (popr->name[1] == 'h') // XXX..
1746 snprintf(buf, buf_size, "BYTE1(%s)", opr_reg_p(po, popr));
1747 else
1748 snprintf(buf, buf_size, "LOBYTE(%s)", opr_reg_p(po, popr));
1749 break;
1750 default:
1751 ferr(po, "invalid dst lmod: %d\n", popr->lmod);
1752 }
1753 break;
1754
1755 case OPT_REGMEM:
1756 if (is_stack_access(po, popr)) {
1757 stack_frame_access(po, popr, buf, buf_size,
1758 popr->name, "", 0, 0);
1759 break;
1760 }
1761
1762 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1763
1764 case OPT_LABEL:
1765 if (popr->size_mismatch)
1766 snprintf(buf, buf_size, "%s%s%s",
1767 lmod_cast_u_ptr(po, popr->lmod),
1768 popr->is_array ? "" : "&", popr->name);
1769 else
1770 snprintf(buf, buf_size, "%s%s", popr->name,
1771 popr->is_array ? "[0]" : "");
1772 break;
1773
1774 default:
1775 ferr(po, "invalid dst type: %d\n", popr->type);
1776 }
1777
1778 return buf;
1779}
1780
1781static char *out_src_opr_u32(char *buf, size_t buf_size,
1782 struct parsed_op *po, struct parsed_opr *popr)
1783{
1784 return out_src_opr(buf, buf_size, po, popr, NULL, 0);
1785}
1786
1787static void out_test_for_cc(char *buf, size_t buf_size,
1788 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv,
1789 enum opr_lenmod lmod, const char *expr)
1790{
1791 const char *cast, *scast;
1792
1793 cast = lmod_cast_u(po, lmod);
1794 scast = lmod_cast_s(po, lmod);
1795
1796 switch (pfo) {
1797 case PFO_Z:
1798 case PFO_BE: // CF=1||ZF=1; CF=0
1799 snprintf(buf, buf_size, "(%s%s %s 0)",
1800 cast, expr, is_inv ? "!=" : "==");
1801 break;
1802
1803 case PFO_S:
1804 case PFO_L: // SF!=OF; OF=0
1805 snprintf(buf, buf_size, "(%s%s %s 0)",
1806 scast, expr, is_inv ? ">=" : "<");
1807 break;
1808
1809 case PFO_LE: // ZF=1||SF!=OF; OF=0
1810 snprintf(buf, buf_size, "(%s%s %s 0)",
1811 scast, expr, is_inv ? ">" : "<=");
1812 break;
1813
1814 default:
1815 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1816 }
1817}
1818
1819static void out_cmp_for_cc(char *buf, size_t buf_size,
1820 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1821{
1822 const char *cast, *scast, *cast_use;
1823 char buf1[256], buf2[256];
1824 enum opr_lenmod lmod;
1825
1826 if (po->operand[0].lmod != po->operand[1].lmod)
1827 ferr(po, "%s: lmod mismatch: %d %d\n", __func__,
1828 po->operand[0].lmod, po->operand[1].lmod);
1829 lmod = po->operand[0].lmod;
1830
1831 cast = lmod_cast_u(po, lmod);
1832 scast = lmod_cast_s(po, lmod);
1833
1834 switch (pfo) {
1835 case PFO_C:
1836 case PFO_Z:
1837 case PFO_BE: // !a
1838 cast_use = cast;
1839 break;
1840
1841 case PFO_S:
1842 case PFO_L: // !ge
1843 case PFO_LE:
1844 cast_use = scast;
1845 break;
1846
1847 default:
1848 ferr(po, "%s: unhandled parsed_flag_op: %d\n", __func__, pfo);
1849 }
1850
1851 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], cast_use, 0);
1852 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1], cast_use, 0);
1853
1854 switch (pfo) {
1855 case PFO_C:
1856 // note: must be unsigned compare
1857 snprintf(buf, buf_size, "(%s %s %s)",
1858 buf1, is_inv ? ">=" : "<", buf2);
1859 break;
1860
1861 case PFO_Z:
1862 snprintf(buf, buf_size, "(%s %s %s)",
1863 buf1, is_inv ? "!=" : "==", buf2);
1864 break;
1865
1866 case PFO_BE: // !a
1867 // note: must be unsigned compare
1868 snprintf(buf, buf_size, "(%s %s %s)",
1869 buf1, is_inv ? ">" : "<=", buf2);
1870
1871 // annoying case
1872 if (is_inv && lmod == OPLM_BYTE
1873 && po->operand[1].type == OPT_CONST
1874 && po->operand[1].val == 0xff)
1875 {
1876 snprintf(g_comment, sizeof(g_comment), "if %s", buf);
1877 snprintf(buf, buf_size, "(0)");
1878 }
1879 break;
1880
1881 // note: must be signed compare
1882 case PFO_S:
1883 snprintf(buf, buf_size, "(%s(%s - %s) %s 0)",
1884 scast, buf1, buf2, is_inv ? ">=" : "<");
1885 break;
1886
1887 case PFO_L: // !ge
1888 snprintf(buf, buf_size, "(%s %s %s)",
1889 buf1, is_inv ? ">=" : "<", buf2);
1890 break;
1891
1892 case PFO_LE:
1893 snprintf(buf, buf_size, "(%s %s %s)",
1894 buf1, is_inv ? ">" : "<=", buf2);
1895 break;
1896
1897 default:
1898 break;
1899 }
1900}
1901
1902static void out_cmp_test(char *buf, size_t buf_size,
1903 struct parsed_op *po, enum parsed_flag_op pfo, int is_inv)
1904{
1905 char buf1[256], buf2[256], buf3[256];
1906
1907 if (po->op == OP_TEST) {
1908 if (IS(opr_name(po, 0), opr_name(po, 1))) {
1909 out_src_opr_u32(buf3, sizeof(buf3), po, &po->operand[0]);
1910 }
1911 else {
1912 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
1913 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
1914 snprintf(buf3, sizeof(buf3), "(%s & %s)", buf1, buf2);
1915 }
1916 out_test_for_cc(buf, buf_size, po, pfo, is_inv,
1917 po->operand[0].lmod, buf3);
1918 }
1919 else if (po->op == OP_CMP) {
1920 out_cmp_for_cc(buf, buf_size, po, pfo, is_inv);
1921 }
1922 else
1923 ferr(po, "%s: unhandled op: %d\n", __func__, po->op);
1924}
1925
1926static void propagate_lmod(struct parsed_op *po, struct parsed_opr *popr1,
1927 struct parsed_opr *popr2)
1928{
1929 if (popr1->lmod == OPLM_UNSPEC && popr2->lmod == OPLM_UNSPEC)
1930 ferr(po, "missing lmod for both operands\n");
1931
1932 if (popr1->lmod == OPLM_UNSPEC)
1933 popr1->lmod = popr2->lmod;
1934 else if (popr2->lmod == OPLM_UNSPEC)
1935 popr2->lmod = popr1->lmod;
1936 else if (popr1->lmod != popr2->lmod) {
1937 if (popr1->type_from_var) {
1938 popr1->size_mismatch = 1;
1939 if (popr1->lmod < popr2->lmod)
1940 popr1->size_lt = 1;
1941 popr1->lmod = popr2->lmod;
1942 }
1943 else if (popr2->type_from_var) {
1944 popr2->size_mismatch = 1;
1945 if (popr2->lmod < popr1->lmod)
1946 popr2->size_lt = 1;
1947 popr2->lmod = popr1->lmod;
1948 }
1949 else
1950 ferr(po, "conflicting lmods: %d vs %d\n",
1951 popr1->lmod, popr2->lmod);
1952 }
1953}
1954
1955static const char *op_to_c(struct parsed_op *po)
1956{
1957 switch (po->op)
1958 {
1959 case OP_ADD:
1960 case OP_ADC:
1961 return "+";
1962 case OP_SUB:
1963 case OP_SBB:
1964 return "-";
1965 case OP_AND:
1966 return "&";
1967 case OP_OR:
1968 return "|";
1969 case OP_XOR:
1970 return "^";
1971 case OP_SHL:
1972 return "<<";
1973 case OP_SHR:
1974 return ">>";
1975 case OP_MUL:
1976 case OP_IMUL:
1977 return "*";
1978 default:
1979 ferr(po, "op_to_c was supplied with %d\n", po->op);
1980 }
1981}
1982
1983static void op_set_clear_flag(struct parsed_op *po,
1984 enum op_flags flag_set, enum op_flags flag_clear)
1985{
1986 po->flags |= flag_set;
1987 po->flags &= ~flag_clear;
1988}
1989
1990// last op in stream - unconditional branch or ret
1991#define LAST_OP(_i) ((ops[_i].flags & OPF_TAIL) \
1992 || ((ops[_i].flags & (OPF_JMP|OPF_CJMP|OPF_RMD)) == OPF_JMP \
1993 && ops[_i].op != OP_CALL))
1994
1995static int scan_for_pop(int i, int opcnt, const char *reg,
1996 int magic, int depth, int *maxdepth, int do_flags)
1997{
1998 const struct parsed_proto *pp;
1999 struct parsed_op *po;
2000 int ret = 0;
2001 int j;
2002
2003 for (; i < opcnt; i++) {
2004 po = &ops[i];
2005 if (po->cc_scratch == magic)
2006 break; // already checked
2007 po->cc_scratch = magic;
2008
2009 if (po->flags & OPF_TAIL) {
2010 if (po->op == OP_CALL) {
2011 pp = proto_parse(g_fhdr, po->operand[0].name, 0);
2012 if (pp != NULL && pp->is_noreturn)
2013 // no stack cleanup for noreturn
2014 return ret;
2015 }
2016 return -1; // deadend
2017 }
2018
2019 if ((po->flags & OPF_RMD)
2020 || (po->op == OP_PUSH && po->p_argnum != 0)) // arg push
2021 continue;
2022
2023 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2024 if (po->btj != NULL) {
2025 // jumptable
2026 for (j = 0; j < po->btj->count; j++) {
2027 ret |= scan_for_pop(po->btj->d[j].bt_i, opcnt, reg, magic,
2028 depth, maxdepth, do_flags);
2029 if (ret < 0)
2030 return ret; // dead end
2031 }
2032 return ret;
2033 }
2034
2035 if (po->bt_i < 0) {
2036 ferr(po, "dead branch\n");
2037 return -1;
2038 }
2039
2040 if (po->flags & OPF_CJMP) {
2041 ret |= scan_for_pop(po->bt_i, opcnt, reg, magic,
2042 depth, maxdepth, do_flags);
2043 if (ret < 0)
2044 return ret; // dead end
2045 }
2046 else {
2047 i = po->bt_i - 1;
2048 }
2049 continue;
2050 }
2051
2052 if ((po->op == OP_POP || po->op == OP_PUSH)
2053 && po->operand[0].type == OPT_REG
2054 && IS(po->operand[0].name, reg))
2055 {
2056 if (po->op == OP_PUSH && !(po->flags & OPF_FARG)) {
2057 depth++;
2058 if (depth > *maxdepth)
2059 *maxdepth = depth;
2060 if (do_flags)
2061 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2062 }
2063 else if (po->op == OP_POP) {
2064 if (depth == 0) {
2065 if (do_flags)
2066 op_set_clear_flag(po, OPF_RMD, OPF_RSAVE);
2067 return 1;
2068 }
2069 else {
2070 depth--;
2071 if (depth < 0) // should not happen
2072 ferr(po, "fail with depth\n");
2073 if (do_flags)
2074 op_set_clear_flag(po, OPF_RSAVE, OPF_RMD);
2075 }
2076 }
2077 }
2078 }
2079
2080 return ret;
2081}
2082
2083// scan for pop starting from 'ret' op (all paths)
2084static int scan_for_pop_ret(int i, int opcnt, const char *reg,
2085 int flag_set)
2086{
2087 int found = 0;
2088 int j;
2089
2090 for (; i < opcnt; i++) {
2091 if (!(ops[i].flags & OPF_TAIL))
2092 continue;
2093
2094 for (j = i - 1; j >= 0; j--) {
2095 if (ops[j].flags & OPF_RMD)
2096 continue;
2097 if (ops[j].flags & OPF_JMP)
2098 return -1;
2099
2100 if (ops[j].op == OP_POP && ops[j].operand[0].type == OPT_REG
2101 && IS(ops[j].operand[0].name, reg))
2102 {
2103 found = 1;
2104 ops[j].flags |= flag_set;
2105 break;
2106 }
2107
2108 if (g_labels[j][0] != 0)
2109 return -1;
2110 }
2111 }
2112
2113 return found ? 0 : -1;
2114}
2115
2116static void scan_propagate_df(int i, int opcnt)
2117{
2118 struct parsed_op *po = &ops[i];
2119 int j;
2120
2121 for (; i < opcnt; i++) {
2122 po = &ops[i];
2123 if (po->flags & OPF_DF)
2124 return; // already resolved
2125 po->flags |= OPF_DF;
2126
2127 if (po->op == OP_CALL)
2128 ferr(po, "call with DF set?\n");
2129
2130 if (po->flags & OPF_JMP) {
2131 if (po->btj != NULL) {
2132 // jumptable
2133 for (j = 0; j < po->btj->count; j++)
2134 scan_propagate_df(po->btj->d[j].bt_i, opcnt);
2135 return;
2136 }
2137
2138 if (po->bt_i < 0) {
2139 ferr(po, "dead branch\n");
2140 return;
2141 }
2142
2143 if (po->flags & OPF_CJMP)
2144 scan_propagate_df(po->bt_i, opcnt);
2145 else
2146 i = po->bt_i - 1;
2147 continue;
2148 }
2149
2150 if (po->flags & OPF_TAIL)
2151 break;
2152
2153 if (po->op == OP_CLD) {
2154 po->flags |= OPF_RMD;
2155 return;
2156 }
2157 }
2158
2159 ferr(po, "missing DF clear?\n");
2160}
2161
2162// is operand 'opr' modified by parsed_op 'po'?
2163static int is_opr_modified(const struct parsed_opr *opr,
2164 const struct parsed_op *po)
2165{
2166 int mask;
2167
2168 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2169 return 0;
2170
2171 if (opr->type == OPT_REG) {
2172 if (po->op == OP_CALL) {
2173 mask = (1 << xAX) | (1 << xCX) | (1 << xDX);
2174 if ((1 << opr->reg) & mask)
2175 return 1;
2176 else
2177 return 0;
2178 }
2179
2180 if (po->operand[0].type == OPT_REG) {
2181 if (po->regmask_dst & (1 << opr->reg))
2182 return 1;
2183 else
2184 return 0;
2185 }
2186 }
2187
2188 return IS(po->operand[0].name, opr->name);
2189}
2190
2191// is any operand of parsed_op 'po_test' modified by parsed_op 'po'?
2192static int is_any_opr_modified(const struct parsed_op *po_test,
2193 const struct parsed_op *po, int c_mode)
2194{
2195 int mask;
2196 int i;
2197
2198 if ((po->flags & OPF_RMD) || !(po->flags & OPF_DATA))
2199 return 0;
2200
2201 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2202 return 0;
2203
2204 if ((po_test->regmask_src | po_test->regmask_dst) & po->regmask_dst)
2205 return 1;
2206
2207 // in reality, it can wreck any register, but in decompiled C
2208 // version it can only overwrite eax or edx:eax
2209 mask = (1 << xAX) | (1 << xDX);
2210 if (!c_mode)
2211 mask |= 1 << xCX;
2212
2213 if (po->op == OP_CALL
2214 && ((po_test->regmask_src | po_test->regmask_dst) & mask))
2215 return 1;
2216
2217 for (i = 0; i < po_test->operand_cnt; i++)
2218 if (IS(po_test->operand[i].name, po->operand[0].name))
2219 return 1;
2220
2221 return 0;
2222}
2223
2224// scan for any po_test operand modification in range given
2225static int scan_for_mod(struct parsed_op *po_test, int i, int opcnt,
2226 int c_mode)
2227{
2228 if (po_test->operand_cnt == 1 && po_test->operand[0].type == OPT_CONST)
2229 return -1;
2230
2231 for (; i < opcnt; i++) {
2232 if (is_any_opr_modified(po_test, &ops[i], c_mode))
2233 return i;
2234 }
2235
2236 return -1;
2237}
2238
2239// scan for po_test operand[0] modification in range given
2240static int scan_for_mod_opr0(struct parsed_op *po_test,
2241 int i, int opcnt)
2242{
2243 for (; i < opcnt; i++) {
2244 if (is_opr_modified(&po_test->operand[0], &ops[i]))
2245 return i;
2246 }
2247
2248 return -1;
2249}
2250
2251static int scan_for_flag_set(int i, int magic, int *branched,
2252 int *setters, int *setter_cnt)
2253{
2254 struct label_ref *lr;
2255 int ret;
2256
2257 while (i >= 0) {
2258 if (ops[i].cc_scratch == magic) {
2259 ferr(&ops[i], "%s looped\n", __func__);
2260 return -1;
2261 }
2262 ops[i].cc_scratch = magic;
2263
2264 if (g_labels[i][0] != 0) {
2265 *branched = 1;
2266
2267 lr = &g_label_refs[i];
2268 for (; lr->next; lr = lr->next) {
2269 ret = scan_for_flag_set(lr->i, magic,
2270 branched, setters, setter_cnt);
2271 if (ret < 0)
2272 return ret;
2273 }
2274
2275 if (i > 0 && LAST_OP(i - 1)) {
2276 i = lr->i;
2277 continue;
2278 }
2279 ret = scan_for_flag_set(lr->i, magic,
2280 branched, setters, setter_cnt);
2281 if (ret < 0)
2282 return ret;
2283 }
2284 i--;
2285
2286 if (ops[i].flags & OPF_FLAGS) {
2287 setters[*setter_cnt] = i;
2288 (*setter_cnt)++;
2289 return 0;
2290 }
2291
2292 if ((ops[i].flags & (OPF_JMP|OPF_CJMP)) == OPF_JMP)
2293 return -1;
2294 }
2295
2296 return -1;
2297}
2298
2299// scan back for cdq, if anything modifies edx, fail
2300static int scan_for_cdq_edx(int i)
2301{
2302 while (i >= 0) {
2303 if (g_labels[i][0] != 0) {
2304 if (g_label_refs[i].next != NULL)
2305 return -1;
2306 if (i > 0 && LAST_OP(i - 1)) {
2307 i = g_label_refs[i].i;
2308 continue;
2309 }
2310 return -1;
2311 }
2312 i--;
2313
2314 if (ops[i].op == OP_CDQ)
2315 return i;
2316
2317 if (ops[i].regmask_dst & (1 << xDX))
2318 return -1;
2319 }
2320
2321 return -1;
2322}
2323
2324static int scan_for_reg_clear(int i, int reg)
2325{
2326 while (i >= 0) {
2327 if (g_labels[i][0] != 0) {
2328 if (g_label_refs[i].next != NULL)
2329 return -1;
2330 if (i > 0 && LAST_OP(i - 1)) {
2331 i = g_label_refs[i].i;
2332 continue;
2333 }
2334 return -1;
2335 }
2336 i--;
2337
2338 if (ops[i].op == OP_XOR
2339 && ops[i].operand[0].lmod == OPLM_DWORD
2340 && ops[i].operand[0].reg == ops[i].operand[1].reg
2341 && ops[i].operand[0].reg == reg)
2342 return i;
2343
2344 if (ops[i].regmask_dst & (1 << reg))
2345 return -1;
2346 }
2347
2348 return -1;
2349}
2350
2351// scan for positive, constant esp adjust
2352static int scan_for_esp_adjust(int i, int opcnt, int *adj,
2353 int *multipath)
2354{
2355 struct parsed_op *po;
2356 int first_pop = -1;
2357
2358 *adj = *multipath = 0;
2359
2360 for (; i < opcnt; i++) {
2361 po = &ops[i];
2362
2363 if (g_labels[i][0] != 0)
2364 *multipath = 1;
2365
2366 if (po->op == OP_ADD && po->operand[0].reg == xSP) {
2367 if (po->operand[1].type != OPT_CONST)
2368 ferr(&ops[i], "non-const esp adjust?\n");
2369 *adj += po->operand[1].val;
2370 if (*adj & 3)
2371 ferr(&ops[i], "unaligned esp adjust: %x\n", *adj);
2372 return i;
2373 }
2374 else if (po->op == OP_PUSH && !(po->flags & OPF_RMD)) {
2375 //if (first_pop == -1)
2376 // first_pop = -2; // none
2377 *adj -= lmod_bytes(po, po->operand[0].lmod);
2378 }
2379 else if (po->op == OP_POP && !(po->flags & OPF_RMD)) {
2380 // seems like msvc only uses 'pop ecx' for stack realignment..
2381 if (po->operand[0].type != OPT_REG || po->operand[0].reg != xCX)
2382 break;
2383 if (first_pop == -1 && *adj >= 0)
2384 first_pop = i;
2385 *adj += lmod_bytes(po, po->operand[0].lmod);
2386 }
2387 else if (po->flags & (OPF_JMP|OPF_TAIL)) {
2388 if (po->op == OP_JMP && po->btj == NULL) {
2389 i = po->bt_i - 1;
2390 continue;
2391 }
2392 if (po->op != OP_CALL)
2393 break;
2394 if (po->operand[0].type != OPT_LABEL)
2395 break;
2396 if (po->pp != NULL && po->pp->is_stdcall)
2397 break;
2398 }
2399 }
2400
2401 if (first_pop >= 0) {
2402 // probably 'pop ecx' was used..
2403 return first_pop;
2404 }
2405
2406 return -1;
2407}
2408
2409static void scan_fwd_set_flags(int i, int opcnt, int magic, int flags)
2410{
2411 struct parsed_op *po;
2412 int j;
2413
2414 if (i < 0)
2415 ferr(ops, "%s: followed bad branch?\n", __func__);
2416
2417 for (; i < opcnt; i++) {
2418 po = &ops[i];
2419 if (po->cc_scratch == magic)
2420 return;
2421 po->cc_scratch = magic;
2422 po->flags |= flags;
2423
2424 if ((po->flags & OPF_JMP) && po->op != OP_CALL) {
2425 if (po->btj != NULL) {
2426 // jumptable
2427 for (j = 0; j < po->btj->count; j++)
2428 scan_fwd_set_flags(po->btj->d[j].bt_i, opcnt, magic, flags);
2429 return;
2430 }
2431
2432 scan_fwd_set_flags(po->bt_i, opcnt, magic, flags);
2433 if (!(po->flags & OPF_CJMP))
2434 return;
2435 }
2436 if (po->flags & OPF_TAIL)
2437 return;
2438 }
2439}
2440
2441static const struct parsed_proto *try_recover_pp(
2442 struct parsed_op *po, const struct parsed_opr *opr, int *search_instead)
2443{
2444 const struct parsed_proto *pp = NULL;
2445 char buf[256];
2446 char *p;
2447
2448 // maybe an arg of g_func?
2449 if (opr->type == OPT_REGMEM && is_stack_access(po, opr))
2450 {
2451 char ofs_reg[16] = { 0, };
2452 int arg, arg_s, arg_i;
2453 int stack_ra = 0;
2454 int offset = 0;
2455
2456 parse_stack_access(po, opr->name, ofs_reg,
2457 &offset, &stack_ra, NULL, 0);
2458 if (ofs_reg[0] != 0)
2459 ferr(po, "offset reg on arg access?\n");
2460 if (offset <= stack_ra) {
2461 // search who set the stack var instead
2462 if (search_instead != NULL)
2463 *search_instead = 1;
2464 return NULL;
2465 }
2466
2467 arg_i = (offset - stack_ra - 4) / 4;
2468 for (arg = arg_s = 0; arg < g_func_pp->argc; arg++) {
2469 if (g_func_pp->arg[arg].reg != NULL)
2470 continue;
2471 if (arg_s == arg_i)
2472 break;
2473 arg_s++;
2474 }
2475 if (arg == g_func_pp->argc)
2476 ferr(po, "stack arg %d not in prototype?\n", arg_i);
2477
2478 pp = g_func_pp->arg[arg].fptr;
2479 if (pp == NULL)
2480 ferr(po, "icall sa: arg%d is not a fptr?\n", arg + 1);
2481 check_func_pp(po, pp, "icall arg");
2482 }
2483 else if (opr->type == OPT_REGMEM && strchr(opr->name + 1, '[')) {
2484 // label[index]
2485 p = strchr(opr->name + 1, '[');
2486 memcpy(buf, opr->name, p - opr->name);
2487 buf[p - opr->name] = 0;
2488 pp = proto_parse(g_fhdr, buf, 0);
2489 }
2490 else if (opr->type == OPT_OFFSET || opr->type == OPT_LABEL) {
2491 pp = proto_parse(g_fhdr, opr->name, 0);
2492 if (pp == NULL)
2493 ferr(po, "proto_parse failed for icall from '%s'\n", opr->name);
2494 check_func_pp(po, pp, "reg-fptr ref");
2495 }
2496
2497 return pp;
2498}
2499
2500static void scan_for_call_type(int i, const struct parsed_opr *opr,
2501 int magic, const struct parsed_proto **pp_found, int *multi)
2502{
2503 const struct parsed_proto *pp = NULL;
2504 struct parsed_op *po;
2505 struct label_ref *lr;
2506
2507 ops[i].cc_scratch = magic;
2508
2509 while (1) {
2510 if (g_labels[i][0] != 0) {
2511 lr = &g_label_refs[i];
2512 for (; lr != NULL; lr = lr->next)
2513 scan_for_call_type(lr->i, opr, magic, pp_found, multi);
2514 if (i > 0 && LAST_OP(i - 1))
2515 return;
2516 }
2517
2518 i--;
2519 if (i < 0)
2520 break;
2521
2522 if (ops[i].cc_scratch == magic)
2523 return;
2524 ops[i].cc_scratch = magic;
2525
2526 if (!(ops[i].flags & OPF_DATA))
2527 continue;
2528 if (!is_opr_modified(opr, &ops[i]))
2529 continue;
2530 if (ops[i].op != OP_MOV && ops[i].op != OP_LEA) {
2531 // most probably trashed by some processing
2532 *pp_found = NULL;
2533 return;
2534 }
2535
2536 opr = &ops[i].operand[1];
2537 if (opr->type != OPT_REG)
2538 break;
2539 }
2540
2541 po = (i >= 0) ? &ops[i] : ops;
2542
2543 if (i < 0) {
2544 // reached the top - can only be an arg-reg
2545 if (opr->type != OPT_REG)
2546 return;
2547
2548 for (i = 0; i < g_func_pp->argc; i++) {
2549 if (g_func_pp->arg[i].reg == NULL)
2550 continue;
2551 if (IS(opr->name, g_func_pp->arg[i].reg))
2552 break;
2553 }
2554 if (i == g_func_pp->argc)
2555 return;
2556 pp = g_func_pp->arg[i].fptr;
2557 if (pp == NULL)
2558 ferr(po, "icall: arg%d (%s) is not a fptr?\n",
2559 i + 1, g_func_pp->arg[i].reg);
2560 check_func_pp(po, pp, "icall reg-arg");
2561 }
2562 else
2563 pp = try_recover_pp(po, opr, NULL);
2564
2565 if (*pp_found != NULL && pp != NULL && *pp_found != pp) {
2566 if (!IS((*pp_found)->ret_type.name, pp->ret_type.name)
2567 || (*pp_found)->is_stdcall != pp->is_stdcall
2568 || (*pp_found)->is_fptr != pp->is_fptr
2569 || (*pp_found)->argc != pp->argc
2570 || (*pp_found)->argc_reg != pp->argc_reg
2571 || (*pp_found)->argc_stack != pp->argc_stack)
2572 {
2573 ferr(po, "icall: parsed_proto mismatch\n");
2574 }
2575 *multi = 1;
2576 }
2577 if (pp != NULL)
2578 *pp_found = pp;
2579}
2580
2581static const struct parsed_proto *resolve_icall(int i, int opcnt,
2582 int *multi_src)
2583{
2584 const struct parsed_proto *pp = NULL;
2585 int search_advice = 0;
2586
2587 *multi_src = 0;
2588
2589 switch (ops[i].operand[0].type) {
2590 case OPT_REGMEM:
2591 case OPT_LABEL:
2592 case OPT_OFFSET:
2593 pp = try_recover_pp(&ops[i], &ops[i].operand[0], &search_advice);
2594 if (!search_advice)
2595 break;
2596 // fallthrough
2597 default:
2598 scan_for_call_type(i, &ops[i].operand[0], i + opcnt * 9, &pp,
2599 multi_src);
2600 break;
2601 }
2602
2603 return pp;
2604}
2605
2606// find an instruction that changed opr before i op
2607// *op_i must be set to -1
2608static int resolve_origin(int i, const struct parsed_opr *opr,
2609 int magic, int *op_i)
2610{
2611 struct label_ref *lr;
2612 int ret = 0;
2613
2614 ops[i].cc_scratch = magic;
2615
2616 while (1) {
2617 if (g_labels[i][0] != 0) {
2618 lr = &g_label_refs[i];
2619 for (; lr != NULL; lr = lr->next)
2620 ret |= resolve_origin(lr->i, opr, magic, op_i);
2621 if (i > 0 && LAST_OP(i - 1))
2622 return ret;
2623 }
2624
2625 i--;
2626 if (i < 0)
2627 return -1;
2628
2629 if (ops[i].cc_scratch == magic)
2630 return 0;
2631 ops[i].cc_scratch = magic;
2632
2633 if (!(ops[i].flags & OPF_DATA))
2634 continue;
2635 if (!is_opr_modified(opr, &ops[i]))
2636 continue;
2637
2638 if (*op_i >= 0) {
2639 if (*op_i == i)
2640 return 1;
2641 // XXX: could check if the other op does the same
2642 return -1;
2643 }
2644
2645 *op_i = i;
2646 return 1;
2647 }
2648}
2649
2650static int try_resolve_const(int i, const struct parsed_opr *opr,
2651 int magic, unsigned int *val)
2652{
2653 int s_i = -1;
2654 int ret = 0;
2655
2656 ret = resolve_origin(i, opr, magic, &s_i);
2657 if (ret == 1) {
2658 i = s_i;
2659 if (ops[i].op != OP_MOV && ops[i].operand[1].type != OPT_CONST)
2660 return -1;
2661
2662 *val = ops[i].operand[1].val;
2663 return 1;
2664 }
2665
2666 return -1;
2667}
2668
2669static int collect_call_args_r(struct parsed_op *po, int i,
2670 struct parsed_proto *pp, int *regmask, int *save_arg_vars, int arg,
2671 int magic, int need_op_saving, int may_reuse)
2672{
2673 struct parsed_proto *pp_tmp;
2674 struct label_ref *lr;
2675 int need_to_save_current;
2676 int save_args;
2677 int ret = 0;
2678 int reg;
2679 char buf[32];
2680 int j, k;
2681
2682 if (i < 0) {
2683 ferr(po, "dead label encountered\n");
2684 return -1;
2685 }
2686
2687 for (; arg < pp->argc; arg++)
2688 if (pp->arg[arg].reg == NULL)
2689 break;
2690 magic = (magic & 0xffffff) | (arg << 24);
2691
2692 for (j = i; j >= 0 && (arg < pp->argc || pp->is_unresolved); )
2693 {
2694 if (((ops[j].cc_scratch ^ magic) & 0xffffff) == 0) {
2695 if (ops[j].cc_scratch != magic) {
2696 ferr(&ops[j], "arg collect hit same path with diff args for %s\n",
2697 pp->name);
2698 return -1;
2699 }
2700 // ok: have already been here
2701 return 0;
2702 }
2703 ops[j].cc_scratch = magic;
2704
2705 if (g_labels[j][0] != 0 && g_label_refs[j].i != -1) {
2706 lr = &g_label_refs[j];
2707 if (lr->next != NULL)
2708 need_op_saving = 1;
2709 for (; lr->next; lr = lr->next) {
2710 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2711 may_reuse = 1;
2712 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2713 arg, magic, need_op_saving, may_reuse);
2714 if (ret < 0)
2715 return ret;
2716 }
2717
2718 if ((ops[lr->i].flags & (OPF_JMP|OPF_CJMP)) != OPF_JMP)
2719 may_reuse = 1;
2720 if (j > 0 && LAST_OP(j - 1)) {
2721 // follow last branch in reverse
2722 j = lr->i;
2723 continue;
2724 }
2725 need_op_saving = 1;
2726 ret = collect_call_args_r(po, lr->i, pp, regmask, save_arg_vars,
2727 arg, magic, need_op_saving, may_reuse);
2728 if (ret < 0)
2729 return ret;
2730 }
2731 j--;
2732
2733 if (ops[j].op == OP_CALL)
2734 {
2735 if (pp->is_unresolved)
2736 break;
2737
2738 pp_tmp = ops[j].pp;
2739 if (pp_tmp == NULL)
2740 ferr(po, "arg collect hit unparsed call '%s'\n",
2741 ops[j].operand[0].name);
2742 if (may_reuse && pp_tmp->argc_stack > 0)
2743 ferr(po, "arg collect %d/%d hit '%s' with %d stack args\n",
2744 arg, pp->argc, opr_name(&ops[j], 0), pp_tmp->argc_stack);
2745 }
2746 else if (ops[j].op == OP_ADD && ops[j].operand[0].reg == xSP) {
2747 if (pp->is_unresolved)
2748 break;
2749
2750 ferr(po, "arg collect %d/%d hit esp adjust\n",
2751 arg, pp->argc);
2752 }
2753 else if (ops[j].op == OP_POP) {
2754 if (pp->is_unresolved)
2755 break;
2756
2757 ferr(po, "arg collect %d/%d hit pop\n", arg, pp->argc);
2758 }
2759 else if (ops[j].flags & OPF_CJMP)
2760 {
2761 if (pp->is_unresolved)
2762 break;
2763
2764 may_reuse = 1;
2765 }
2766 else if (ops[j].op == OP_PUSH && !(ops[j].flags & OPF_FARG))
2767 {
2768 if (pp->is_unresolved && (ops[j].flags & OPF_RMD))
2769 break;
2770
2771 pp->arg[arg].datap = &ops[j];
2772 need_to_save_current = 0;
2773 save_args = 0;
2774 reg = -1;
2775 if (ops[j].operand[0].type == OPT_REG)
2776 reg = ops[j].operand[0].reg;
2777
2778 if (!need_op_saving) {
2779 ret = scan_for_mod(&ops[j], j + 1, i, 1);
2780 need_to_save_current = (ret >= 0);
2781 }
2782 if (need_op_saving || need_to_save_current) {
2783 // mark this push as one that needs operand saving
2784 ops[j].flags &= ~OPF_RMD;
2785 if (ops[j].p_argnum == 0) {
2786 ops[j].p_argnum = arg + 1;
2787 save_args |= 1 << arg;
2788 }
2789 else if (ops[j].p_argnum < arg + 1)
2790 ferr(&ops[j], "p_argnum conflict (%d<%d) for '%s'\n",
2791 ops[j].p_argnum, arg + 1, pp->name);
2792 }
2793 else if (ops[j].p_argnum == 0)
2794 ops[j].flags |= OPF_RMD;
2795
2796 // some PUSHes are reused by different calls on other branches,
2797 // but that can't happen if we didn't branch, so they
2798 // can be removed from future searches (handles nested calls)
2799 if (!may_reuse)
2800 ops[j].flags |= OPF_FARG;
2801
2802 ops[j].flags &= ~OPF_RSAVE;
2803
2804 // check for __VALIST
2805 if (!pp->is_unresolved && pp->arg[arg].type.is_va_list) {
2806 k = -1;
2807 ret = resolve_origin(j, &ops[j].operand[0], magic + 1, &k);
2808 if (ret == 1 && k >= 0)
2809 {
2810 if (ops[k].op == OP_LEA) {
2811 snprintf(buf, sizeof(buf), "arg_%X",
2812 g_func_pp->argc_stack * 4);
2813 if (!g_func_pp->is_vararg
2814 || strstr(ops[k].operand[1].name, buf))
2815 {
2816 ops[k].flags |= OPF_RMD;
2817 ops[j].flags |= OPF_RMD | OPF_VAPUSH;
2818 save_args &= ~(1 << arg);
2819 reg = -1;
2820 }
2821 else
2822 ferr(&ops[j], "lea va_list used, but no vararg?\n");
2823 }
2824 // check for va_list from g_func_pp arg too
2825 else if (ops[k].op == OP_MOV
2826 && is_stack_access(&ops[k], &ops[k].operand[1]))
2827 {
2828 ret = stack_frame_access(&ops[k], &ops[k].operand[1],
2829 buf, sizeof(buf), ops[k].operand[1].name, "", 1, 0);
2830 if (ret >= 0) {
2831 ops[k].flags |= OPF_RMD;
2832 ops[j].flags |= OPF_RMD;
2833 ops[j].p_argpass = ret + 1;
2834 save_args &= ~(1 << arg);
2835 reg = -1;
2836 }
2837 }
2838 }
2839 }
2840
2841 *save_arg_vars |= save_args;
2842
2843 // tracking reg usage
2844 if (reg >= 0)
2845 *regmask |= 1 << reg;
2846
2847 arg++;
2848 if (!pp->is_unresolved) {
2849 // next arg
2850 for (; arg < pp->argc; arg++)
2851 if (pp->arg[arg].reg == NULL)
2852 break;
2853 }
2854 magic = (magic & 0xffffff) | (arg << 24);
2855 }
2856 }
2857
2858 if (arg < pp->argc) {
2859 ferr(po, "arg collect failed for '%s': %d/%d\n",
2860 pp->name, arg, pp->argc);
2861 return -1;
2862 }
2863
2864 return arg;
2865}
2866
2867static int collect_call_args(struct parsed_op *po, int i,
2868 struct parsed_proto *pp, int *regmask, int *save_arg_vars,
2869 int magic)
2870{
2871 int ret;
2872 int a;
2873
2874 ret = collect_call_args_r(po, i, pp, regmask, save_arg_vars,
2875 0, magic, 0, 0);
2876 if (ret < 0)
2877 return ret;
2878
2879 if (pp->is_unresolved) {
2880 pp->argc += ret;
2881 pp->argc_stack += ret;
2882 for (a = 0; a < pp->argc; a++)
2883 if (pp->arg[a].type.name == NULL)
2884 pp->arg[a].type.name = strdup("int");
2885 }
2886
2887 return ret;
2888}
2889
2890// early check for tail call or branch back
2891static int is_like_tailjmp(int j)
2892{
2893 if (!(ops[j].flags & OPF_JMP))
2894 return 0;
2895
2896 if (ops[j].op == OP_JMP && !ops[j].operand[0].had_ds)
2897 // probably local branch back..
2898 return 1;
2899 if (ops[j].op == OP_CALL)
2900 // probably noreturn call..
2901 return 1;
2902
2903 return 0;
2904}
2905
2906static void pp_insert_reg_arg(struct parsed_proto *pp, const char *reg)
2907{
2908 int i;
2909
2910 for (i = 0; i < pp->argc; i++)
2911 if (pp->arg[i].reg == NULL)
2912 break;
2913
2914 if (pp->argc_stack)
2915 memmove(&pp->arg[i + 1], &pp->arg[i],
2916 sizeof(pp->arg[0]) * pp->argc_stack);
2917 memset(&pp->arg[i], 0, sizeof(pp->arg[i]));
2918 pp->arg[i].reg = strdup(reg);
2919 pp->arg[i].type.name = strdup("int");
2920 pp->argc++;
2921 pp->argc_reg++;
2922}
2923
2924static void add_label_ref(struct label_ref *lr, int op_i)
2925{
2926 struct label_ref *lr_new;
2927
2928 if (lr->i == -1) {
2929 lr->i = op_i;
2930 return;
2931 }
2932
2933 lr_new = calloc(1, sizeof(*lr_new));
2934 lr_new->i = op_i;
2935 lr_new->next = lr->next;
2936 lr->next = lr_new;
2937}
2938
2939static void output_std_flags(FILE *fout, struct parsed_op *po,
2940 int *pfomask, const char *dst_opr_text)
2941{
2942 if (*pfomask & (1 << PFO_Z)) {
2943 fprintf(fout, "\n cond_z = (%s%s == 0);",
2944 lmod_cast_u(po, po->operand[0].lmod), dst_opr_text);
2945 *pfomask &= ~(1 << PFO_Z);
2946 }
2947 if (*pfomask & (1 << PFO_S)) {
2948 fprintf(fout, "\n cond_s = (%s%s < 0);",
2949 lmod_cast_s(po, po->operand[0].lmod), dst_opr_text);
2950 *pfomask &= ~(1 << PFO_S);
2951 }
2952}
2953
2954static void output_pp_attrs(FILE *fout, const struct parsed_proto *pp,
2955 int is_noreturn)
2956{
2957 if (pp->is_fastcall)
2958 fprintf(fout, "__fastcall ");
2959 else if (pp->is_stdcall && pp->argc_reg == 0)
2960 fprintf(fout, "__stdcall ");
2961 if (pp->is_noreturn || is_noreturn)
2962 fprintf(fout, "noreturn ");
2963}
2964
2965static void gen_func(FILE *fout, FILE *fhdr, const char *funcn, int opcnt)
2966{
2967 struct parsed_op *po, *delayed_flag_op = NULL, *tmp_op;
2968 struct parsed_opr *last_arith_dst = NULL;
2969 char buf1[256], buf2[256], buf3[256], cast[64];
2970 const struct parsed_proto *pp_c;
2971 struct parsed_proto *pp, *pp_tmp;
2972 struct parsed_data *pd;
2973 const char *tmpname;
2974 unsigned int uval;
2975 int save_arg_vars = 0;
2976 int cond_vars = 0;
2977 int need_tmp_var = 0;
2978 int need_tmp64 = 0;
2979 int had_decl = 0;
2980 int label_pending = 0;
2981 int regmask_save = 0;
2982 int regmask_arg = 0;
2983 int regmask_now = 0;
2984 int regmask_init = 0;
2985 int regmask = 0;
2986 int pfomask = 0;
2987 int found = 0;
2988 int depth = 0;
2989 int no_output;
2990 int i, j, l;
2991 int arg;
2992 int reg;
2993 int ret;
2994
2995 g_bp_frame = g_sp_frame = g_stack_fsz = 0;
2996 g_stack_frame_used = 0;
2997
2998 g_func_pp = proto_parse(fhdr, funcn, 0);
2999 if (g_func_pp == NULL)
3000 ferr(ops, "proto_parse failed for '%s'\n", funcn);
3001
3002 for (i = 0; i < g_func_pp->argc; i++) {
3003 if (g_func_pp->arg[i].reg != NULL) {
3004 reg = char_array_i(regs_r32,
3005 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3006 if (reg < 0)
3007 ferr(ops, "arg '%s' is not a reg?\n", g_func_pp->arg[i].reg);
3008 regmask_arg |= 1 << reg;
3009 }
3010 }
3011
3012 // pass1:
3013 // - handle ebp/esp frame, remove ops related to it
3014 if (ops[0].op == OP_PUSH && IS(opr_name(&ops[0], 0), "ebp")
3015 && ops[1].op == OP_MOV
3016 && IS(opr_name(&ops[1], 0), "ebp")
3017 && IS(opr_name(&ops[1], 1), "esp"))
3018 {
3019 int ecx_push = 0;
3020
3021 g_bp_frame = 1;
3022 ops[0].flags |= OPF_RMD;
3023 ops[1].flags |= OPF_RMD;
3024 i = 2;
3025
3026 if (ops[2].op == OP_SUB && IS(opr_name(&ops[2], 0), "esp")) {
3027 g_stack_fsz = opr_const(&ops[2], 1);
3028 ops[2].flags |= OPF_RMD;
3029 i++;
3030 }
3031 else {
3032 // another way msvc builds stack frame..
3033 i = 2;
3034 while (ops[i].op == OP_PUSH && IS(opr_name(&ops[i], 0), "ecx")) {
3035 g_stack_fsz += 4;
3036 ops[i].flags |= OPF_RMD;
3037 ecx_push++;
3038 i++;
3039 }
3040 // and another way..
3041 if (i == 2 && ops[i].op == OP_MOV && ops[i].operand[0].reg == xAX
3042 && ops[i].operand[1].type == OPT_CONST
3043 && ops[i + 1].op == OP_CALL
3044 && IS(opr_name(&ops[i + 1], 0), "__alloca_probe"))
3045 {
3046 g_stack_fsz += ops[i].operand[1].val;
3047 ops[i].flags |= OPF_RMD;
3048 i++;
3049 ops[i].flags |= OPF_RMD;
3050 i++;
3051 }
3052 }
3053
3054 found = 0;
3055 do {
3056 for (; i < opcnt; i++)
3057 if (ops[i].op == OP_RET)
3058 break;
3059 j = i - 1;
3060 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3061 if (found && is_like_tailjmp(j))
3062 break;
3063 j--;
3064 }
3065
3066 if ((ops[j].op == OP_POP && IS(opr_name(&ops[j], 0), "ebp"))
3067 || ops[j].op == OP_LEAVE)
3068 {
3069 ops[j].flags |= OPF_RMD;
3070 }
3071 else if (!(g_ida_func_attr & IDAFA_NORETURN))
3072 ferr(&ops[j], "'pop ebp' expected\n");
3073
3074 if (g_stack_fsz != 0) {
3075 if (ops[j - 1].op == OP_MOV
3076 && IS(opr_name(&ops[j - 1], 0), "esp")
3077 && IS(opr_name(&ops[j - 1], 1), "ebp"))
3078 {
3079 ops[j - 1].flags |= OPF_RMD;
3080 }
3081 else if (ops[j].op != OP_LEAVE
3082 && !(g_ida_func_attr & IDAFA_NORETURN))
3083 {
3084 ferr(&ops[j - 1], "esp restore expected\n");
3085 }
3086
3087 if (ecx_push && ops[j - 2].op == OP_POP
3088 && IS(opr_name(&ops[j - 2], 0), "ecx"))
3089 {
3090 ferr(&ops[j - 2], "unexpected ecx pop\n");
3091 }
3092 }
3093
3094 found = 1;
3095 i++;
3096 } while (i < opcnt);
3097 }
3098 else {
3099 for (i = 0; i < opcnt; i++) {
3100 if (ops[i].op == OP_PUSH || (ops[i].flags & (OPF_JMP|OPF_TAIL)))
3101 break;
3102 if (ops[i].op == OP_SUB && ops[i].operand[0].reg == xSP
3103 && ops[i].operand[1].type == OPT_CONST)
3104 {
3105 g_sp_frame = 1;
3106 break;
3107 }
3108 }
3109
3110 found = 0;
3111 if (g_sp_frame)
3112 {
3113 g_stack_fsz = ops[i].operand[1].val;
3114 ops[i].flags |= OPF_RMD;
3115
3116 i++;
3117 do {
3118 for (; i < opcnt; i++)
3119 if (ops[i].op == OP_RET)
3120 break;
3121 j = i - 1;
3122 if (i == opcnt && (ops[j].flags & OPF_JMP)) {
3123 if (found && is_like_tailjmp(j))
3124 break;
3125 j--;
3126 }
3127
3128 if (ops[j].op != OP_ADD
3129 || !IS(opr_name(&ops[j], 0), "esp")
3130 || ops[j].operand[1].type != OPT_CONST
3131 || ops[j].operand[1].val != g_stack_fsz)
3132 ferr(&ops[j], "'add esp' expected\n");
3133 ops[j].flags |= OPF_RMD;
3134
3135 found = 1;
3136 i++;
3137 } while (i < opcnt);
3138 }
3139 }
3140
3141 // pass2:
3142 // - parse calls with labels
3143 // - resolve all branches
3144 for (i = 0; i < opcnt; i++)
3145 {
3146 po = &ops[i];
3147 po->bt_i = -1;
3148 po->btj = NULL;
3149
3150 if (po->flags & OPF_RMD)
3151 continue;
3152
3153 if (po->op == OP_CALL) {
3154 pp = NULL;
3155
3156 if (po->operand[0].type == OPT_LABEL) {
3157 tmpname = opr_name(po, 0);
3158 if (IS_START(tmpname, "loc_"))
3159 ferr(po, "call to loc_*\n");
3160 pp_c = proto_parse(fhdr, tmpname, 0);
3161 if (pp_c == NULL)
3162 ferr(po, "proto_parse failed for call '%s'\n", tmpname);
3163
3164 pp = proto_clone(pp_c);
3165 my_assert_not(pp, NULL);
3166 }
3167 else if (po->datap != NULL) {
3168 pp = calloc(1, sizeof(*pp));
3169 my_assert_not(pp, NULL);
3170
3171 ret = parse_protostr(po->datap, pp);
3172 if (ret < 0)
3173 ferr(po, "bad protostr supplied: %s\n", (char *)po->datap);
3174 free(po->datap);
3175 po->datap = NULL;
3176 }
3177
3178 if (pp != NULL) {
3179 if (pp->is_fptr)
3180 check_func_pp(po, pp, "fptr var call");
3181 if (pp->is_noreturn)
3182 po->flags |= OPF_TAIL;
3183 }
3184 po->pp = pp;
3185 continue;
3186 }
3187
3188 if (!(po->flags & OPF_JMP) || po->op == OP_RET)
3189 continue;
3190
3191 if (po->operand[0].type == OPT_REGMEM) {
3192 char *p = strchr(po->operand[0].name, '[');
3193 if (p == NULL)
3194 goto tailcall;
3195 ret = p - po->operand[0].name;
3196 strncpy(buf1, po->operand[0].name, ret);
3197 buf1[ret] = 0;
3198
3199 for (j = 0, pd = NULL; j < g_func_pd_cnt; j++) {
3200 if (IS(g_func_pd[j].label, buf1)) {
3201 pd = &g_func_pd[j];
3202 break;
3203 }
3204 }
3205 if (pd == NULL)
3206 //ferr(po, "label '%s' not parsed?\n", buf1);
3207 goto tailcall;
3208 if (pd->type != OPT_OFFSET)
3209 ferr(po, "label '%s' with non-offset data?\n", buf1);
3210
3211 // find all labels, link
3212 for (j = 0; j < pd->count; j++) {
3213 for (l = 0; l < opcnt; l++) {
3214 if (g_labels[l][0] && IS(g_labels[l], pd->d[j].u.label)) {
3215 add_label_ref(&g_label_refs[l], i);
3216 pd->d[j].bt_i = l;
3217 break;
3218 }
3219 }
3220 }
3221
3222 po->btj = pd;
3223 continue;
3224 }
3225
3226 for (l = 0; l < opcnt; l++) {
3227 if (g_labels[l][0] && IS(po->operand[0].name, g_labels[l])) {
3228 if (l == i + 1 && po->op == OP_JMP) {
3229 // yet another alignment type..
3230 po->flags |= OPF_RMD;
3231 break;
3232 }
3233 add_label_ref(&g_label_refs[l], i);
3234 po->bt_i = l;
3235 break;
3236 }
3237 }
3238
3239 if (po->bt_i != -1 || (po->flags & OPF_RMD))
3240 continue;
3241
3242 if (po->operand[0].type == OPT_LABEL)
3243 // assume tail call
3244 goto tailcall;
3245
3246 ferr(po, "unhandled branch\n");
3247
3248tailcall:
3249 po->op = OP_CALL;
3250 po->flags |= OPF_TAIL;
3251 if (i > 0 && ops[i - 1].op == OP_POP)
3252 po->flags |= OPF_ATAIL;
3253 i--; // reprocess
3254 }
3255
3256 // pass3:
3257 // - remove dead labels
3258 // - process calls
3259 for (i = 0; i < opcnt; i++)
3260 {
3261 if (g_labels[i][0] != 0 && g_label_refs[i].i == -1)
3262 g_labels[i][0] = 0;
3263
3264 po = &ops[i];
3265 if (po->flags & OPF_RMD)
3266 continue;
3267
3268 if (po->op == OP_CALL)
3269 {
3270 tmpname = opr_name(po, 0);
3271 pp = po->pp;
3272 if (pp == NULL)
3273 {
3274 // indirect call
3275 pp_c = resolve_icall(i, opcnt, &l);
3276 if (pp_c != NULL) {
3277 if (!pp_c->is_func && !pp_c->is_fptr)
3278 ferr(po, "call to non-func: %s\n", pp_c->name);
3279 pp = proto_clone(pp_c);
3280 my_assert_not(pp, NULL);
3281 if (l)
3282 // not resolved just to single func
3283 pp->is_fptr = 1;
3284
3285 switch (po->operand[0].type) {
3286 case OPT_REG:
3287 // we resolved this call and no longer need the register
3288 po->regmask_src &= ~(1 << po->operand[0].reg);
3289 break;
3290 case OPT_REGMEM:
3291 pp->is_fptr = 1;
3292 break;
3293 default:
3294 break;
3295 }
3296 }
3297 if (pp == NULL) {
3298 pp = calloc(1, sizeof(*pp));
3299 my_assert_not(pp, NULL);
3300 pp->is_fptr = 1;
3301 ret = scan_for_esp_adjust(i + 1, opcnt, &j, &l);
3302 if (ret < 0) {
3303 if (!g_allow_regfunc)
3304 ferr(po, "non-__cdecl indirect call unhandled yet\n");
3305 pp->is_unresolved = 1;
3306 j = 0;
3307 }
3308 j /= 4;
3309 if (j > ARRAY_SIZE(pp->arg))
3310 ferr(po, "esp adjust too large: %d\n", j);
3311 pp->ret_type.name = strdup("int");
3312 pp->argc = pp->argc_stack = j;
3313 for (arg = 0; arg < pp->argc; arg++)
3314 pp->arg[arg].type.name = strdup("int");
3315 }
3316 po->pp = pp;
3317 }
3318
3319 // look for and make use of esp adjust
3320 ret = -1;
3321 if (!pp->is_stdcall && pp->argc_stack > 0)
3322 ret = scan_for_esp_adjust(i + 1, opcnt, &j, &l);
3323 if (ret >= 0) {
3324 if (pp->is_vararg) {
3325 if (j / 4 < pp->argc_stack)
3326 ferr(po, "esp adjust is too small: %x < %x\n",
3327 j, pp->argc_stack * 4);
3328 // modify pp to make it have varargs as normal args
3329 arg = pp->argc;
3330 pp->argc += j / 4 - pp->argc_stack;
3331 for (; arg < pp->argc; arg++) {
3332 pp->arg[arg].type.name = strdup("int");
3333 pp->argc_stack++;
3334 }
3335 if (pp->argc > ARRAY_SIZE(pp->arg))
3336 ferr(po, "too many args for '%s'\n", tmpname);
3337 }
3338 if (pp->argc_stack != j / 4)
3339 ferr(po, "stack tracking failed for '%s': %x %x\n",
3340 tmpname, pp->argc_stack * 4, j);
3341
3342 ops[ret].flags |= OPF_RMD;
3343 if (ops[ret].op == OP_POP && j > 4) {
3344 // deal with multi-pop stack adjust
3345 j = pp->argc_stack;
3346 while (ops[ret].op == OP_POP && j > 0 && ret < opcnt) {
3347 ops[ret].flags |= OPF_RMD;
3348 j--;
3349 ret++;
3350 }
3351 }
3352 else if (!l) {
3353 // a bit of a hack, but deals with use of
3354 // single adj for multiple calls
3355 ops[ret].operand[1].val -= j;
3356 }
3357 }
3358 else if (pp->is_vararg)
3359 ferr(po, "missing esp_adjust for vararg func '%s'\n",
3360 pp->name);
3361
3362 if (!pp->is_unresolved && !(po->flags & OPF_ATAIL)) {
3363 // since we know the args, collect them
3364 collect_call_args(po, i, pp, &regmask, &save_arg_vars,
3365 i + opcnt * 2);
3366 }
3367
3368 if (strstr(pp->ret_type.name, "int64"))
3369 need_tmp64 = 1;
3370 }
3371 }
3372
3373 // pass4:
3374 // - find POPs for PUSHes, rm both
3375 // - scan for STD/CLD, propagate DF
3376 // - scan for all used registers
3377 // - find flag set ops for their users
3378 // - do unreselved calls
3379 // - declare indirect functions
3380 for (i = 0; i < opcnt; i++) {
3381 po = &ops[i];
3382 if (po->flags & OPF_RMD)
3383 continue;
3384
3385 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE)) {
3386 reg = po->operand[0].reg;
3387 if (!(regmask & (1 << reg)))
3388 // not a reg save after all, rerun scan_for_pop
3389 po->flags &= ~OPF_RSAVE;
3390 else
3391 regmask_save |= 1 << reg;
3392 }
3393
3394 if (po->op == OP_PUSH && po->p_argnum == 0
3395 && !(po->flags & OPF_RSAVE) && !g_func_pp->is_userstack)
3396 {
3397 if (po->operand[0].type == OPT_REG)
3398 {
3399 reg = po->operand[0].reg;
3400 if (reg < 0)
3401 ferr(po, "reg not set for push?\n");
3402
3403 depth = 0;
3404 ret = scan_for_pop(i + 1, opcnt,
3405 po->operand[0].name, i + opcnt * 3, 0, &depth, 0);
3406 if (ret == 1) {
3407 if (depth > 1)
3408 ferr(po, "too much depth: %d\n", depth);
3409
3410 po->flags |= OPF_RMD;
3411 scan_for_pop(i + 1, opcnt, po->operand[0].name,
3412 i + opcnt * 4, 0, &depth, 1);
3413 continue;
3414 }
3415 ret = scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, 0);
3416 if (ret == 0) {
3417 arg = OPF_RMD;
3418 if (regmask & (1 << reg)) {
3419 if (regmask_save & (1 << reg))
3420 ferr(po, "%s already saved?\n", po->operand[0].name);
3421 arg = OPF_RSAVE;
3422 }
3423 po->flags |= arg;
3424 scan_for_pop_ret(i + 1, opcnt, po->operand[0].name, arg);
3425 continue;
3426 }
3427 }
3428 else if (po->operand[0].type == OPT_CONST) {
3429 for (j = i + 1; j < opcnt; j++) {
3430 if ((ops[j].flags & (OPF_JMP|OPF_TAIL|OPF_RSAVE))
3431 || ops[j].op == OP_PUSH || g_labels[i][0] != 0)
3432 {
3433 break;
3434 }
3435
3436 if (!(ops[j].flags & OPF_RMD) && ops[j].op == OP_POP)
3437 {
3438 po->flags |= OPF_RMD;
3439 ops[j].datap = po;
3440 break;
3441 }
3442 }
3443 }
3444 }
3445
3446 if (po->op == OP_STD) {
3447 po->flags |= OPF_DF | OPF_RMD;
3448 scan_propagate_df(i + 1, opcnt);
3449 }
3450
3451 regmask_now = po->regmask_src | po->regmask_dst;
3452 if (regmask_now & (1 << xBP)) {
3453 if (g_bp_frame && !(po->flags & OPF_EBP_S)) {
3454 if (po->regmask_dst & (1 << xBP))
3455 // compiler decided to drop bp frame and use ebp as scratch
3456 scan_fwd_set_flags(i + 1, opcnt, i + opcnt * 5, OPF_EBP_S);
3457 else
3458 regmask_now &= ~(1 << xBP);
3459 }
3460 }
3461
3462 regmask |= regmask_now;
3463
3464 if (po->flags & OPF_CC)
3465 {
3466 int setters[16], cnt = 0, branched = 0;
3467
3468 ret = scan_for_flag_set(i, i + opcnt * 6,
3469 &branched, setters, &cnt);
3470 if (ret < 0 || cnt <= 0)
3471 ferr(po, "unable to trace flag setter(s)\n");
3472 if (cnt > ARRAY_SIZE(setters))
3473 ferr(po, "too many flag setters\n");
3474
3475 for (j = 0; j < cnt; j++)
3476 {
3477 tmp_op = &ops[setters[j]]; // flag setter
3478 pfomask = 0;
3479
3480 // to get nicer code, we try to delay test and cmp;
3481 // if we can't because of operand modification, or if we
3482 // have arith op, or branch, make it calculate flags explicitly
3483 if (tmp_op->op == OP_TEST || tmp_op->op == OP_CMP)
3484 {
3485 if (branched || scan_for_mod(tmp_op, setters[j] + 1, i, 0) >= 0)
3486 pfomask = 1 << po->pfo;
3487 }
3488 else if (tmp_op->op == OP_CMPS || tmp_op->op == OP_SCAS) {
3489 pfomask = 1 << po->pfo;
3490 }
3491 else {
3492 // see if we'll be able to handle based on op result
3493 if ((tmp_op->op != OP_AND && tmp_op->op != OP_OR
3494 && po->pfo != PFO_Z && po->pfo != PFO_S
3495 && po->pfo != PFO_P)
3496 || branched
3497 || scan_for_mod_opr0(tmp_op, setters[j] + 1, i) >= 0)
3498 {
3499 pfomask = 1 << po->pfo;
3500 }
3501
3502 if (tmp_op->op == OP_ADD && po->pfo == PFO_C) {
3503 propagate_lmod(tmp_op, &tmp_op->operand[0],
3504 &tmp_op->operand[1]);
3505 if (tmp_op->operand[0].lmod == OPLM_DWORD)
3506 need_tmp64 = 1;
3507 }
3508 }
3509 if (pfomask) {
3510 tmp_op->pfomask |= pfomask;
3511 cond_vars |= pfomask;
3512 }
3513 // note: may overwrite, currently not a problem
3514 po->datap = tmp_op;
3515 }
3516
3517 if (po->op == OP_RCL || po->op == OP_RCR
3518 || po->op == OP_ADC || po->op == OP_SBB)
3519 cond_vars |= 1 << PFO_C;
3520 }
3521
3522 if (po->op == OP_CMPS || po->op == OP_SCAS) {
3523 cond_vars |= 1 << PFO_Z;
3524 }
3525 else if (po->op == OP_MUL
3526 || (po->op == OP_IMUL && po->operand_cnt == 1))
3527 {
3528 if (po->operand[0].lmod == OPLM_DWORD)
3529 need_tmp64 = 1;
3530 }
3531 else if (po->op == OP_CALL) {
3532 pp = po->pp;
3533 if (pp == NULL)
3534 ferr(po, "NULL pp\n");
3535
3536 if (pp->is_unresolved) {
3537 int regmask_stack = 0;
3538 collect_call_args(po, i, pp, &regmask, &save_arg_vars,
3539 i + opcnt * 2);
3540
3541 // this is pretty rough guess:
3542 // see ecx and edx were pushed (and not their saved versions)
3543 for (arg = 0; arg < pp->argc; arg++) {
3544 if (pp->arg[arg].reg != NULL)
3545 continue;
3546
3547 tmp_op = pp->arg[arg].datap;
3548 if (tmp_op == NULL)
3549 ferr(po, "parsed_op missing for arg%d\n", arg);
3550 if (tmp_op->p_argnum == 0 && tmp_op->operand[0].type == OPT_REG)
3551 regmask_stack |= 1 << tmp_op->operand[0].reg;
3552 }
3553
3554 if (!((regmask_stack & (1 << xCX))
3555 && (regmask_stack & (1 << xDX))))
3556 {
3557 if (pp->argc_stack != 0
3558 || ((regmask | regmask_arg) & ((1 << xCX)|(1 << xDX))))
3559 {
3560 pp_insert_reg_arg(pp, "ecx");
3561 pp->is_fastcall = 1;
3562 regmask_init |= 1 << xCX;
3563 regmask |= 1 << xCX;
3564 }
3565 if (pp->argc_stack != 0
3566 || ((regmask | regmask_arg) & (1 << xDX)))
3567 {
3568 pp_insert_reg_arg(pp, "edx");
3569 regmask_init |= 1 << xDX;
3570 regmask |= 1 << xDX;
3571 }
3572 }
3573
3574 // note: __cdecl doesn't fall into is_unresolved category
3575 if (pp->argc_stack > 0)
3576 pp->is_stdcall = 1;
3577 }
3578
3579 for (arg = 0; arg < pp->argc; arg++) {
3580 if (pp->arg[arg].reg != NULL) {
3581 reg = char_array_i(regs_r32,
3582 ARRAY_SIZE(regs_r32), pp->arg[arg].reg);
3583 if (reg < 0)
3584 ferr(ops, "arg '%s' is not a reg?\n", pp->arg[arg].reg);
3585 if (!(regmask & (1 << reg))) {
3586 regmask_init |= 1 << reg;
3587 regmask |= 1 << reg;
3588 }
3589 }
3590 }
3591 }
3592 else if (po->op == OP_MOV && po->operand[0].pp != NULL
3593 && po->operand[1].pp != NULL)
3594 {
3595 // <var> = offset <something>
3596 if ((po->operand[1].pp->is_func || po->operand[1].pp->is_fptr)
3597 && !IS_START(po->operand[1].name, "off_"))
3598 {
3599 if (!po->operand[0].pp->is_fptr)
3600 ferr(po, "%s not declared as fptr when it should be\n",
3601 po->operand[0].name);
3602 if (pp_cmp_func(po->operand[0].pp, po->operand[1].pp)) {
3603 pp_print(buf1, sizeof(buf1), po->operand[0].pp);
3604 pp_print(buf2, sizeof(buf2), po->operand[1].pp);
3605 fnote(po, "var: %s\n", buf1);
3606 fnote(po, "func: %s\n", buf2);
3607 ferr(po, "^ mismatch\n");
3608 }
3609 }
3610 }
3611 else if (po->op == OP_RET && !IS(g_func_pp->ret_type.name, "void"))
3612 regmask |= 1 << xAX;
3613 else if (po->op == OP_DIV || po->op == OP_IDIV) {
3614 // 32bit division is common, look for it
3615 if (po->op == OP_DIV)
3616 ret = scan_for_reg_clear(i, xDX);
3617 else
3618 ret = scan_for_cdq_edx(i);
3619 if (ret >= 0)
3620 po->flags |= OPF_32BIT;
3621 else
3622 need_tmp64 = 1;
3623 }
3624 else if (po->op == OP_CLD)
3625 po->flags |= OPF_RMD;
3626
3627 if (po->op == OP_RCL || po->op == OP_RCR || po->op == OP_XCHG) {
3628 need_tmp_var = 1;
3629 }
3630 }
3631
3632 // pass4:
3633 // - confirm regmask_save, it might have been reduced
3634 if (regmask_save != 0)
3635 {
3636 regmask_save = 0;
3637 for (i = 0; i < opcnt; i++) {
3638 po = &ops[i];
3639 if (po->flags & OPF_RMD)
3640 continue;
3641
3642 if (po->op == OP_PUSH && (po->flags & OPF_RSAVE))
3643 regmask_save |= 1 << po->operand[0].reg;
3644 }
3645 }
3646
3647 // output starts here
3648
3649 // define userstack size
3650 if (g_func_pp->is_userstack) {
3651 fprintf(fout, "#ifndef US_SZ_%s\n", g_func_pp->name);
3652 fprintf(fout, "#define US_SZ_%s USERSTACK_SIZE\n", g_func_pp->name);
3653 fprintf(fout, "#endif\n");
3654 }
3655
3656 // the function itself
3657 fprintf(fout, "%s ", g_func_pp->ret_type.name);
3658 output_pp_attrs(fout, g_func_pp, g_ida_func_attr & IDAFA_NORETURN);
3659 fprintf(fout, "%s(", g_func_pp->name);
3660
3661 for (i = 0; i < g_func_pp->argc; i++) {
3662 if (i > 0)
3663 fprintf(fout, ", ");
3664 if (g_func_pp->arg[i].fptr != NULL) {
3665 // func pointer..
3666 pp = g_func_pp->arg[i].fptr;
3667 fprintf(fout, "%s (", pp->ret_type.name);
3668 output_pp_attrs(fout, pp, 0);
3669 fprintf(fout, "*a%d)(", i + 1);
3670 for (j = 0; j < pp->argc; j++) {
3671 if (j > 0)
3672 fprintf(fout, ", ");
3673 if (pp->arg[j].fptr)
3674 ferr(ops, "nested fptr\n");
3675 fprintf(fout, "%s", pp->arg[j].type.name);
3676 }
3677 if (pp->is_vararg) {
3678 if (j > 0)
3679 fprintf(fout, ", ");
3680 fprintf(fout, "...");
3681 }
3682 fprintf(fout, ")");
3683 }
3684 else if (g_func_pp->arg[i].type.is_retreg) {
3685 fprintf(fout, "u32 *r_%s", g_func_pp->arg[i].reg);
3686 }
3687 else {
3688 fprintf(fout, "%s a%d", g_func_pp->arg[i].type.name, i + 1);
3689 }
3690 }
3691 if (g_func_pp->is_vararg) {
3692 if (i > 0)
3693 fprintf(fout, ", ");
3694 fprintf(fout, "...");
3695 }
3696
3697 fprintf(fout, ")\n{\n");
3698
3699 // declare indirect functions
3700 for (i = 0; i < opcnt; i++) {
3701 po = &ops[i];
3702 if (po->flags & OPF_RMD)
3703 continue;
3704
3705 if (po->op == OP_CALL) {
3706 pp = po->pp;
3707 if (pp == NULL)
3708 ferr(po, "NULL pp\n");
3709
3710 if (pp->is_fptr && !(pp->name[0] != 0 && pp->is_arg)) {
3711 if (pp->name[0] != 0) {
3712 memmove(pp->name + 2, pp->name, strlen(pp->name) + 1);
3713 memcpy(pp->name, "i_", 2);
3714
3715 // might be declared already
3716 found = 0;
3717 for (j = 0; j < i; j++) {
3718 if (ops[j].op == OP_CALL && (pp_tmp = ops[j].pp)) {
3719 if (pp_tmp->is_fptr && IS(pp->name, pp_tmp->name)) {
3720 found = 1;
3721 break;
3722 }
3723 }
3724 }
3725 if (found)
3726 continue;
3727 }
3728 else
3729 snprintf(pp->name, sizeof(pp->name), "icall%d", i);
3730
3731 fprintf(fout, " %s (", pp->ret_type.name);
3732 output_pp_attrs(fout, pp, 0);
3733 fprintf(fout, "*%s)(", pp->name);
3734 for (j = 0; j < pp->argc; j++) {
3735 if (j > 0)
3736 fprintf(fout, ", ");
3737 fprintf(fout, "%s a%d", pp->arg[j].type.name, j + 1);
3738 }
3739 fprintf(fout, ");\n");
3740 }
3741 }
3742 }
3743
3744 // output LUTs/jumptables
3745 for (i = 0; i < g_func_pd_cnt; i++) {
3746 pd = &g_func_pd[i];
3747 fprintf(fout, " static const ");
3748 if (pd->type == OPT_OFFSET) {
3749 fprintf(fout, "void *jt_%s[] =\n { ", pd->label);
3750
3751 for (j = 0; j < pd->count; j++) {
3752 if (j > 0)
3753 fprintf(fout, ", ");
3754 fprintf(fout, "&&%s", pd->d[j].u.label);
3755 }
3756 }
3757 else {
3758 fprintf(fout, "%s %s[] =\n { ",
3759 lmod_type_u(ops, pd->lmod), pd->label);
3760
3761 for (j = 0; j < pd->count; j++) {
3762 if (j > 0)
3763 fprintf(fout, ", ");
3764 fprintf(fout, "%u", pd->d[j].u.val);
3765 }
3766 }
3767 fprintf(fout, " };\n");
3768 had_decl = 1;
3769 }
3770
3771 // declare stack frame, va_arg
3772 if (g_stack_fsz) {
3773 fprintf(fout, " union { u32 d[%d]; u16 w[%d]; u8 b[%d]; } sf;\n",
3774 (g_stack_fsz + 3) / 4, (g_stack_fsz + 1) / 2, g_stack_fsz);
3775 had_decl = 1;
3776 }
3777
3778 if (g_func_pp->is_userstack) {
3779 fprintf(fout, " u32 fake_sf[US_SZ_%s / 4];\n", g_func_pp->name);
3780 fprintf(fout, " u32 *esp = &fake_sf[sizeof(fake_sf) / 4];\n");
3781 had_decl = 1;
3782 }
3783
3784 if (g_func_pp->is_vararg) {
3785 fprintf(fout, " va_list ap;\n");
3786 had_decl = 1;
3787 }
3788
3789 // declare arg-registers
3790 for (i = 0; i < g_func_pp->argc; i++) {
3791 if (g_func_pp->arg[i].reg != NULL) {
3792 reg = char_array_i(regs_r32,
3793 ARRAY_SIZE(regs_r32), g_func_pp->arg[i].reg);
3794 if (regmask & (1 << reg)) {
3795 if (g_func_pp->arg[i].type.is_retreg)
3796 fprintf(fout, " u32 %s = *r_%s;\n",
3797 g_func_pp->arg[i].reg, g_func_pp->arg[i].reg);
3798 else
3799 fprintf(fout, " u32 %s = (u32)a%d;\n",
3800 g_func_pp->arg[i].reg, i + 1);
3801 }
3802 else {
3803 if (g_func_pp->arg[i].type.is_retreg)
3804 ferr(ops, "retreg '%s' is unused?\n",
3805 g_func_pp->arg[i].reg);
3806 fprintf(fout, " // %s = a%d; // unused\n",
3807 g_func_pp->arg[i].reg, i + 1);
3808 }
3809 had_decl = 1;
3810 }
3811 }
3812
3813 regmask_now = regmask & ~regmask_arg;
3814 regmask_now &= ~(1 << xSP);
3815 if (regmask_now) {
3816 for (reg = 0; reg < 8; reg++) {
3817 if (regmask_now & (1 << reg)) {
3818 fprintf(fout, " u32 %s", regs_r32[reg]);
3819 if (regmask_init & (1 << reg))
3820 fprintf(fout, " = 0");
3821 fprintf(fout, ";\n");
3822 had_decl = 1;
3823 }
3824 }
3825 }
3826
3827 if (regmask_save) {
3828 for (reg = 0; reg < 8; reg++) {
3829 if (regmask_save & (1 << reg)) {
3830 fprintf(fout, " u32 s_%s;\n", regs_r32[reg]);
3831 had_decl = 1;
3832 }
3833 }
3834 }
3835
3836 if (save_arg_vars) {
3837 for (reg = 0; reg < 32; reg++) {
3838 if (save_arg_vars & (1 << reg)) {
3839 fprintf(fout, " u32 s_a%d;\n", reg + 1);
3840 had_decl = 1;
3841 }
3842 }
3843 }
3844
3845 if (cond_vars) {
3846 for (i = 0; i < 8; i++) {
3847 if (cond_vars & (1 << i)) {
3848 fprintf(fout, " u32 cond_%s;\n", parsed_flag_op_names[i]);
3849 had_decl = 1;
3850 }
3851 }
3852 }
3853
3854 if (need_tmp_var) {
3855 fprintf(fout, " u32 tmp;\n");
3856 had_decl = 1;
3857 }
3858
3859 if (need_tmp64) {
3860 fprintf(fout, " u64 tmp64;\n");
3861 had_decl = 1;
3862 }
3863
3864 if (had_decl)
3865 fprintf(fout, "\n");
3866
3867 if (g_func_pp->is_vararg) {
3868 if (g_func_pp->argc_stack == 0)
3869 ferr(ops, "vararg func without stack args?\n");
3870 fprintf(fout, " va_start(ap, a%d);\n", g_func_pp->argc);
3871 }
3872
3873 // output ops
3874 for (i = 0; i < opcnt; i++)
3875 {
3876 if (g_labels[i][0] != 0) {
3877 fprintf(fout, "\n%s:\n", g_labels[i]);
3878 label_pending = 1;
3879
3880 delayed_flag_op = NULL;
3881 last_arith_dst = NULL;
3882 }
3883
3884 po = &ops[i];
3885 if (po->flags & OPF_RMD)
3886 continue;
3887
3888 no_output = 0;
3889
3890 #define assert_operand_cnt(n_) \
3891 if (po->operand_cnt != n_) \
3892 ferr(po, "operand_cnt is %d/%d\n", po->operand_cnt, n_)
3893
3894 // conditional/flag using op?
3895 if (po->flags & OPF_CC)
3896 {
3897 int is_delayed = 0;
3898
3899 tmp_op = po->datap;
3900
3901 // we go through all this trouble to avoid using parsed_flag_op,
3902 // which makes generated code much nicer
3903 if (delayed_flag_op != NULL)
3904 {
3905 out_cmp_test(buf1, sizeof(buf1), delayed_flag_op,
3906 po->pfo, po->pfo_inv);
3907 is_delayed = 1;
3908 }
3909 else if (last_arith_dst != NULL
3910 && (po->pfo == PFO_Z || po->pfo == PFO_S || po->pfo == PFO_P
3911 || (tmp_op && (tmp_op->op == OP_AND || tmp_op->op == OP_OR))
3912 ))
3913 {
3914 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3915 out_test_for_cc(buf1, sizeof(buf1), po, po->pfo, po->pfo_inv,
3916 last_arith_dst->lmod, buf3);
3917 is_delayed = 1;
3918 }
3919 else if (tmp_op != NULL) {
3920 // use preprocessed flag calc results
3921 if (!(tmp_op->pfomask & (1 << po->pfo)))
3922 ferr(po, "not prepared for pfo %d\n", po->pfo);
3923
3924 // note: pfo_inv was not yet applied
3925 snprintf(buf1, sizeof(buf1), "(%scond_%s)",
3926 po->pfo_inv ? "!" : "", parsed_flag_op_names[po->pfo]);
3927 }
3928 else {
3929 ferr(po, "all methods of finding comparison failed\n");
3930 }
3931
3932 if (po->flags & OPF_JMP) {
3933 fprintf(fout, " if %s", buf1);
3934 }
3935 else if (po->op == OP_RCL || po->op == OP_RCR
3936 || po->op == OP_ADC || po->op == OP_SBB)
3937 {
3938 if (is_delayed)
3939 fprintf(fout, " cond_%s = %s;\n",
3940 parsed_flag_op_names[po->pfo], buf1);
3941 }
3942 else if (po->flags & OPF_DATA) { // SETcc
3943 out_dst_opr(buf2, sizeof(buf2), po, &po->operand[0]);
3944 fprintf(fout, " %s = %s;", buf2, buf1);
3945 }
3946 else {
3947 ferr(po, "unhandled conditional op\n");
3948 }
3949 }
3950
3951 pfomask = po->pfomask;
3952
3953 if (po->flags & (OPF_REPZ|OPF_REPNZ)) {
3954 struct parsed_opr opr = {0,};
3955 opr.type = OPT_REG;
3956 opr.reg = xCX;
3957 opr.lmod = OPLM_DWORD;
3958 ret = try_resolve_const(i, &opr, opcnt * 7 + i, &uval);
3959
3960 if (ret != 1 || uval == 0) {
3961 // we need initial flags for ecx=0 case..
3962 if (i > 0 && ops[i - 1].op == OP_XOR
3963 && IS(ops[i - 1].operand[0].name,
3964 ops[i - 1].operand[1].name))
3965 {
3966 fprintf(fout, " cond_z = ");
3967 if (pfomask & (1 << PFO_C))
3968 fprintf(fout, "cond_c = ");
3969 fprintf(fout, "0;\n");
3970 }
3971 else if (last_arith_dst != NULL) {
3972 out_src_opr_u32(buf3, sizeof(buf3), po, last_arith_dst);
3973 out_test_for_cc(buf1, sizeof(buf1), po, PFO_Z, 0,
3974 last_arith_dst->lmod, buf3);
3975 fprintf(fout, " cond_z = %s;\n", buf1);
3976 }
3977 else
3978 ferr(po, "missing initial ZF\n");
3979 }
3980 }
3981
3982 switch (po->op)
3983 {
3984 case OP_MOV:
3985 assert_operand_cnt(2);
3986 propagate_lmod(po, &po->operand[0], &po->operand[1]);
3987 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
3988 default_cast_to(buf3, sizeof(buf3), &po->operand[0]);
3989 fprintf(fout, " %s = %s;", buf1,
3990 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
3991 buf3, 0));
3992 break;
3993
3994 case OP_LEA:
3995 assert_operand_cnt(2);
3996 po->operand[1].lmod = OPLM_DWORD; // always
3997 fprintf(fout, " %s = %s;",
3998 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
3999 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4000 NULL, 1));
4001 break;
4002
4003 case OP_MOVZX:
4004 assert_operand_cnt(2);
4005 fprintf(fout, " %s = %s;",
4006 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4007 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4008 break;
4009
4010 case OP_MOVSX:
4011 assert_operand_cnt(2);
4012 switch (po->operand[1].lmod) {
4013 case OPLM_BYTE:
4014 strcpy(buf3, "(s8)");
4015 break;
4016 case OPLM_WORD:
4017 strcpy(buf3, "(s16)");
4018 break;
4019 default:
4020 ferr(po, "invalid src lmod: %d\n", po->operand[1].lmod);
4021 }
4022 fprintf(fout, " %s = %s;",
4023 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4024 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4025 buf3, 0));
4026 break;
4027
4028 case OP_XCHG:
4029 assert_operand_cnt(2);
4030 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4031 fprintf(fout, " tmp = %s;",
4032 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0], "", 0));
4033 fprintf(fout, " %s = %s;",
4034 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4035 out_src_opr(buf2, sizeof(buf2), po, &po->operand[1],
4036 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4037 fprintf(fout, " %s = %stmp;",
4038 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[1]),
4039 default_cast_to(buf3, sizeof(buf3), &po->operand[1]));
4040 snprintf(g_comment, sizeof(g_comment), "xchg");
4041 break;
4042
4043 case OP_NOT:
4044 assert_operand_cnt(1);
4045 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4046 fprintf(fout, " %s = ~%s;", buf1, buf1);
4047 break;
4048
4049 case OP_CDQ:
4050 assert_operand_cnt(2);
4051 fprintf(fout, " %s = (s32)%s >> 31;",
4052 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4053 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4054 strcpy(g_comment, "cdq");
4055 break;
4056
4057 case OP_LODS:
4058 assert_operand_cnt(3);
4059 if (po->flags & OPF_REP) {
4060 // hmh..
4061 ferr(po, "TODO\n");
4062 }
4063 else {
4064 fprintf(fout, " eax = %sesi; esi %c= %d;",
4065 lmod_cast_u_ptr(po, po->operand[0].lmod),
4066 (po->flags & OPF_DF) ? '-' : '+',
4067 lmod_bytes(po, po->operand[0].lmod));
4068 strcpy(g_comment, "lods");
4069 }
4070 break;
4071
4072 case OP_STOS:
4073 assert_operand_cnt(3);
4074 if (po->flags & OPF_REP) {
4075 fprintf(fout, " for (; ecx != 0; ecx--, edi %c= %d)\n",
4076 (po->flags & OPF_DF) ? '-' : '+',
4077 lmod_bytes(po, po->operand[0].lmod));
4078 fprintf(fout, " %sedi = eax;",
4079 lmod_cast_u_ptr(po, po->operand[0].lmod));
4080 strcpy(g_comment, "rep stos");
4081 }
4082 else {
4083 fprintf(fout, " %sedi = eax; edi %c= %d;",
4084 lmod_cast_u_ptr(po, po->operand[0].lmod),
4085 (po->flags & OPF_DF) ? '-' : '+',
4086 lmod_bytes(po, po->operand[0].lmod));
4087 strcpy(g_comment, "stos");
4088 }
4089 break;
4090
4091 case OP_MOVS:
4092 assert_operand_cnt(3);
4093 j = lmod_bytes(po, po->operand[0].lmod);
4094 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4095 l = (po->flags & OPF_DF) ? '-' : '+';
4096 if (po->flags & OPF_REP) {
4097 fprintf(fout,
4098 " for (; ecx != 0; ecx--, edi %c= %d, esi %c= %d)\n",
4099 l, j, l, j);
4100 fprintf(fout,
4101 " %sedi = %sesi;", buf1, buf1);
4102 strcpy(g_comment, "rep movs");
4103 }
4104 else {
4105 fprintf(fout, " %sedi = %sesi; edi %c= %d; esi %c= %d;",
4106 buf1, buf1, l, j, l, j);
4107 strcpy(g_comment, "movs");
4108 }
4109 break;
4110
4111 case OP_CMPS:
4112 // repe ~ repeat while ZF=1
4113 assert_operand_cnt(3);
4114 j = lmod_bytes(po, po->operand[0].lmod);
4115 strcpy(buf1, lmod_cast_u_ptr(po, po->operand[0].lmod));
4116 l = (po->flags & OPF_DF) ? '-' : '+';
4117 if (po->flags & OPF_REP) {
4118 fprintf(fout,
4119 " for (; ecx != 0; ecx--) {\n");
4120 if (pfomask & (1 << PFO_C)) {
4121 // ugh..
4122 fprintf(fout,
4123 " cond_c = %sesi < %sedi;\n", buf1, buf1);
4124 pfomask &= ~(1 << PFO_C);
4125 }
4126 fprintf(fout,
4127 " cond_z = (%sesi == %sedi); esi %c= %d, edi %c= %d;\n",
4128 buf1, buf1, l, j, l, j);
4129 fprintf(fout,
4130 " if (cond_z %s 0) break;\n",
4131 (po->flags & OPF_REPZ) ? "==" : "!=");
4132 fprintf(fout,
4133 " }");
4134 snprintf(g_comment, sizeof(g_comment), "rep%s cmps",
4135 (po->flags & OPF_REPZ) ? "e" : "ne");
4136 }
4137 else {
4138 fprintf(fout,
4139 " cond_z = (%sesi == %sedi); esi %c= %d; edi %c= %d;",
4140 buf1, buf1, l, j, l, j);
4141 strcpy(g_comment, "cmps");
4142 }
4143 pfomask &= ~(1 << PFO_Z);
4144 last_arith_dst = NULL;
4145 delayed_flag_op = NULL;
4146 break;
4147
4148 case OP_SCAS:
4149 // only does ZF (for now)
4150 // repe ~ repeat while ZF=1
4151 assert_operand_cnt(3);
4152 j = lmod_bytes(po, po->operand[0].lmod);
4153 l = (po->flags & OPF_DF) ? '-' : '+';
4154 if (po->flags & OPF_REP) {
4155 fprintf(fout,
4156 " for (; ecx != 0; ecx--) {\n");
4157 fprintf(fout,
4158 " cond_z = (%seax == %sedi); edi %c= %d;\n",
4159 lmod_cast_u(po, po->operand[0].lmod),
4160 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4161 fprintf(fout,
4162 " if (cond_z %s 0) break;\n",
4163 (po->flags & OPF_REPZ) ? "==" : "!=");
4164 fprintf(fout,
4165 " }");
4166 snprintf(g_comment, sizeof(g_comment), "rep%s scas",
4167 (po->flags & OPF_REPZ) ? "e" : "ne");
4168 }
4169 else {
4170 fprintf(fout, " cond_z = (%seax == %sedi); edi %c= %d;",
4171 lmod_cast_u(po, po->operand[0].lmod),
4172 lmod_cast_u_ptr(po, po->operand[0].lmod), l, j);
4173 strcpy(g_comment, "scas");
4174 }
4175 pfomask &= ~(1 << PFO_Z);
4176 last_arith_dst = NULL;
4177 delayed_flag_op = NULL;
4178 break;
4179
4180 // arithmetic w/flags
4181 case OP_AND:
4182 case OP_OR:
4183 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4184 // fallthrough
4185 dualop_arith:
4186 assert_operand_cnt(2);
4187 fprintf(fout, " %s %s= %s;",
4188 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4189 op_to_c(po),
4190 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4191 output_std_flags(fout, po, &pfomask, buf1);
4192 last_arith_dst = &po->operand[0];
4193 delayed_flag_op = NULL;
4194 break;
4195
4196 case OP_SHL:
4197 case OP_SHR:
4198 assert_operand_cnt(2);
4199 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4200 if (pfomask & (1 << PFO_C)) {
4201 if (po->operand[1].type == OPT_CONST) {
4202 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4203 j = po->operand[1].val;
4204 j %= l;
4205 if (j != 0) {
4206 if (po->op == OP_SHL)
4207 j = l - j;
4208 else
4209 j -= 1;
4210 fprintf(fout, " cond_c = (%s >> %d) & 1;\n",
4211 buf1, j);
4212 }
4213 else
4214 ferr(po, "zero shift?\n");
4215 }
4216 else
4217 ferr(po, "TODO\n");
4218 pfomask &= ~(1 << PFO_C);
4219 }
4220 fprintf(fout, " %s %s= %s;", buf1, op_to_c(po),
4221 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4222 output_std_flags(fout, po, &pfomask, buf1);
4223 last_arith_dst = &po->operand[0];
4224 delayed_flag_op = NULL;
4225 break;
4226
4227 case OP_SAR:
4228 assert_operand_cnt(2);
4229 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4230 fprintf(fout, " %s = %s%s >> %s;", buf1,
4231 lmod_cast_s(po, po->operand[0].lmod), buf1,
4232 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4233 output_std_flags(fout, po, &pfomask, buf1);
4234 last_arith_dst = &po->operand[0];
4235 delayed_flag_op = NULL;
4236 break;
4237
4238 case OP_ROL:
4239 case OP_ROR:
4240 assert_operand_cnt(2);
4241 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4242 if (po->operand[1].type == OPT_CONST) {
4243 j = po->operand[1].val;
4244 j %= lmod_bytes(po, po->operand[0].lmod) * 8;
4245 fprintf(fout, po->op == OP_ROL ?
4246 " %s = (%s << %d) | (%s >> %d);" :
4247 " %s = (%s >> %d) | (%s << %d);",
4248 buf1, buf1, j, buf1,
4249 lmod_bytes(po, po->operand[0].lmod) * 8 - j);
4250 }
4251 else
4252 ferr(po, "TODO\n");
4253 output_std_flags(fout, po, &pfomask, buf1);
4254 last_arith_dst = &po->operand[0];
4255 delayed_flag_op = NULL;
4256 break;
4257
4258 case OP_RCL:
4259 case OP_RCR:
4260 assert_operand_cnt(2);
4261 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4262 l = lmod_bytes(po, po->operand[0].lmod) * 8;
4263 if (po->operand[1].type == OPT_CONST) {
4264 j = po->operand[1].val % l;
4265 if (j == 0)
4266 ferr(po, "zero rotate\n");
4267 fprintf(fout, " tmp = (%s >> %d) & 1;\n",
4268 buf1, (po->op == OP_RCL) ? (l - j) : (j - 1));
4269 if (po->op == OP_RCL) {
4270 fprintf(fout,
4271 " %s = (%s << %d) | (cond_c << %d)",
4272 buf1, buf1, j, j - 1);
4273 if (j != 1)
4274 fprintf(fout, " | (%s >> %d)", buf1, l + 1 - j);
4275 }
4276 else {
4277 fprintf(fout,
4278 " %s = (%s >> %d) | (cond_c << %d)",
4279 buf1, buf1, j, l - j);
4280 if (j != 1)
4281 fprintf(fout, " | (%s << %d)", buf1, l + 1 - j);
4282 }
4283 fprintf(fout, ";\n");
4284 fprintf(fout, " cond_c = tmp;");
4285 }
4286 else
4287 ferr(po, "TODO\n");
4288 strcpy(g_comment, (po->op == OP_RCL) ? "rcl" : "rcr");
4289 output_std_flags(fout, po, &pfomask, buf1);
4290 last_arith_dst = &po->operand[0];
4291 delayed_flag_op = NULL;
4292 break;
4293
4294 case OP_XOR:
4295 assert_operand_cnt(2);
4296 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4297 if (IS(opr_name(po, 0), opr_name(po, 1))) {
4298 // special case for XOR
4299 if (pfomask & (1 << PFO_BE)) { // weird, but it happens..
4300 fprintf(fout, " cond_be = 1;\n");
4301 pfomask &= ~(1 << PFO_BE);
4302 }
4303 fprintf(fout, " %s = 0;",
4304 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4305 last_arith_dst = &po->operand[0];
4306 delayed_flag_op = NULL;
4307 break;
4308 }
4309 goto dualop_arith;
4310
4311 case OP_ADD:
4312 assert_operand_cnt(2);
4313 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4314 if (pfomask & (1 << PFO_C)) {
4315 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4316 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4317 if (po->operand[0].lmod == OPLM_DWORD) {
4318 fprintf(fout, " tmp64 = (u64)%s + %s;\n", buf1, buf2);
4319 fprintf(fout, " cond_c = tmp64 >> 32;\n");
4320 fprintf(fout, " %s = (u32)tmp64;",
4321 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4322 strcat(g_comment, "add64");
4323 }
4324 else {
4325 fprintf(fout, " cond_c = ((u32)%s + %s) >> %d;\n",
4326 buf1, buf2, lmod_bytes(po, po->operand[0].lmod) * 8);
4327 fprintf(fout, " %s += %s;",
4328 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4329 buf2);
4330 }
4331 pfomask &= ~(1 << PFO_C);
4332 output_std_flags(fout, po, &pfomask, buf1);
4333 last_arith_dst = &po->operand[0];
4334 delayed_flag_op = NULL;
4335 break;
4336 }
4337 goto dualop_arith;
4338
4339 case OP_SUB:
4340 assert_operand_cnt(2);
4341 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4342 if (pfomask & (1 << PFO_C)) {
4343 fprintf(fout, " cond_c = %s < %s;\n",
4344 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]),
4345 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4346 pfomask &= ~(1 << PFO_C);
4347 }
4348 goto dualop_arith;
4349
4350 case OP_ADC:
4351 case OP_SBB:
4352 assert_operand_cnt(2);
4353 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4354 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4355 if (po->op == OP_SBB
4356 && IS(po->operand[0].name, po->operand[1].name))
4357 {
4358 // avoid use of unitialized var
4359 fprintf(fout, " %s = -cond_c;", buf1);
4360 // carry remains what it was
4361 pfomask &= ~(1 << PFO_C);
4362 }
4363 else {
4364 fprintf(fout, " %s %s= %s + cond_c;", buf1, op_to_c(po),
4365 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]));
4366 }
4367 output_std_flags(fout, po, &pfomask, buf1);
4368 last_arith_dst = &po->operand[0];
4369 delayed_flag_op = NULL;
4370 break;
4371
4372 case OP_BSF:
4373 assert_operand_cnt(2);
4374 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[1]);
4375 fprintf(fout, " %s = %s ? __builtin_ffs(%s) - 1 : 0;",
4376 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]),
4377 buf2, buf2);
4378 output_std_flags(fout, po, &pfomask, buf1);
4379 last_arith_dst = &po->operand[0];
4380 delayed_flag_op = NULL;
4381 strcat(g_comment, "bsf");
4382 break;
4383
4384 case OP_INC:
4385 case OP_DEC:
4386 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4387 if (po->operand[0].type == OPT_REG) {
4388 strcpy(buf2, po->op == OP_INC ? "++" : "--");
4389 fprintf(fout, " %s%s;", buf1, buf2);
4390 }
4391 else {
4392 strcpy(buf2, po->op == OP_INC ? "+" : "-");
4393 fprintf(fout, " %s %s= 1;", buf1, buf2);
4394 }
4395 output_std_flags(fout, po, &pfomask, buf1);
4396 last_arith_dst = &po->operand[0];
4397 delayed_flag_op = NULL;
4398 break;
4399
4400 case OP_NEG:
4401 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4402 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]);
4403 fprintf(fout, " %s = -%s%s;", buf1,
4404 lmod_cast_s(po, po->operand[0].lmod), buf2);
4405 last_arith_dst = &po->operand[0];
4406 delayed_flag_op = NULL;
4407 if (pfomask & (1 << PFO_C)) {
4408 fprintf(fout, "\n cond_c = (%s != 0);", buf1);
4409 pfomask &= ~(1 << PFO_C);
4410 }
4411 break;
4412
4413 case OP_IMUL:
4414 if (po->operand_cnt == 2) {
4415 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4416 goto dualop_arith;
4417 }
4418 if (po->operand_cnt == 3)
4419 ferr(po, "TODO imul3\n");
4420 // fallthrough
4421 case OP_MUL:
4422 assert_operand_cnt(1);
4423 switch (po->operand[0].lmod) {
4424 case OPLM_DWORD:
4425 strcpy(buf1, po->op == OP_IMUL ? "(s64)(s32)" : "(u64)");
4426 fprintf(fout, " tmp64 = %seax * %s%s;\n", buf1, buf1,
4427 out_src_opr_u32(buf2, sizeof(buf2), po, &po->operand[0]));
4428 fprintf(fout, " edx = tmp64 >> 32;\n");
4429 fprintf(fout, " eax = tmp64;");
4430 break;
4431 case OPLM_BYTE:
4432 strcpy(buf1, po->op == OP_IMUL ? "(s16)(s8)" : "(u16)(u8)");
4433 fprintf(fout, " LOWORD(eax) = %seax * %s;", buf1,
4434 out_src_opr(buf2, sizeof(buf2), po, &po->operand[0],
4435 buf1, 0));
4436 break;
4437 default:
4438 ferr(po, "TODO: unhandled mul type\n");
4439 break;
4440 }
4441 last_arith_dst = NULL;
4442 delayed_flag_op = NULL;
4443 break;
4444
4445 case OP_DIV:
4446 case OP_IDIV:
4447 assert_operand_cnt(1);
4448 if (po->operand[0].lmod != OPLM_DWORD)
4449 ferr(po, "unhandled lmod %d\n", po->operand[0].lmod);
4450
4451 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4452 strcpy(buf2, lmod_cast(po, po->operand[0].lmod,
4453 po->op == OP_IDIV));
4454 switch (po->operand[0].lmod) {
4455 case OPLM_DWORD:
4456 if (po->flags & OPF_32BIT)
4457 snprintf(buf3, sizeof(buf3), "%seax", buf2);
4458 else {
4459 fprintf(fout, " tmp64 = ((u64)edx << 32) | eax;\n");
4460 snprintf(buf3, sizeof(buf3), "%stmp64",
4461 (po->op == OP_IDIV) ? "(s64)" : "");
4462 }
4463 if (po->operand[0].type == OPT_REG
4464 && po->operand[0].reg == xDX)
4465 {
4466 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
4467 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
4468 }
4469 else {
4470 fprintf(fout, " edx = %s %% %s%s;\n", buf3, buf2, buf1);
4471 fprintf(fout, " eax = %s / %s%s;", buf3, buf2, buf1);
4472 }
4473 break;
4474 default:
4475 ferr(po, "unhandled division type\n");
4476 }
4477 last_arith_dst = NULL;
4478 delayed_flag_op = NULL;
4479 break;
4480
4481 case OP_TEST:
4482 case OP_CMP:
4483 propagate_lmod(po, &po->operand[0], &po->operand[1]);
4484 if (pfomask != 0) {
4485 for (j = 0; j < 8; j++) {
4486 if (pfomask & (1 << j)) {
4487 out_cmp_test(buf1, sizeof(buf1), po, j, 0);
4488 fprintf(fout, " cond_%s = %s;",
4489 parsed_flag_op_names[j], buf1);
4490 }
4491 }
4492 pfomask = 0;
4493 }
4494 else
4495 no_output = 1;
4496 last_arith_dst = NULL;
4497 delayed_flag_op = po;
4498 break;
4499
4500 case OP_SCC:
4501 // SETcc - should already be handled
4502 break;
4503
4504 // note: we reuse OP_Jcc for SETcc, only flags differ
4505 case OP_JCC:
4506 fprintf(fout, "\n goto %s;", po->operand[0].name);
4507 break;
4508
4509 case OP_JECXZ:
4510 fprintf(fout, " if (ecx == 0)\n");
4511 fprintf(fout, " goto %s;", po->operand[0].name);
4512 strcat(g_comment, "jecxz");
4513 break;
4514
4515 case OP_JMP:
4516 assert_operand_cnt(1);
4517 last_arith_dst = NULL;
4518 delayed_flag_op = NULL;
4519
4520 if (po->operand[0].type == OPT_REGMEM) {
4521 ret = sscanf(po->operand[0].name, "%[^[][%[^*]*4]",
4522 buf1, buf2);
4523 if (ret != 2)
4524 ferr(po, "parse failure for jmp '%s'\n",
4525 po->operand[0].name);
4526 fprintf(fout, " goto *jt_%s[%s];", buf1, buf2);
4527 break;
4528 }
4529 else if (po->operand[0].type != OPT_LABEL)
4530 ferr(po, "unhandled jmp type\n");
4531
4532 fprintf(fout, " goto %s;", po->operand[0].name);
4533 break;
4534
4535 case OP_CALL:
4536 assert_operand_cnt(1);
4537 pp = po->pp;
4538 my_assert_not(pp, NULL);
4539
4540 strcpy(buf3, " ");
4541 if (po->flags & OPF_CC) {
4542 // we treat conditional branch to another func
4543 // (yes such code exists..) as conditional tailcall
4544 strcat(buf3, " ");
4545 fprintf(fout, " {\n");
4546 }
4547
4548 if (pp->is_fptr && !pp->is_arg) {
4549 fprintf(fout, "%s%s = %s;\n", buf3, pp->name,
4550 out_src_opr(buf1, sizeof(buf1), po, &po->operand[0],
4551 "(void *)", 0));
4552 if (pp->is_unresolved)
4553 fprintf(fout, "%sunresolved_call(\"%s:%d\", %s);\n",
4554 buf3, asmfn, po->asmln, pp->name);
4555 }
4556
4557 fprintf(fout, "%s", buf3);
4558 if (strstr(pp->ret_type.name, "int64")) {
4559 if (po->flags & OPF_TAIL)
4560 ferr(po, "int64 and tail?\n");
4561 fprintf(fout, "tmp64 = ");
4562 }
4563 else if (!IS(pp->ret_type.name, "void")) {
4564 if (po->flags & OPF_TAIL) {
4565 if (!IS(g_func_pp->ret_type.name, "void")) {
4566 fprintf(fout, "return ");
4567 if (g_func_pp->ret_type.is_ptr != pp->ret_type.is_ptr)
4568 fprintf(fout, "(%s)", g_func_pp->ret_type.name);
4569 }
4570 }
4571 else if (regmask & (1 << xAX)) {
4572 fprintf(fout, "eax = ");
4573 if (pp->ret_type.is_ptr)
4574 fprintf(fout, "(u32)");
4575 }
4576 }
4577
4578 if (pp->name[0] == 0)
4579 ferr(po, "missing pp->name\n");
4580 fprintf(fout, "%s%s(", pp->name,
4581 pp->has_structarg ? "_sa" : "");
4582
4583 if (po->flags & OPF_ATAIL) {
4584 if (pp->argc_stack != g_func_pp->argc_stack
4585 || (pp->argc_stack > 0
4586 && pp->is_stdcall != g_func_pp->is_stdcall))
4587 ferr(po, "incompatible tailcall\n");
4588 if (g_func_pp->has_retreg)
4589 ferr(po, "TODO: retreg+tailcall\n");
4590
4591 for (arg = j = 0; arg < pp->argc; arg++) {
4592 if (arg > 0)
4593 fprintf(fout, ", ");
4594
4595 cast[0] = 0;
4596 if (pp->arg[arg].type.is_ptr)
4597 snprintf(cast, sizeof(cast), "(%s)",
4598 pp->arg[arg].type.name);
4599
4600 if (pp->arg[arg].reg != NULL) {
4601 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4602 continue;
4603 }
4604 // stack arg
4605 for (; j < g_func_pp->argc; j++)
4606 if (g_func_pp->arg[j].reg == NULL)
4607 break;
4608 fprintf(fout, "%sa%d", cast, j + 1);
4609 j++;
4610 }
4611 }
4612 else {
4613 for (arg = 0; arg < pp->argc; arg++) {
4614 if (arg > 0)
4615 fprintf(fout, ", ");
4616
4617 cast[0] = 0;
4618 if (pp->arg[arg].type.is_ptr)
4619 snprintf(cast, sizeof(cast), "(%s)",
4620 pp->arg[arg].type.name);
4621
4622 if (pp->arg[arg].reg != NULL) {
4623 if (pp->arg[arg].type.is_retreg)
4624 fprintf(fout, "&%s", pp->arg[arg].reg);
4625 else
4626 fprintf(fout, "%s%s", cast, pp->arg[arg].reg);
4627 continue;
4628 }
4629
4630 // stack arg
4631 tmp_op = pp->arg[arg].datap;
4632 if (tmp_op == NULL)
4633 ferr(po, "parsed_op missing for arg%d\n", arg);
4634
4635 if (tmp_op->flags & OPF_VAPUSH) {
4636 fprintf(fout, "ap");
4637 }
4638 else if (tmp_op->p_argpass != 0) {
4639 fprintf(fout, "a%d", tmp_op->p_argpass);
4640 }
4641 else if (tmp_op->p_argnum != 0) {
4642 fprintf(fout, "%ss_a%d", cast, tmp_op->p_argnum);
4643 }
4644 else {
4645 fprintf(fout, "%s",
4646 out_src_opr(buf1, sizeof(buf1),
4647 tmp_op, &tmp_op->operand[0], cast, 0));
4648 }
4649 }
4650 }
4651 fprintf(fout, ");");
4652
4653 if (strstr(pp->ret_type.name, "int64")) {
4654 fprintf(fout, "\n");
4655 fprintf(fout, "%sedx = tmp64 >> 32;\n", buf3);
4656 fprintf(fout, "%seax = tmp64;", buf3);
4657 }
4658
4659 if (pp->is_unresolved) {
4660 snprintf(buf2, sizeof(buf2), " unresolved %dreg",
4661 pp->argc_reg);
4662 strcat(g_comment, buf2);
4663 }
4664
4665 if (po->flags & OPF_TAIL) {
4666 ret = 0;
4667 if (i == opcnt - 1 || pp->is_noreturn)
4668 ret = 0;
4669 else if (IS(pp->ret_type.name, "void"))
4670 ret = 1;
4671 else if (IS(g_func_pp->ret_type.name, "void"))
4672 ret = 1;
4673 // else already handled as 'return f()'
4674
4675 if (ret) {
4676 if (!IS(g_func_pp->ret_type.name, "void")) {
4677 ferr(po, "int func -> void func tailcall?\n");
4678 }
4679 else {
4680 fprintf(fout, "\n%sreturn;", buf3);
4681 strcat(g_comment, " ^ tailcall");
4682 }
4683 }
4684 else
4685 strcat(g_comment, " tailcall");
4686 }
4687 if (pp->is_noreturn)
4688 strcat(g_comment, " noreturn");
4689 if ((po->flags & OPF_ATAIL) && pp->argc_stack > 0)
4690 strcat(g_comment, " argframe");
4691 if (po->flags & OPF_CC)
4692 strcat(g_comment, " cond");
4693
4694 if (po->flags & OPF_CC)
4695 fprintf(fout, "\n }");
4696
4697 delayed_flag_op = NULL;
4698 last_arith_dst = NULL;
4699 break;
4700
4701 case OP_RET:
4702 if (g_func_pp->is_vararg)
4703 fprintf(fout, " va_end(ap);\n");
4704 if (g_func_pp->has_retreg) {
4705 for (arg = 0; arg < g_func_pp->argc; arg++)
4706 if (g_func_pp->arg[arg].type.is_retreg)
4707 fprintf(fout, " *r_%s = %s;\n",
4708 g_func_pp->arg[arg].reg, g_func_pp->arg[arg].reg);
4709 }
4710
4711 if (IS(g_func_pp->ret_type.name, "void")) {
4712 if (i != opcnt - 1 || label_pending)
4713 fprintf(fout, " return;");
4714 }
4715 else if (g_func_pp->ret_type.is_ptr) {
4716 fprintf(fout, " return (%s)eax;",
4717 g_func_pp->ret_type.name);
4718 }
4719 else if (IS(g_func_pp->ret_type.name, "__int64"))
4720 fprintf(fout, " return ((u64)edx << 32) | eax;");
4721 else
4722 fprintf(fout, " return eax;");
4723
4724 last_arith_dst = NULL;
4725 delayed_flag_op = NULL;
4726 break;
4727
4728 case OP_PUSH:
4729 out_src_opr_u32(buf1, sizeof(buf1), po, &po->operand[0]);
4730 if (po->p_argnum != 0) {
4731 // special case - saved func arg
4732 fprintf(fout, " s_a%d = %s;", po->p_argnum, buf1);
4733 break;
4734 }
4735 else if (po->flags & OPF_RSAVE) {
4736 fprintf(fout, " s_%s = %s;", buf1, buf1);
4737 break;
4738 }
4739 else if (g_func_pp->is_userstack) {
4740 fprintf(fout, " *(--esp) = %s;", buf1);
4741 break;
4742 }
4743 if (!(g_ida_func_attr & IDAFA_NORETURN))
4744 ferr(po, "stray push encountered\n");
4745 no_output = 1;
4746 break;
4747
4748 case OP_POP:
4749 if (po->flags & OPF_RSAVE) {
4750 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4751 fprintf(fout, " %s = s_%s;", buf1, buf1);
4752 break;
4753 }
4754 else if (po->datap != NULL) {
4755 // push/pop pair
4756 tmp_op = po->datap;
4757 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]);
4758 fprintf(fout, " %s = %s;", buf1,
4759 out_src_opr(buf2, sizeof(buf2),
4760 tmp_op, &tmp_op->operand[0],
4761 default_cast_to(buf3, sizeof(buf3), &po->operand[0]), 0));
4762 break;
4763 }
4764 else if (g_func_pp->is_userstack) {
4765 fprintf(fout, " %s = *esp++;",
4766 out_dst_opr(buf1, sizeof(buf1), po, &po->operand[0]));
4767 break;
4768 }
4769 else
4770 ferr(po, "stray pop encountered\n");
4771 break;
4772
4773 case OP_NOP:
4774 no_output = 1;
4775 break;
4776
4777 default:
4778 no_output = 1;
4779 ferr(po, "unhandled op type %d, flags %x\n",
4780 po->op, po->flags);
4781 break;
4782 }
4783
4784 if (g_comment[0] != 0) {
4785 char *p = g_comment;
4786 while (my_isblank(*p))
4787 p++;
4788 fprintf(fout, " // %s", p);
4789 g_comment[0] = 0;
4790 no_output = 0;
4791 }
4792 if (!no_output)
4793 fprintf(fout, "\n");
4794
4795 // some sanity checking
4796 if (po->flags & OPF_REP) {
4797 if (po->op != OP_STOS && po->op != OP_MOVS
4798 && po->op != OP_CMPS && po->op != OP_SCAS)
4799 ferr(po, "unexpected rep\n");
4800 if (!(po->flags & (OPF_REPZ|OPF_REPNZ))
4801 && (po->op == OP_CMPS || po->op == OP_SCAS))
4802 ferr(po, "cmps/scas with plain rep\n");
4803 }
4804 if ((po->flags & (OPF_REPZ|OPF_REPNZ))
4805 && po->op != OP_CMPS && po->op != OP_SCAS)
4806 ferr(po, "unexpected repz/repnz\n");
4807
4808 if (pfomask != 0)
4809 ferr(po, "missed flag calc, pfomask=%x\n", pfomask);
4810
4811 // see is delayed flag stuff is still valid
4812 if (delayed_flag_op != NULL && delayed_flag_op != po) {
4813 if (is_any_opr_modified(delayed_flag_op, po, 0))
4814 delayed_flag_op = NULL;
4815 }
4816
4817 if (last_arith_dst != NULL && last_arith_dst != &po->operand[0]) {
4818 if (is_opr_modified(last_arith_dst, po))
4819 last_arith_dst = NULL;
4820 }
4821
4822 label_pending = 0;
4823 }
4824
4825 if (g_stack_fsz && !g_stack_frame_used)
4826 fprintf(fout, " (void)sf;\n");
4827
4828 fprintf(fout, "}\n\n");
4829
4830 // cleanup
4831 for (i = 0; i < opcnt; i++) {
4832 struct label_ref *lr, *lr_del;
4833
4834 lr = g_label_refs[i].next;
4835 while (lr != NULL) {
4836 lr_del = lr;
4837 lr = lr->next;
4838 free(lr_del);
4839 }
4840 g_label_refs[i].i = -1;
4841 g_label_refs[i].next = NULL;
4842
4843 if (ops[i].op == OP_CALL) {
4844 if (ops[i].pp)
4845 proto_release(ops[i].pp);
4846 }
4847 }
4848 g_func_pp = NULL;
4849}
4850
4851static void set_label(int i, const char *name)
4852{
4853 const char *p;
4854 int len;
4855
4856 len = strlen(name);
4857 p = strchr(name, ':');
4858 if (p != NULL)
4859 len = p - name;
4860
4861 if (len > sizeof(g_labels[0]) - 1)
4862 aerr("label '%s' too long: %d\n", name, len);
4863 if (g_labels[i][0] != 0 && !IS_START(g_labels[i], "algn_"))
4864 aerr("dupe label '%s' vs '%s'?\n", name, g_labels[i]);
4865 memcpy(g_labels[i], name, len);
4866 g_labels[i][len] = 0;
4867}
4868
4869// '=' needs special treatment..
4870static char *next_word_s(char *w, size_t wsize, char *s)
4871{
4872 size_t i;
4873
4874 s = sskip(s);
4875
4876 for (i = 0; i < wsize - 1; i++) {
4877 if (s[i] == 0 || my_isblank(s[i]) || (s[i] == '=' && i > 0))
4878 break;
4879 w[i] = s[i];
4880 }
4881 w[i] = 0;
4882
4883 if (s[i] != 0 && !my_isblank(s[i]) && s[i] != '=')
4884 printf("warning: '%s' truncated\n", w);
4885
4886 return s + i;
4887}
4888
4889struct chunk_item {
4890 char *name;
4891 long fptr;
4892 int asmln;
4893};
4894
4895static struct chunk_item *func_chunks;
4896static int func_chunk_cnt;
4897static int func_chunk_alloc;
4898
4899static void add_func_chunk(FILE *fasm, const char *name, int line)
4900{
4901 if (func_chunk_cnt >= func_chunk_alloc) {
4902 func_chunk_alloc *= 2;
4903 func_chunks = realloc(func_chunks,
4904 func_chunk_alloc * sizeof(func_chunks[0]));
4905 my_assert_not(func_chunks, NULL);
4906 }
4907 func_chunks[func_chunk_cnt].fptr = ftell(fasm);
4908 func_chunks[func_chunk_cnt].name = strdup(name);
4909 func_chunks[func_chunk_cnt].asmln = line;
4910 func_chunk_cnt++;
4911}
4912
4913static int cmp_chunks(const void *p1, const void *p2)
4914{
4915 const struct chunk_item *c1 = p1, *c2 = p2;
4916 return strcmp(c1->name, c2->name);
4917}
4918
4919static int cmpstringp(const void *p1, const void *p2)
4920{
4921 return strcmp(*(char * const *)p1, *(char * const *)p2);
4922}
4923
4924static void scan_ahead(FILE *fasm)
4925{
4926 char words[2][256];
4927 char line[256];
4928 long oldpos;
4929 int oldasmln;
4930 int wordc;
4931 char *p;
4932 int i;
4933
4934 oldpos = ftell(fasm);
4935 oldasmln = asmln;
4936
4937 while (fgets(line, sizeof(line), fasm))
4938 {
4939 wordc = 0;
4940 asmln++;
4941
4942 p = sskip(line);
4943 if (*p == 0)
4944 continue;
4945
4946 if (*p == ';')
4947 {
4948 // get rid of random tabs
4949 for (i = 0; line[i] != 0; i++)
4950 if (line[i] == '\t')
4951 line[i] = ' ';
4952
4953 if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
4954 {
4955 p += 30;
4956 next_word(words[0], sizeof(words[0]), p);
4957 if (words[0][0] == 0)
4958 aerr("missing name for func chunk?\n");
4959
4960 add_func_chunk(fasm, words[0], asmln);
4961 }
4962 else if (IS_START(p, "; sctend"))
4963 break;
4964
4965 continue;
4966 } // *p == ';'
4967
4968 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
4969 words[wordc][0] = 0;
4970 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
4971 if (*p == 0 || *p == ';') {
4972 wordc++;
4973 break;
4974 }
4975 }
4976
4977 if (wordc == 2 && IS(words[1], "ends"))
4978 break;
4979 }
4980
4981 fseek(fasm, oldpos, SEEK_SET);
4982 asmln = oldasmln;
4983}
4984
4985int main(int argc, char *argv[])
4986{
4987 FILE *fout, *fasm, *frlist;
4988 struct parsed_data *pd = NULL;
4989 int pd_alloc = 0;
4990 char **rlist = NULL;
4991 int rlist_len = 0;
4992 int rlist_alloc = 0;
4993 int func_chunks_used = 0;
4994 int func_chunks_sorted = 0;
4995 int func_chunk_i = -1;
4996 long func_chunk_ret = 0;
4997 int func_chunk_ret_ln = 0;
4998 int scanned_ahead = 0;
4999 char line[256];
5000 char words[20][256];
5001 enum opr_lenmod lmod;
5002 char *sctproto = NULL;
5003 int in_func = 0;
5004 int pending_endp = 0;
5005 int skip_func = 0;
5006 int skip_warned = 0;
5007 int eq_alloc;
5008 int verbose = 0;
5009 int multi_seg = 0;
5010 int end = 0;
5011 int arg_out;
5012 int arg;
5013 int pi = 0;
5014 int i, j;
5015 int ret, len;
5016 char *p;
5017 int wordc;
5018
5019 for (arg = 1; arg < argc; arg++) {
5020 if (IS(argv[arg], "-v"))
5021 verbose = 1;
5022 else if (IS(argv[arg], "-rf"))
5023 g_allow_regfunc = 1;
5024 else if (IS(argv[arg], "-m"))
5025 multi_seg = 1;
5026 else
5027 break;
5028 }
5029
5030 if (argc < arg + 3) {
5031 printf("usage:\n%s [-v] [-rf] [-m] <.c> <.asm> <hdrf> [rlist]*\n",
5032 argv[0]);
5033 return 1;
5034 }
5035
5036 arg_out = arg++;
5037
5038 asmfn = argv[arg++];
5039 fasm = fopen(asmfn, "r");
5040 my_assert_not(fasm, NULL);
5041
5042 hdrfn = argv[arg++];
5043 g_fhdr = fopen(hdrfn, "r");
5044 my_assert_not(g_fhdr, NULL);
5045
5046 rlist_alloc = 64;
5047 rlist = malloc(rlist_alloc * sizeof(rlist[0]));
5048 my_assert_not(rlist, NULL);
5049 // needs special handling..
5050 rlist[rlist_len++] = "__alloca_probe";
5051
5052 func_chunk_alloc = 32;
5053 func_chunks = malloc(func_chunk_alloc * sizeof(func_chunks[0]));
5054 my_assert_not(func_chunks, NULL);
5055
5056 memset(words, 0, sizeof(words));
5057
5058 for (; arg < argc; arg++) {
5059 frlist = fopen(argv[arg], "r");
5060 my_assert_not(frlist, NULL);
5061
5062 while (fgets(line, sizeof(line), frlist)) {
5063 p = sskip(line);
5064 if (*p == 0 || *p == ';')
5065 continue;
5066 if (*p == '#') {
5067 if (IS_START(p, "#if 0")
5068 || (g_allow_regfunc && IS_START(p, "#if NO_REGFUNC")))
5069 {
5070 skip_func = 1;
5071 }
5072 else if (IS_START(p, "#endif"))
5073 skip_func = 0;
5074 continue;
5075 }
5076 if (skip_func)
5077 continue;
5078
5079 p = next_word(words[0], sizeof(words[0]), p);
5080 if (words[0][0] == 0)
5081 continue;
5082
5083 if (rlist_len >= rlist_alloc) {
5084 rlist_alloc = rlist_alloc * 2 + 64;
5085 rlist = realloc(rlist, rlist_alloc * sizeof(rlist[0]));
5086 my_assert_not(rlist, NULL);
5087 }
5088 rlist[rlist_len++] = strdup(words[0]);
5089 }
5090 skip_func = 0;
5091
5092 fclose(frlist);
5093 frlist = NULL;
5094 }
5095
5096 if (rlist_len > 0)
5097 qsort(rlist, rlist_len, sizeof(rlist[0]), cmpstringp);
5098
5099 fout = fopen(argv[arg_out], "w");
5100 my_assert_not(fout, NULL);
5101
5102 eq_alloc = 128;
5103 g_eqs = malloc(eq_alloc * sizeof(g_eqs[0]));
5104 my_assert_not(g_eqs, NULL);
5105
5106 for (i = 0; i < ARRAY_SIZE(g_label_refs); i++) {
5107 g_label_refs[i].i = -1;
5108 g_label_refs[i].next = NULL;
5109 }
5110
5111 while (fgets(line, sizeof(line), fasm))
5112 {
5113 wordc = 0;
5114 asmln++;
5115
5116 p = sskip(line);
5117 if (*p == 0)
5118 continue;
5119
5120 // get rid of random tabs
5121 for (i = 0; line[i] != 0; i++)
5122 if (line[i] == '\t')
5123 line[i] = ' ';
5124
5125 if (*p == ';')
5126 {
5127 if (p[2] == '=' && IS_START(p, "; =============== S U B"))
5128 goto do_pending_endp; // eww..
5129
5130 if (p[2] == 'A' && IS_START(p, "; Attributes:"))
5131 {
5132 static const char *attrs[] = {
5133 "bp-based frame",
5134 "library function",
5135 "static",
5136 "noreturn",
5137 "thunk",
5138 "fpd=",
5139 };
5140
5141 // parse IDA's attribute-list comment
5142 g_ida_func_attr = 0;
5143 p = sskip(p + 13);
5144
5145 for (; *p != 0; p = sskip(p)) {
5146 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
5147 if (!strncmp(p, attrs[i], strlen(attrs[i]))) {
5148 g_ida_func_attr |= 1 << i;
5149 p += strlen(attrs[i]);
5150 break;
5151 }
5152 }
5153 if (i == ARRAY_SIZE(attrs)) {
5154 anote("unparsed IDA attr: %s\n", p);
5155 break;
5156 }
5157 if (IS(attrs[i], "fpd=")) {
5158 p = next_word(words[0], sizeof(words[0]), p);
5159 // ignore for now..
5160 }
5161 }
5162 }
5163 else if (p[2] == 'S' && IS_START(p, "; START OF FUNCTION CHUNK FOR "))
5164 {
5165 p += 30;
5166 next_word(words[0], sizeof(words[0]), p);
5167 if (words[0][0] == 0)
5168 aerr("missing name for func chunk?\n");
5169
5170 if (!scanned_ahead) {
5171 add_func_chunk(fasm, words[0], asmln);
5172 func_chunks_sorted = 0;
5173 }
5174 }
5175 else if (p[2] == 'E' && IS_START(p, "; END OF FUNCTION CHUNK"))
5176 {
5177 if (func_chunk_i >= 0) {
5178 if (func_chunk_i < func_chunk_cnt
5179 && IS(func_chunks[func_chunk_i].name, g_func))
5180 {
5181 // move on to next chunk
5182 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
5183 if (ret)
5184 aerr("seek failed for '%s' chunk #%d\n",
5185 g_func, func_chunk_i);
5186 asmln = func_chunks[func_chunk_i].asmln;
5187 func_chunk_i++;
5188 }
5189 else {
5190 if (func_chunk_ret == 0)
5191 aerr("no return from chunk?\n");
5192 fseek(fasm, func_chunk_ret, SEEK_SET);
5193 asmln = func_chunk_ret_ln;
5194 func_chunk_ret = 0;
5195 pending_endp = 1;
5196 }
5197 }
5198 }
5199 else if (p[2] == 'F' && IS_START(p, "; FUNCTION CHUNK AT ")) {
5200 func_chunks_used = 1;
5201 p += 20;
5202 if (IS_START(g_func, "sub_")) {
5203 unsigned long addr = strtoul(p, NULL, 16);
5204 unsigned long f_addr = strtoul(g_func + 4, NULL, 16);
5205 if (addr > f_addr && !scanned_ahead) {
5206 anote("scan_ahead caused by '%s', addr %lx\n",
5207 g_func, addr);
5208 scan_ahead(fasm);
5209 scanned_ahead = 1;
5210 func_chunks_sorted = 0;
5211 }
5212 }
5213 }
5214 continue;
5215 } // *p == ';'
5216
5217parse_words:
5218 for (i = wordc; i < ARRAY_SIZE(words); i++)
5219 words[i][0] = 0;
5220 for (wordc = 0; wordc < ARRAY_SIZE(words); wordc++) {
5221 p = sskip(next_word_s(words[wordc], sizeof(words[0]), p));
5222 if (*p == 0 || *p == ';') {
5223 wordc++;
5224 break;
5225 }
5226 }
5227 if (*p != 0 && *p != ';')
5228 aerr("too many words\n");
5229
5230 // alow asm patches in comments
5231 if (*p == ';') {
5232 if (IS_START(p, "; sctpatch:")) {
5233 p = sskip(p + 11);
5234 if (*p == 0 || *p == ';')
5235 continue;
5236 goto parse_words; // lame
5237 }
5238 if (IS_START(p, "; sctproto:")) {
5239 sctproto = strdup(p + 11);
5240 }
5241 else if (IS_START(p, "; sctend")) {
5242 end = 1;
5243 if (!pending_endp)
5244 break;
5245 }
5246 }
5247
5248 if (wordc == 0) {
5249 // shouldn't happen
5250 awarn("wordc == 0?\n");
5251 continue;
5252 }
5253
5254 // don't care about this:
5255 if (words[0][0] == '.'
5256 || IS(words[0], "include")
5257 || IS(words[0], "assume") || IS(words[1], "segment")
5258 || IS(words[0], "align"))
5259 {
5260 continue;
5261 }
5262
5263do_pending_endp:
5264 // do delayed endp processing to collect switch jumptables
5265 if (pending_endp) {
5266 if (in_func && !skip_func && !end && wordc >= 2
5267 && ((words[0][0] == 'd' && words[0][2] == 0)
5268 || (words[1][0] == 'd' && words[1][2] == 0)))
5269 {
5270 i = 1;
5271 if (words[1][0] == 'd' && words[1][2] == 0) {
5272 // label
5273 if (g_func_pd_cnt >= pd_alloc) {
5274 pd_alloc = pd_alloc * 2 + 16;
5275 g_func_pd = realloc(g_func_pd,
5276 sizeof(g_func_pd[0]) * pd_alloc);
5277 my_assert_not(g_func_pd, NULL);
5278 }
5279 pd = &g_func_pd[g_func_pd_cnt];
5280 g_func_pd_cnt++;
5281 memset(pd, 0, sizeof(*pd));
5282 strcpy(pd->label, words[0]);
5283 pd->type = OPT_CONST;
5284 pd->lmod = lmod_from_directive(words[1]);
5285 i = 2;
5286 }
5287 else {
5288 if (pd == NULL) {
5289 if (verbose)
5290 anote("skipping alignment byte?\n");
5291 continue;
5292 }
5293 lmod = lmod_from_directive(words[0]);
5294 if (lmod != pd->lmod)
5295 aerr("lmod change? %d->%d\n", pd->lmod, lmod);
5296 }
5297
5298 if (pd->count_alloc < pd->count + wordc) {
5299 pd->count_alloc = pd->count_alloc * 2 + 14 + wordc;
5300 pd->d = realloc(pd->d, sizeof(pd->d[0]) * pd->count_alloc);
5301 my_assert_not(pd->d, NULL);
5302 }
5303 for (; i < wordc; i++) {
5304 if (IS(words[i], "offset")) {
5305 pd->type = OPT_OFFSET;
5306 i++;
5307 }
5308 p = strchr(words[i], ',');
5309 if (p != NULL)
5310 *p = 0;
5311 if (pd->type == OPT_OFFSET)
5312 pd->d[pd->count].u.label = strdup(words[i]);
5313 else
5314 pd->d[pd->count].u.val = parse_number(words[i]);
5315 pd->d[pd->count].bt_i = -1;
5316 pd->count++;
5317 }
5318 continue;
5319 }
5320
5321 if (in_func && !skip_func)
5322 gen_func(fout, g_fhdr, g_func, pi);
5323
5324 pending_endp = 0;
5325 in_func = 0;
5326 g_ida_func_attr = 0;
5327 skip_warned = 0;
5328 skip_func = 0;
5329 g_func[0] = 0;
5330 func_chunks_used = 0;
5331 func_chunk_i = -1;
5332 if (pi != 0) {
5333 memset(&ops, 0, pi * sizeof(ops[0]));
5334 memset(g_labels, 0, pi * sizeof(g_labels[0]));
5335 pi = 0;
5336 }
5337 g_eqcnt = 0;
5338 for (i = 0; i < g_func_pd_cnt; i++) {
5339 pd = &g_func_pd[i];
5340 if (pd->type == OPT_OFFSET) {
5341 for (j = 0; j < pd->count; j++)
5342 free(pd->d[j].u.label);
5343 }
5344 free(pd->d);
5345 pd->d = NULL;
5346 }
5347 g_func_pd_cnt = 0;
5348 pd = NULL;
5349
5350 if (end)
5351 break;
5352 if (wordc == 0)
5353 continue;
5354 }
5355
5356 if (IS(words[1], "proc")) {
5357 if (in_func)
5358 aerr("proc '%s' while in_func '%s'?\n",
5359 words[0], g_func);
5360 p = words[0];
5361 if (bsearch(&p, rlist, rlist_len, sizeof(rlist[0]), cmpstringp))
5362 skip_func = 1;
5363 strcpy(g_func, words[0]);
5364 set_label(0, words[0]);
5365 in_func = 1;
5366 continue;
5367 }
5368
5369 if (IS(words[1], "endp"))
5370 {
5371 if (!in_func)
5372 aerr("endp '%s' while not in_func?\n", words[0]);
5373 if (!IS(g_func, words[0]))
5374 aerr("endp '%s' while in_func '%s'?\n",
5375 words[0], g_func);
5376
5377 if ((g_ida_func_attr & IDAFA_THUNK) && pi == 1
5378 && ops[0].op == OP_JMP && ops[0].operand[0].had_ds)
5379 {
5380 // import jump
5381 skip_func = 1;
5382 }
5383
5384 if (!skip_func && func_chunks_used) {
5385 // start processing chunks
5386 struct chunk_item *ci, key = { g_func, 0 };
5387
5388 func_chunk_ret = ftell(fasm);
5389 func_chunk_ret_ln = asmln;
5390 if (!func_chunks_sorted) {
5391 qsort(func_chunks, func_chunk_cnt,
5392 sizeof(func_chunks[0]), cmp_chunks);
5393 func_chunks_sorted = 1;
5394 }
5395 ci = bsearch(&key, func_chunks, func_chunk_cnt,
5396 sizeof(func_chunks[0]), cmp_chunks);
5397 if (ci == NULL)
5398 aerr("'%s' needs chunks, but none found\n", g_func);
5399 func_chunk_i = ci - func_chunks;
5400 for (; func_chunk_i > 0; func_chunk_i--)
5401 if (!IS(func_chunks[func_chunk_i - 1].name, g_func))
5402 break;
5403
5404 ret = fseek(fasm, func_chunks[func_chunk_i].fptr, SEEK_SET);
5405 if (ret)
5406 aerr("seek failed for '%s' chunk #%d\n", g_func, func_chunk_i);
5407 asmln = func_chunks[func_chunk_i].asmln;
5408 func_chunk_i++;
5409 continue;
5410 }
5411 pending_endp = 1;
5412 continue;
5413 }
5414
5415 if (wordc == 2 && IS(words[1], "ends")) {
5416 if (!multi_seg) {
5417 end = 1;
5418 if (pending_endp)
5419 goto do_pending_endp;
5420 break;
5421 }
5422
5423 // scan for next text segment
5424 while (fgets(line, sizeof(line), fasm)) {
5425 asmln++;
5426 p = sskip(line);
5427 if (*p == 0 || *p == ';')
5428 continue;
5429
5430 if (strstr(p, "segment para public 'CODE' use32"))
5431 break;
5432 }
5433
5434 continue;
5435 }
5436
5437 p = strchr(words[0], ':');
5438 if (p != NULL) {
5439 set_label(pi, words[0]);
5440 continue;
5441 }
5442
5443 if (!in_func || skip_func) {
5444 if (!skip_warned && !skip_func && g_labels[pi][0] != 0) {
5445 if (verbose)
5446 anote("skipping from '%s'\n", g_labels[pi]);
5447 skip_warned = 1;
5448 }
5449 g_labels[pi][0] = 0;
5450 continue;
5451 }
5452
5453 if (wordc > 1 && IS(words[1], "="))
5454 {
5455 if (wordc != 5)
5456 aerr("unhandled equ, wc=%d\n", wordc);
5457 if (g_eqcnt >= eq_alloc) {
5458 eq_alloc *= 2;
5459 g_eqs = realloc(g_eqs, eq_alloc * sizeof(g_eqs[0]));
5460 my_assert_not(g_eqs, NULL);
5461 }
5462
5463 len = strlen(words[0]);
5464 if (len > sizeof(g_eqs[0].name) - 1)
5465 aerr("equ name too long: %d\n", len);
5466 strcpy(g_eqs[g_eqcnt].name, words[0]);
5467
5468 if (!IS(words[3], "ptr"))
5469 aerr("unhandled equ\n");
5470 if (IS(words[2], "dword"))
5471 g_eqs[g_eqcnt].lmod = OPLM_DWORD;
5472 else if (IS(words[2], "word"))
5473 g_eqs[g_eqcnt].lmod = OPLM_WORD;
5474 else if (IS(words[2], "byte"))
5475 g_eqs[g_eqcnt].lmod = OPLM_BYTE;
5476 else
5477 aerr("bad lmod: '%s'\n", words[2]);
5478
5479 g_eqs[g_eqcnt].offset = parse_number(words[4]);
5480 g_eqcnt++;
5481 continue;
5482 }
5483
5484 if (pi >= ARRAY_SIZE(ops))
5485 aerr("too many ops\n");
5486
5487 parse_op(&ops[pi], words, wordc);
5488
5489 if (sctproto != NULL) {
5490 if (ops[pi].op == OP_CALL || ops[pi].op == OP_JMP)
5491 ops[pi].datap = sctproto;
5492 sctproto = NULL;
5493 }
5494 pi++;
5495 }
5496
5497 fclose(fout);
5498 fclose(fasm);
5499 fclose(g_fhdr);
5500
5501 return 0;
5502}
5503
5504// vim:ts=2:shiftwidth=2:expandtab