1 /*===-- X86DisassemblerDecoder.c - Disassembler decoder ------------*- C -*-===*
3 * The LLVM Compiler Infrastructure
5 * This file is distributed under the University of Illinois Open Source
6 * License. See LICENSE.TXT for details.
8 *===----------------------------------------------------------------------===*
10 * This file is part of the X86 Disassembler.
11 * It contains the implementation of the instruction decoder.
12 * Documentation for the disassembler can be found in X86Disassembler.h.
14 *===----------------------------------------------------------------------===*/
16 #include <stdarg.h> /* for va_*() */
17 #include <stdio.h> /* for vsnprintf() */
18 #include <stdlib.h> /* for exit() */
19 #include <string.h> /* for memset() */
21 #include "X86DisassemblerDecoder.h"
23 #include "X86GenDisassemblerTables.inc"
29 #define debug(s) do { x86DisassemblerDebug(__FILE__, __LINE__, s); } while (0)
31 #define debug(s) do { } while (0)
36 * contextForAttrs - Client for the instruction context table. Takes a set of
37 * attributes and returns the appropriate decode context.
39 * @param attrMask - Attributes, from the enumeration attributeBits.
40 * @return - The InstructionContext to use when looking up an
41 * an instruction with these attributes.
43 static InstructionContext contextForAttrs(uint8_t attrMask) {
44 return CONTEXTS_SYM[attrMask];
48 * modRMRequired - Reads the appropriate instruction table to determine whether
49 * the ModR/M byte is required to decode a particular instruction.
51 * @param type - The opcode type (i.e., how many bytes it has).
52 * @param insnContext - The context for the instruction, as returned by
54 * @param opcode - The last byte of the instruction's opcode, not counting
55 * ModR/M extensions and escapes.
56 * @return - TRUE if the ModR/M byte is required, FALSE otherwise.
58 static int modRMRequired(OpcodeType type,
59 InstructionContext insnContext,
61 const struct ContextDecision* decision = 0;
65 decision = &ONEBYTE_SYM;
68 decision = &TWOBYTE_SYM;
71 decision = &THREEBYTE38_SYM;
74 decision = &THREEBYTE3A_SYM;
77 decision = &THREEBYTEA6_SYM;
80 decision = &THREEBYTEA7_SYM;
83 decision = &XOP8_MAP_SYM;
86 decision = &XOP9_MAP_SYM;
89 decision = &XOPA_MAP_SYM;
93 return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].
94 modrm_type != MODRM_ONEENTRY;
98 * decode - Reads the appropriate instruction table to obtain the unique ID of
101 * @param type - See modRMRequired().
102 * @param insnContext - See modRMRequired().
103 * @param opcode - See modRMRequired().
104 * @param modRM - The ModR/M byte if required, or any value if not.
105 * @return - The UID of the instruction, or 0 on failure.
107 static InstrUID decode(OpcodeType type,
108 InstructionContext insnContext,
111 const struct ModRMDecision* dec = 0;
115 dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
118 dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
121 dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
124 dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
127 dec = &THREEBYTEA6_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
130 dec = &THREEBYTEA7_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
133 dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
136 dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
139 dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
143 switch (dec->modrm_type) {
145 debug("Corrupt table! Unknown modrm_type");
148 return modRMTable[dec->instructionIDs];
150 if (modFromModRM(modRM) == 0x3)
151 return modRMTable[dec->instructionIDs+1];
152 return modRMTable[dec->instructionIDs];
154 if (modFromModRM(modRM) == 0x3)
155 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)+8];
156 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
157 case MODRM_SPLITMISC:
158 if (modFromModRM(modRM) == 0x3)
159 return modRMTable[dec->instructionIDs+(modRM & 0x3f)+8];
160 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
162 return modRMTable[dec->instructionIDs+modRM];
167 * specifierForUID - Given a UID, returns the name and operand specification for
170 * @param uid - The unique ID for the instruction. This should be returned by
171 * decode(); specifierForUID will not check bounds.
172 * @return - A pointer to the specification for that instruction.
174 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
175 return &INSTRUCTIONS_SYM[uid];
179 * consumeByte - Uses the reader function provided by the user to consume one
180 * byte from the instruction's memory and advance the cursor.
182 * @param insn - The instruction with the reader function to use. The cursor
183 * for this instruction is advanced.
184 * @param byte - A pointer to a pre-allocated memory buffer to be populated
185 * with the data read.
186 * @return - 0 if the read was successful; nonzero otherwise.
188 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
189 int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
192 ++(insn->readerCursor);
198 * lookAtByte - Like consumeByte, but does not advance the cursor.
200 * @param insn - See consumeByte().
201 * @param byte - See consumeByte().
202 * @return - See consumeByte().
204 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
205 return insn->reader(insn->readerArg, byte, insn->readerCursor);
208 static void unconsumeByte(struct InternalInstruction* insn) {
209 insn->readerCursor--;
212 #define CONSUME_FUNC(name, type) \
213 static int name(struct InternalInstruction* insn, type* ptr) { \
216 for (offset = 0; offset < sizeof(type); ++offset) { \
218 int ret = insn->reader(insn->readerArg, \
220 insn->readerCursor + offset); \
223 combined = combined | ((uint64_t)byte << (offset * 8)); \
226 insn->readerCursor += sizeof(type); \
231 * consume* - Use the reader function provided by the user to consume data
232 * values of various sizes from the instruction's memory and advance the
233 * cursor appropriately. These readers perform endian conversion.
235 * @param insn - See consumeByte().
236 * @param ptr - A pointer to a pre-allocated memory of appropriate size to
237 * be populated with the data read.
238 * @return - See consumeByte().
240 CONSUME_FUNC(consumeInt8, int8_t)
241 CONSUME_FUNC(consumeInt16, int16_t)
242 CONSUME_FUNC(consumeInt32, int32_t)
243 CONSUME_FUNC(consumeUInt16, uint16_t)
244 CONSUME_FUNC(consumeUInt32, uint32_t)
245 CONSUME_FUNC(consumeUInt64, uint64_t)
248 * dbgprintf - Uses the logging function provided by the user to log a single
249 * message, typically without a carriage-return.
251 * @param insn - The instruction containing the logging function.
252 * @param format - See printf().
253 * @param ... - See printf().
255 static void dbgprintf(struct InternalInstruction* insn,
264 va_start(ap, format);
265 (void)vsnprintf(buffer, sizeof(buffer), format, ap);
268 insn->dlog(insn->dlogArg, buffer);
274 * setPrefixPresent - Marks that a particular prefix is present at a particular
277 * @param insn - The instruction to be marked as having the prefix.
278 * @param prefix - The prefix that is present.
279 * @param location - The location where the prefix is located (in the address
280 * space of the instruction's reader).
282 static void setPrefixPresent(struct InternalInstruction* insn,
286 insn->prefixPresent[prefix] = 1;
287 insn->prefixLocations[prefix] = location;
291 * isPrefixAtLocation - Queries an instruction to determine whether a prefix is
292 * present at a given location.
294 * @param insn - The instruction to be queried.
295 * @param prefix - The prefix.
296 * @param location - The location to query.
297 * @return - Whether the prefix is at that location.
299 static BOOL isPrefixAtLocation(struct InternalInstruction* insn,
303 if (insn->prefixPresent[prefix] == 1 &&
304 insn->prefixLocations[prefix] == location)
311 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
312 * instruction as having them. Also sets the instruction's default operand,
313 * address, and other relevant data sizes to report operands correctly.
315 * @param insn - The instruction whose prefixes are to be read.
316 * @return - 0 if the instruction could be read until the end of the prefix
317 * bytes, and no prefixes conflicted; nonzero otherwise.
319 static int readPrefixes(struct InternalInstruction* insn) {
320 BOOL isPrefix = TRUE;
321 BOOL prefixGroups[4] = { FALSE };
322 uint64_t prefixLocation;
326 BOOL hasAdSize = FALSE;
327 BOOL hasOpSize = FALSE;
329 dbgprintf(insn, "readPrefixes()");
332 prefixLocation = insn->readerCursor;
334 /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
335 if (consumeByte(insn, &byte))
339 * If the byte is a LOCK/REP/REPNE prefix and not a part of the opcode, then
340 * break and let it be disassembled as a normal "instruction".
342 if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0)
345 if (insn->readerCursor - 1 == insn->startLocation
346 && (byte == 0xf2 || byte == 0xf3)
347 && !lookAtByte(insn, &nextByte))
350 * If the byte is 0xf2 or 0xf3, and any of the following conditions are
352 * - it is followed by a LOCK (0xf0) prefix
353 * - it is followed by an xchg instruction
354 * then it should be disassembled as a xacquire/xrelease not repne/rep.
356 if ((byte == 0xf2 || byte == 0xf3) &&
357 ((nextByte == 0xf0) |
358 ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90)))
359 insn->xAcquireRelease = TRUE;
361 * Also if the byte is 0xf3, and the following condition is met:
362 * - it is followed by a "mov mem, reg" (opcode 0x88/0x89) or
363 * "mov mem, imm" (opcode 0xc6/0xc7) instructions.
364 * then it should be disassembled as an xrelease not rep.
367 (nextByte == 0x88 || nextByte == 0x89 ||
368 nextByte == 0xc6 || nextByte == 0xc7))
369 insn->xAcquireRelease = TRUE;
370 if (insn->mode == MODE_64BIT && (nextByte & 0xf0) == 0x40) {
371 if (consumeByte(insn, &nextByte))
373 if (lookAtByte(insn, &nextByte))
377 if (nextByte != 0x0f && nextByte != 0x90)
382 case 0xf0: /* LOCK */
383 case 0xf2: /* REPNE/REPNZ */
384 case 0xf3: /* REP or REPE/REPZ */
386 dbgprintf(insn, "Redundant Group 1 prefix");
387 prefixGroups[0] = TRUE;
388 setPrefixPresent(insn, byte, prefixLocation);
390 case 0x2e: /* CS segment override -OR- Branch not taken */
391 case 0x36: /* SS segment override -OR- Branch taken */
392 case 0x3e: /* DS segment override */
393 case 0x26: /* ES segment override */
394 case 0x64: /* FS segment override */
395 case 0x65: /* GS segment override */
398 insn->segmentOverride = SEG_OVERRIDE_CS;
401 insn->segmentOverride = SEG_OVERRIDE_SS;
404 insn->segmentOverride = SEG_OVERRIDE_DS;
407 insn->segmentOverride = SEG_OVERRIDE_ES;
410 insn->segmentOverride = SEG_OVERRIDE_FS;
413 insn->segmentOverride = SEG_OVERRIDE_GS;
416 debug("Unhandled override");
420 dbgprintf(insn, "Redundant Group 2 prefix");
421 prefixGroups[1] = TRUE;
422 setPrefixPresent(insn, byte, prefixLocation);
424 case 0x66: /* Operand-size override */
426 dbgprintf(insn, "Redundant Group 3 prefix");
427 prefixGroups[2] = TRUE;
429 setPrefixPresent(insn, byte, prefixLocation);
431 case 0x67: /* Address-size override */
433 dbgprintf(insn, "Redundant Group 4 prefix");
434 prefixGroups[3] = TRUE;
436 setPrefixPresent(insn, byte, prefixLocation);
438 default: /* Not a prefix byte */
444 dbgprintf(insn, "Found prefix 0x%hhx", byte);
447 insn->vexXopType = TYPE_NO_VEX_XOP;
452 if (lookAtByte(insn, &byte1)) {
453 dbgprintf(insn, "Couldn't read second byte of VEX");
457 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
458 insn->vexXopType = TYPE_VEX_3B;
459 insn->necessaryPrefixLocation = insn->readerCursor - 1;
463 insn->necessaryPrefixLocation = insn->readerCursor - 1;
466 if (insn->vexXopType == TYPE_VEX_3B) {
467 insn->vexXopPrefix[0] = byte;
468 consumeByte(insn, &insn->vexXopPrefix[1]);
469 consumeByte(insn, &insn->vexXopPrefix[2]);
471 /* We simulate the REX prefix for simplicity's sake */
473 if (insn->mode == MODE_64BIT) {
474 insn->rexPrefix = 0x40
475 | (wFromVEX3of3(insn->vexXopPrefix[2]) << 3)
476 | (rFromVEX2of3(insn->vexXopPrefix[1]) << 2)
477 | (xFromVEX2of3(insn->vexXopPrefix[1]) << 1)
478 | (bFromVEX2of3(insn->vexXopPrefix[1]) << 0);
481 switch (ppFromVEX3of3(insn->vexXopPrefix[2]))
490 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx",
491 insn->vexXopPrefix[0], insn->vexXopPrefix[1],
492 insn->vexXopPrefix[2]);
495 else if (byte == 0xc5) {
498 if (lookAtByte(insn, &byte1)) {
499 dbgprintf(insn, "Couldn't read second byte of VEX");
503 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
504 insn->vexXopType = TYPE_VEX_2B;
510 if (insn->vexXopType == TYPE_VEX_2B) {
511 insn->vexXopPrefix[0] = byte;
512 consumeByte(insn, &insn->vexXopPrefix[1]);
514 if (insn->mode == MODE_64BIT) {
515 insn->rexPrefix = 0x40
516 | (rFromVEX2of2(insn->vexXopPrefix[1]) << 2);
519 switch (ppFromVEX2of2(insn->vexXopPrefix[1]))
528 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx", insn->vexXopPrefix[0], insn->vexXopPrefix[1]);
531 else if (byte == 0x8f) {
534 if (lookAtByte(insn, &byte1)) {
535 dbgprintf(insn, "Couldn't read second byte of XOP");
539 if ((byte1 & 0x38) != 0x0) { /* 0 in these 3 bits is a POP instruction. */
540 insn->vexXopType = TYPE_XOP;
541 insn->necessaryPrefixLocation = insn->readerCursor - 1;
545 insn->necessaryPrefixLocation = insn->readerCursor - 1;
548 if (insn->vexXopType == TYPE_XOP) {
549 insn->vexXopPrefix[0] = byte;
550 consumeByte(insn, &insn->vexXopPrefix[1]);
551 consumeByte(insn, &insn->vexXopPrefix[2]);
553 /* We simulate the REX prefix for simplicity's sake */
555 if (insn->mode == MODE_64BIT) {
556 insn->rexPrefix = 0x40
557 | (wFromXOP3of3(insn->vexXopPrefix[2]) << 3)
558 | (rFromXOP2of3(insn->vexXopPrefix[1]) << 2)
559 | (xFromXOP2of3(insn->vexXopPrefix[1]) << 1)
560 | (bFromXOP2of3(insn->vexXopPrefix[1]) << 0);
563 switch (ppFromXOP3of3(insn->vexXopPrefix[2]))
572 dbgprintf(insn, "Found XOP prefix 0x%hhx 0x%hhx 0x%hhx",
573 insn->vexXopPrefix[0], insn->vexXopPrefix[1],
574 insn->vexXopPrefix[2]);
578 if (insn->mode == MODE_64BIT) {
579 if ((byte & 0xf0) == 0x40) {
582 if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
583 dbgprintf(insn, "Redundant REX prefix");
587 insn->rexPrefix = byte;
588 insn->necessaryPrefixLocation = insn->readerCursor - 2;
590 dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
593 insn->necessaryPrefixLocation = insn->readerCursor - 1;
597 insn->necessaryPrefixLocation = insn->readerCursor - 1;
601 if (insn->mode == MODE_16BIT) {
602 insn->registerSize = (hasOpSize ? 4 : 2);
603 insn->addressSize = (hasAdSize ? 4 : 2);
604 insn->displacementSize = (hasAdSize ? 4 : 2);
605 insn->immediateSize = (hasOpSize ? 4 : 2);
606 } else if (insn->mode == MODE_32BIT) {
607 insn->registerSize = (hasOpSize ? 2 : 4);
608 insn->addressSize = (hasAdSize ? 2 : 4);
609 insn->displacementSize = (hasAdSize ? 2 : 4);
610 insn->immediateSize = (hasOpSize ? 2 : 4);
611 } else if (insn->mode == MODE_64BIT) {
612 if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
613 insn->registerSize = 8;
614 insn->addressSize = (hasAdSize ? 4 : 8);
615 insn->displacementSize = 4;
616 insn->immediateSize = 4;
617 } else if (insn->rexPrefix) {
618 insn->registerSize = (hasOpSize ? 2 : 4);
619 insn->addressSize = (hasAdSize ? 4 : 8);
620 insn->displacementSize = (hasOpSize ? 2 : 4);
621 insn->immediateSize = (hasOpSize ? 2 : 4);
623 insn->registerSize = (hasOpSize ? 2 : 4);
624 insn->addressSize = (hasAdSize ? 4 : 8);
625 insn->displacementSize = (hasOpSize ? 2 : 4);
626 insn->immediateSize = (hasOpSize ? 2 : 4);
634 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
635 * extended or escape opcodes).
637 * @param insn - The instruction whose opcode is to be read.
638 * @return - 0 if the opcode could be read successfully; nonzero otherwise.
640 static int readOpcode(struct InternalInstruction* insn) {
641 /* Determine the length of the primary opcode */
645 dbgprintf(insn, "readOpcode()");
647 insn->opcodeType = ONEBYTE;
649 if (insn->vexXopType == TYPE_VEX_3B)
651 switch (mmmmmFromVEX2of3(insn->vexXopPrefix[1]))
654 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
655 mmmmmFromVEX2of3(insn->vexXopPrefix[1]));
658 insn->opcodeType = TWOBYTE;
659 return consumeByte(insn, &insn->opcode);
661 insn->opcodeType = THREEBYTE_38;
662 return consumeByte(insn, &insn->opcode);
664 insn->opcodeType = THREEBYTE_3A;
665 return consumeByte(insn, &insn->opcode);
668 else if (insn->vexXopType == TYPE_VEX_2B)
670 insn->opcodeType = TWOBYTE;
671 return consumeByte(insn, &insn->opcode);
673 else if (insn->vexXopType == TYPE_XOP)
675 switch (mmmmmFromXOP2of3(insn->vexXopPrefix[1]))
678 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
679 mmmmmFromVEX2of3(insn->vexXopPrefix[1]));
681 case XOP_MAP_SELECT_8:
682 insn->opcodeType = XOP8_MAP;
683 return consumeByte(insn, &insn->opcode);
684 case XOP_MAP_SELECT_9:
685 insn->opcodeType = XOP9_MAP;
686 return consumeByte(insn, &insn->opcode);
687 case XOP_MAP_SELECT_A:
688 insn->opcodeType = XOPA_MAP;
689 return consumeByte(insn, &insn->opcode);
693 if (consumeByte(insn, ¤t))
696 if (current == 0x0f) {
697 dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
699 if (consumeByte(insn, ¤t))
702 if (current == 0x38) {
703 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
705 if (consumeByte(insn, ¤t))
708 insn->opcodeType = THREEBYTE_38;
709 } else if (current == 0x3a) {
710 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
712 if (consumeByte(insn, ¤t))
715 insn->opcodeType = THREEBYTE_3A;
716 } else if (current == 0xa6) {
717 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
719 if (consumeByte(insn, ¤t))
722 insn->opcodeType = THREEBYTE_A6;
723 } else if (current == 0xa7) {
724 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
726 if (consumeByte(insn, ¤t))
729 insn->opcodeType = THREEBYTE_A7;
731 dbgprintf(insn, "Didn't find a three-byte escape prefix");
733 insn->opcodeType = TWOBYTE;
738 * At this point we have consumed the full opcode.
739 * Anything we consume from here on must be unconsumed.
742 insn->opcode = current;
747 static int readModRM(struct InternalInstruction* insn);
750 * getIDWithAttrMask - Determines the ID of an instruction, consuming
751 * the ModR/M byte as appropriate for extended and escape opcodes,
752 * and using a supplied attribute mask.
754 * @param instructionID - A pointer whose target is filled in with the ID of the
756 * @param insn - The instruction whose ID is to be determined.
757 * @param attrMask - The attribute mask to search.
758 * @return - 0 if the ModR/M could be read when needed or was not
759 * needed; nonzero otherwise.
761 static int getIDWithAttrMask(uint16_t* instructionID,
762 struct InternalInstruction* insn,
764 BOOL hasModRMExtension;
766 uint8_t instructionClass;
768 instructionClass = contextForAttrs(attrMask);
770 hasModRMExtension = modRMRequired(insn->opcodeType,
774 if (hasModRMExtension) {
778 *instructionID = decode(insn->opcodeType,
783 *instructionID = decode(insn->opcodeType,
793 * is16BitEquivalent - Determines whether two instruction names refer to
794 * equivalent instructions but one is 16-bit whereas the other is not.
796 * @param orig - The instruction that is not 16-bit
797 * @param equiv - The instruction that is 16-bit
799 static BOOL is16BitEquivalent(const char* orig, const char* equiv) {
803 if (orig[i] == '\0' && equiv[i] == '\0')
805 if (orig[i] == '\0' || equiv[i] == '\0')
807 if (orig[i] != equiv[i]) {
808 if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
810 if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
812 if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
820 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
821 * appropriate for extended and escape opcodes. Determines the attributes and
822 * context for the instruction before doing so.
824 * @param insn - The instruction whose ID is to be determined.
825 * @return - 0 if the ModR/M could be read when needed or was not needed;
828 static int getID(struct InternalInstruction* insn, const void *miiArg) {
830 uint16_t instructionID;
832 dbgprintf(insn, "getID()");
834 attrMask = ATTR_NONE;
836 if (insn->mode == MODE_64BIT)
837 attrMask |= ATTR_64BIT;
839 if (insn->vexXopType != TYPE_NO_VEX_XOP) {
840 attrMask |= ATTR_VEX;
842 if (insn->vexXopType == TYPE_VEX_3B) {
843 switch (ppFromVEX3of3(insn->vexXopPrefix[2])) {
845 attrMask |= ATTR_OPSIZE;
855 if (lFromVEX3of3(insn->vexXopPrefix[2]))
856 attrMask |= ATTR_VEXL;
858 else if (insn->vexXopType == TYPE_VEX_2B) {
859 switch (ppFromVEX2of2(insn->vexXopPrefix[1])) {
861 attrMask |= ATTR_OPSIZE;
871 if (lFromVEX2of2(insn->vexXopPrefix[1]))
872 attrMask |= ATTR_VEXL;
874 else if (insn->vexXopType == TYPE_XOP) {
875 switch (ppFromXOP3of3(insn->vexXopPrefix[2])) {
877 attrMask |= ATTR_OPSIZE;
887 if (lFromXOP3of3(insn->vexXopPrefix[2]))
888 attrMask |= ATTR_VEXL;
895 if (isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
896 attrMask |= ATTR_OPSIZE;
897 else if (isPrefixAtLocation(insn, 0x67, insn->necessaryPrefixLocation))
898 attrMask |= ATTR_ADSIZE;
899 else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
901 else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
905 if (insn->rexPrefix & 0x08)
906 attrMask |= ATTR_REXW;
908 if (getIDWithAttrMask(&instructionID, insn, attrMask))
911 /* The following clauses compensate for limitations of the tables. */
913 if (insn->prefixPresent[0x66] && !(attrMask & ATTR_OPSIZE)) {
915 * The instruction tables make no distinction between instructions that
916 * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
917 * particular spot (i.e., many MMX operations). In general we're
918 * conservative, but in the specific case where OpSize is present but not
919 * in the right place we check if there's a 16-bit operation.
922 const struct InstructionSpecifier *spec;
923 uint16_t instructionIDWithOpsize;
924 const char *specName, *specWithOpSizeName;
926 spec = specifierForUID(instructionID);
928 if (getIDWithAttrMask(&instructionIDWithOpsize,
930 attrMask | ATTR_OPSIZE)) {
932 * ModRM required with OpSize but not present; give up and return version
936 insn->instructionID = instructionID;
941 specName = x86DisassemblerGetInstrName(instructionID, miiArg);
943 x86DisassemblerGetInstrName(instructionIDWithOpsize, miiArg);
945 if (is16BitEquivalent(specName, specWithOpSizeName)) {
946 insn->instructionID = instructionIDWithOpsize;
947 insn->spec = specifierForUID(instructionIDWithOpsize);
949 insn->instructionID = instructionID;
955 if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
956 insn->rexPrefix & 0x01) {
958 * NOOP shouldn't decode as NOOP if REX.b is set. Instead
959 * it should decode as XCHG %r8, %eax.
962 const struct InstructionSpecifier *spec;
963 uint16_t instructionIDWithNewOpcode;
964 const struct InstructionSpecifier *specWithNewOpcode;
966 spec = specifierForUID(instructionID);
968 /* Borrow opcode from one of the other XCHGar opcodes */
971 if (getIDWithAttrMask(&instructionIDWithNewOpcode,
976 insn->instructionID = instructionID;
981 specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
986 insn->instructionID = instructionIDWithNewOpcode;
987 insn->spec = specWithNewOpcode;
992 insn->instructionID = instructionID;
993 insn->spec = specifierForUID(insn->instructionID);
999 * readSIB - Consumes the SIB byte to determine addressing information for an
1002 * @param insn - The instruction whose SIB byte is to be read.
1003 * @return - 0 if the SIB byte was successfully read; nonzero otherwise.
1005 static int readSIB(struct InternalInstruction* insn) {
1006 SIBIndex sibIndexBase = 0;
1007 SIBBase sibBaseBase = 0;
1008 uint8_t index, base;
1010 dbgprintf(insn, "readSIB()");
1012 if (insn->consumedSIB)
1015 insn->consumedSIB = TRUE;
1017 switch (insn->addressSize) {
1019 dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
1023 sibIndexBase = SIB_INDEX_EAX;
1024 sibBaseBase = SIB_BASE_EAX;
1027 sibIndexBase = SIB_INDEX_RAX;
1028 sibBaseBase = SIB_BASE_RAX;
1032 if (consumeByte(insn, &insn->sib))
1035 index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1039 insn->sibIndex = SIB_INDEX_NONE;
1042 insn->sibIndex = (SIBIndex)(sibIndexBase + index);
1043 if (insn->sibIndex == SIB_INDEX_sib ||
1044 insn->sibIndex == SIB_INDEX_sib64)
1045 insn->sibIndex = SIB_INDEX_NONE;
1049 switch (scaleFromSIB(insn->sib)) {
1064 base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1069 switch (modFromModRM(insn->modRM)) {
1071 insn->eaDisplacement = EA_DISP_32;
1072 insn->sibBase = SIB_BASE_NONE;
1075 insn->eaDisplacement = EA_DISP_8;
1076 insn->sibBase = (SIBBase)(sibBaseBase + base);
1079 insn->eaDisplacement = EA_DISP_32;
1080 insn->sibBase = (SIBBase)(sibBaseBase + base);
1083 debug("Cannot have Mod = 0b11 and a SIB byte");
1088 insn->sibBase = (SIBBase)(sibBaseBase + base);
1096 * readDisplacement - Consumes the displacement of an instruction.
1098 * @param insn - The instruction whose displacement is to be read.
1099 * @return - 0 if the displacement byte was successfully read; nonzero
1102 static int readDisplacement(struct InternalInstruction* insn) {
1107 dbgprintf(insn, "readDisplacement()");
1109 if (insn->consumedDisplacement)
1112 insn->consumedDisplacement = TRUE;
1113 insn->displacementOffset = insn->readerCursor - insn->startLocation;
1115 switch (insn->eaDisplacement) {
1117 insn->consumedDisplacement = FALSE;
1120 if (consumeInt8(insn, &d8))
1122 insn->displacement = d8;
1125 if (consumeInt16(insn, &d16))
1127 insn->displacement = d16;
1130 if (consumeInt32(insn, &d32))
1132 insn->displacement = d32;
1136 insn->consumedDisplacement = TRUE;
1141 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1142 * displacement) for an instruction and interprets it.
1144 * @param insn - The instruction whose addressing information is to be read.
1145 * @return - 0 if the information was successfully read; nonzero otherwise.
1147 static int readModRM(struct InternalInstruction* insn) {
1148 uint8_t mod, rm, reg;
1150 dbgprintf(insn, "readModRM()");
1152 if (insn->consumedModRM)
1155 if (consumeByte(insn, &insn->modRM))
1157 insn->consumedModRM = TRUE;
1159 mod = modFromModRM(insn->modRM);
1160 rm = rmFromModRM(insn->modRM);
1161 reg = regFromModRM(insn->modRM);
1164 * This goes by insn->registerSize to pick the correct register, which messes
1165 * up if we're using (say) XMM or 8-bit register operands. That gets fixed in
1168 switch (insn->registerSize) {
1170 insn->regBase = MODRM_REG_AX;
1171 insn->eaRegBase = EA_REG_AX;
1174 insn->regBase = MODRM_REG_EAX;
1175 insn->eaRegBase = EA_REG_EAX;
1178 insn->regBase = MODRM_REG_RAX;
1179 insn->eaRegBase = EA_REG_RAX;
1183 reg |= rFromREX(insn->rexPrefix) << 3;
1184 rm |= bFromREX(insn->rexPrefix) << 3;
1186 insn->reg = (Reg)(insn->regBase + reg);
1188 switch (insn->addressSize) {
1190 insn->eaBaseBase = EA_BASE_BX_SI;
1195 insn->eaBase = EA_BASE_NONE;
1196 insn->eaDisplacement = EA_DISP_16;
1197 if (readDisplacement(insn))
1200 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1201 insn->eaDisplacement = EA_DISP_NONE;
1205 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1206 insn->eaDisplacement = EA_DISP_8;
1207 if (readDisplacement(insn))
1211 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1212 insn->eaDisplacement = EA_DISP_16;
1213 if (readDisplacement(insn))
1217 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1218 if (readDisplacement(insn))
1225 insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1229 insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1232 case 0xc: /* in case REXW.b is set */
1233 insn->eaBase = (insn->addressSize == 4 ?
1234 EA_BASE_sib : EA_BASE_sib64);
1236 if (readDisplacement(insn))
1240 insn->eaBase = EA_BASE_NONE;
1241 insn->eaDisplacement = EA_DISP_32;
1242 if (readDisplacement(insn))
1246 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1252 insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1255 case 0xc: /* in case REXW.b is set */
1256 insn->eaBase = EA_BASE_sib;
1258 if (readDisplacement(insn))
1262 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1263 if (readDisplacement(insn))
1269 insn->eaDisplacement = EA_DISP_NONE;
1270 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1274 } /* switch (insn->addressSize) */
1279 #define GENERIC_FIXUP_FUNC(name, base, prefix) \
1280 static uint8_t name(struct InternalInstruction *insn, \
1287 debug("Unhandled register type"); \
1291 return base + index; \
1293 if (insn->rexPrefix && \
1294 index >= 4 && index <= 7) { \
1295 return prefix##_SPL + (index - 4); \
1297 return prefix##_AL + index; \
1300 return prefix##_AX + index; \
1302 return prefix##_EAX + index; \
1304 return prefix##_RAX + index; \
1306 return prefix##_ZMM0 + index; \
1308 return prefix##_YMM0 + index; \
1313 return prefix##_XMM0 + index; \
1319 return prefix##_MM0 + index; \
1320 case TYPE_SEGMENTREG: \
1323 return prefix##_ES + index; \
1324 case TYPE_DEBUGREG: \
1327 return prefix##_DR0 + index; \
1328 case TYPE_CONTROLREG: \
1331 return prefix##_CR0 + index; \
1336 * fixup*Value - Consults an operand type to determine the meaning of the
1337 * reg or R/M field. If the operand is an XMM operand, for example, an
1338 * operand would be XMM0 instead of AX, which readModRM() would otherwise
1339 * misinterpret it as.
1341 * @param insn - The instruction containing the operand.
1342 * @param type - The operand type.
1343 * @param index - The existing value of the field as reported by readModRM().
1344 * @param valid - The address of a uint8_t. The target is set to 1 if the
1345 * field is valid for the register class; 0 if not.
1346 * @return - The proper value.
1348 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG)
1349 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG)
1352 * fixupReg - Consults an operand specifier to determine which of the
1353 * fixup*Value functions to use in correcting readModRM()'ss interpretation.
1355 * @param insn - See fixup*Value().
1356 * @param op - The operand specifier.
1357 * @return - 0 if fixup was successful; -1 if the register returned was
1358 * invalid for its class.
1360 static int fixupReg(struct InternalInstruction *insn,
1361 const struct OperandSpecifier *op) {
1364 dbgprintf(insn, "fixupReg()");
1366 switch ((OperandEncoding)op->encoding) {
1368 debug("Expected a REG or R/M encoding in fixupReg");
1371 insn->vvvv = (Reg)fixupRegValue(insn,
1372 (OperandType)op->type,
1379 insn->reg = (Reg)fixupRegValue(insn,
1380 (OperandType)op->type,
1381 insn->reg - insn->regBase,
1387 if (insn->eaBase >= insn->eaRegBase) {
1388 insn->eaBase = (EABase)fixupRMValue(insn,
1389 (OperandType)op->type,
1390 insn->eaBase - insn->eaRegBase,
1402 * readOpcodeModifier - Reads an operand from the opcode field of an
1403 * instruction. Handles AddRegFrm instructions.
1405 * @param insn - The instruction whose opcode field is to be read.
1406 * @param inModRM - Indicates that the opcode field is to be read from the
1407 * ModR/M extension; useful for escape opcodes
1408 * @return - 0 on success; nonzero otherwise.
1410 static int readOpcodeModifier(struct InternalInstruction* insn) {
1411 dbgprintf(insn, "readOpcodeModifier()");
1413 if (insn->consumedOpcodeModifier)
1416 insn->consumedOpcodeModifier = TRUE;
1418 switch (insn->spec->modifierType) {
1420 debug("Unknown modifier type.");
1423 debug("No modifier but an operand expects one.");
1425 case MODIFIER_OPCODE:
1426 insn->opcodeModifier = insn->opcode - insn->spec->modifierBase;
1428 case MODIFIER_MODRM:
1429 insn->opcodeModifier = insn->modRM - insn->spec->modifierBase;
1435 * readOpcodeRegister - Reads an operand from the opcode field of an
1436 * instruction and interprets it appropriately given the operand width.
1437 * Handles AddRegFrm instructions.
1439 * @param insn - See readOpcodeModifier().
1440 * @param size - The width (in bytes) of the register being specified.
1441 * 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1443 * @return - 0 on success; nonzero otherwise.
1445 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1446 dbgprintf(insn, "readOpcodeRegister()");
1448 if (readOpcodeModifier(insn))
1452 size = insn->registerSize;
1456 insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1457 | insn->opcodeModifier));
1458 if (insn->rexPrefix &&
1459 insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1460 insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1461 insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1462 + (insn->opcodeRegister - MODRM_REG_AL - 4));
1467 insn->opcodeRegister = (Reg)(MODRM_REG_AX
1468 + ((bFromREX(insn->rexPrefix) << 3)
1469 | insn->opcodeModifier));
1472 insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1473 + ((bFromREX(insn->rexPrefix) << 3)
1474 | insn->opcodeModifier));
1477 insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1478 + ((bFromREX(insn->rexPrefix) << 3)
1479 | insn->opcodeModifier));
1487 * readImmediate - Consumes an immediate operand from an instruction, given the
1488 * desired operand size.
1490 * @param insn - The instruction whose operand is to be read.
1491 * @param size - The width (in bytes) of the operand.
1492 * @return - 0 if the immediate was successfully consumed; nonzero
1495 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1501 dbgprintf(insn, "readImmediate()");
1503 if (insn->numImmediatesConsumed == 2) {
1504 debug("Already consumed two immediates");
1509 size = insn->immediateSize;
1511 insn->immediateSize = size;
1512 insn->immediateOffset = insn->readerCursor - insn->startLocation;
1516 if (consumeByte(insn, &imm8))
1518 insn->immediates[insn->numImmediatesConsumed] = imm8;
1521 if (consumeUInt16(insn, &imm16))
1523 insn->immediates[insn->numImmediatesConsumed] = imm16;
1526 if (consumeUInt32(insn, &imm32))
1528 insn->immediates[insn->numImmediatesConsumed] = imm32;
1531 if (consumeUInt64(insn, &imm64))
1533 insn->immediates[insn->numImmediatesConsumed] = imm64;
1537 insn->numImmediatesConsumed++;
1543 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1545 * @param insn - The instruction whose operand is to be read.
1546 * @return - 0 if the vvvv was successfully consumed; nonzero
1549 static int readVVVV(struct InternalInstruction* insn) {
1550 dbgprintf(insn, "readVVVV()");
1552 if (insn->vexXopType == TYPE_VEX_3B)
1553 insn->vvvv = vvvvFromVEX3of3(insn->vexXopPrefix[2]);
1554 else if (insn->vexXopType == TYPE_VEX_2B)
1555 insn->vvvv = vvvvFromVEX2of2(insn->vexXopPrefix[1]);
1556 else if (insn->vexXopType == TYPE_XOP)
1557 insn->vvvv = vvvvFromXOP3of3(insn->vexXopPrefix[2]);
1561 if (insn->mode != MODE_64BIT)
1568 * readOperands - Consults the specifier for an instruction and consumes all
1569 * operands for that instruction, interpreting them as it goes.
1571 * @param insn - The instruction whose operands are to be read and interpreted.
1572 * @return - 0 if all operands could be read; nonzero otherwise.
1574 static int readOperands(struct InternalInstruction* insn) {
1576 int hasVVVV, needVVVV;
1579 dbgprintf(insn, "readOperands()");
1581 /* If non-zero vvvv specified, need to make sure one of the operands
1583 hasVVVV = !readVVVV(insn);
1584 needVVVV = hasVVVV && (insn->vvvv != 0);
1586 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
1587 switch (x86OperandSets[insn->spec->operands][index].encoding) {
1592 if (readModRM(insn))
1594 if (fixupReg(insn, &x86OperandSets[insn->spec->operands][index]))
1603 dbgprintf(insn, "We currently don't hande code-offset encodings");
1607 /* Saw a register immediate so don't read again and instead split the
1608 previous immediate. FIXME: This is a hack. */
1609 insn->immediates[insn->numImmediatesConsumed] =
1610 insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1611 ++insn->numImmediatesConsumed;
1614 if (readImmediate(insn, 1))
1616 if (x86OperandSets[insn->spec->operands][index].type == TYPE_IMM3 &&
1617 insn->immediates[insn->numImmediatesConsumed - 1] > 7)
1619 if (x86OperandSets[insn->spec->operands][index].type == TYPE_IMM5 &&
1620 insn->immediates[insn->numImmediatesConsumed - 1] > 31)
1622 if (x86OperandSets[insn->spec->operands][index].type == TYPE_XMM128 ||
1623 x86OperandSets[insn->spec->operands][index].type == TYPE_XMM256)
1627 if (readImmediate(insn, 2))
1631 if (readImmediate(insn, 4))
1635 if (readImmediate(insn, 8))
1639 if (readImmediate(insn, insn->immediateSize))
1643 if (readImmediate(insn, insn->addressSize))
1647 if (readOpcodeRegister(insn, 1))
1651 if (readOpcodeRegister(insn, 2))
1655 if (readOpcodeRegister(insn, 4))
1659 if (readOpcodeRegister(insn, 8))
1663 if (readOpcodeRegister(insn, 0))
1667 if (readOpcodeModifier(insn))
1671 needVVVV = 0; /* Mark that we have found a VVVV operand. */
1674 if (fixupReg(insn, &x86OperandSets[insn->spec->operands][index]))
1680 dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1685 /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1686 if (needVVVV) return -1;
1692 * decodeInstruction - Reads and interprets a full instruction provided by the
1695 * @param insn - A pointer to the instruction to be populated. Must be
1697 * @param reader - The function to be used to read the instruction's bytes.
1698 * @param readerArg - A generic argument to be passed to the reader to store
1699 * any internal state.
1700 * @param logger - If non-NULL, the function to be used to write log messages
1702 * @param loggerArg - A generic argument to be passed to the logger to store
1703 * any internal state.
1704 * @param startLoc - The address (in the reader's address space) of the first
1705 * byte in the instruction.
1706 * @param mode - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1707 * decode the instruction in.
1708 * @return - 0 if the instruction's memory could be read; nonzero if
1711 int decodeInstruction(struct InternalInstruction* insn,
1712 byteReader_t reader,
1713 const void* readerArg,
1718 DisassemblerMode mode) {
1719 memset(insn, 0, sizeof(struct InternalInstruction));
1721 insn->reader = reader;
1722 insn->readerArg = readerArg;
1723 insn->dlog = logger;
1724 insn->dlogArg = loggerArg;
1725 insn->startLocation = startLoc;
1726 insn->readerCursor = startLoc;
1728 insn->numImmediatesConsumed = 0;
1730 if (readPrefixes(insn) ||
1732 getID(insn, miiArg) ||
1733 insn->instructionID == 0 ||
1737 insn->operands = &x86OperandSets[insn->spec->operands][0];
1739 insn->length = insn->readerCursor - insn->startLocation;
1741 dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1742 startLoc, insn->readerCursor, insn->length);
1744 if (insn->length > 15)
1745 dbgprintf(insn, "Instruction exceeds 15-byte limit");