2 * Copyright (C) 2015 Josh Poimboeuf <jpoimboe@redhat.com>
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #define unlikely(cond) (cond)
22 #include "insn/insn.h"
23 #include "insn/inat.c"
24 #include "insn/insn.c"
26 #include "../../elf.h"
27 #include "../../arch.h"
28 #include "../../warn.h"
30 static int is_x86_64(struct elf *elf)
32 switch (elf->ehdr.e_machine) {
38 WARN("unexpected ELF machine type %d", elf->ehdr.e_machine);
43 int arch_decode_instruction(struct elf *elf, struct section *sec,
44 unsigned long offset, unsigned int maxlen,
45 unsigned int *len, unsigned char *type,
46 unsigned long *immediate)
50 unsigned char op1, op2, ext;
52 x86_64 = is_x86_64(elf);
56 insn_init(&insn, (void *)(sec->data + offset), maxlen, x86_64);
57 insn_get_length(&insn);
58 insn_get_opcode(&insn);
59 insn_get_modrm(&insn);
60 insn_get_immediate(&insn);
62 if (!insn_complete(&insn)) {
63 WARN_FUNC("can't decode instruction", sec, offset);
70 if (insn.vex_prefix.nbytes)
73 op1 = insn.opcode.bytes[0];
74 op2 = insn.opcode.bytes[1];
78 if (!insn.rex_prefix.nbytes)
84 if (!insn.rex_prefix.nbytes)
86 *type = INSN_FP_RESTORE;
90 *type = INSN_JUMP_CONDITIONAL;
94 if (insn.rex_prefix.nbytes == 1 &&
95 insn.rex_prefix.bytes[0] == 0x48 &&
96 insn.modrm.nbytes && insn.modrm.bytes[0] == 0xe5)
98 *type = INSN_FP_SETUP;
106 if (op2 >= 0x80 && op2 <= 0x8f)
107 *type = INSN_JUMP_CONDITIONAL;
108 else if (op2 == 0x05 || op2 == 0x07 || op2 == 0x34 ||
110 /* sysenter, sysret */
111 *type = INSN_CONTEXT_SWITCH;
112 else if (op2 == 0x0b || op2 == 0xb9)
115 else if (op2 == 0x0d || op2 == 0x1f)
118 else if (op2 == 0x01 && insn.modrm.nbytes &&
119 (insn.modrm.bytes[0] == 0xc2 ||
120 insn.modrm.bytes[0] == 0xd8))
121 /* vmlaunch, vmrun */
122 *type = INSN_CONTEXT_SWITCH;
126 case 0xc9: /* leave */
127 *type = INSN_FP_RESTORE;
130 case 0xe3: /* jecxz/jrcxz */
131 *type = INSN_JUMP_CONDITIONAL;
136 *type = INSN_JUMP_UNCONDITIONAL;
144 case 0xc5: /* iret */
145 case 0xca: /* retf */
146 case 0xcb: /* retf */
147 *type = INSN_CONTEXT_SWITCH;
155 ext = X86_MODRM_REG(insn.modrm.bytes[0]);
156 if (ext == 2 || ext == 3)
157 *type = INSN_CALL_DYNAMIC;
159 *type = INSN_JUMP_DYNAMIC;
160 else if (ext == 5) /*jmpf */
161 *type = INSN_CONTEXT_SWITCH;
169 *immediate = insn.immediate.nbytes ? insn.immediate.value : 0;