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"
31 #define debug(s) do { x86DisassemblerDebug(__FILE__, __LINE__, s); } while (0)
33 #define debug(s) do { } while (0)
38 * contextForAttrs - Client for the instruction context table. Takes a set of
39 * attributes and returns the appropriate decode context.
41 * @param attrMask - Attributes, from the enumeration attributeBits.
42 * @return - The InstructionContext to use when looking up an
43 * an instruction with these attributes.
45 static InstructionContext contextForAttrs(uint8_t attrMask) {
46 return CONTEXTS_SYM[attrMask];
50 * modRMRequired - Reads the appropriate instruction table to determine whether
51 * the ModR/M byte is required to decode a particular instruction.
53 * @param type - The opcode type (i.e., how many bytes it has).
54 * @param insnContext - The context for the instruction, as returned by
56 * @param opcode - The last byte of the instruction's opcode, not counting
57 * ModR/M extensions and escapes.
58 * @return - TRUE if the ModR/M byte is required, FALSE otherwise.
60 static int modRMRequired(OpcodeType type,
61 InstructionContext insnContext,
63 const struct ContextDecision* decision = 0;
67 decision = &ONEBYTE_SYM;
70 decision = &TWOBYTE_SYM;
73 decision = &THREEBYTE38_SYM;
76 decision = &THREEBYTE3A_SYM;
79 decision = &THREEBYTEA6_SYM;
82 decision = &THREEBYTEA7_SYM;
86 return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].
87 modrm_type != MODRM_ONEENTRY;
93 * decode - Reads the appropriate instruction table to obtain the unique ID of
96 * @param type - See modRMRequired().
97 * @param insnContext - See modRMRequired().
98 * @param opcode - See modRMRequired().
99 * @param modRM - The ModR/M byte if required, or any value if not.
100 * @return - The UID of the instruction, or 0 on failure.
102 static InstrUID decode(OpcodeType type,
103 InstructionContext insnContext,
106 const struct ModRMDecision* dec;
110 debug("Unknown opcode type");
113 dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
116 dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
119 dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
122 dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
125 dec = &THREEBYTEA6_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
128 dec = &THREEBYTEA7_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
132 switch (dec->modrm_type) {
134 debug("Corrupt table! Unknown modrm_type");
137 return dec->instructionIDs[0];
139 if (modFromModRM(modRM) == 0x3)
140 return dec->instructionIDs[1];
142 return dec->instructionIDs[0];
144 return dec->instructionIDs[modRM];
149 * specifierForUID - Given a UID, returns the name and operand specification for
152 * @param uid - The unique ID for the instruction. This should be returned by
153 * decode(); specifierForUID will not check bounds.
154 * @return - A pointer to the specification for that instruction.
156 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
157 return &INSTRUCTIONS_SYM[uid];
161 * consumeByte - Uses the reader function provided by the user to consume one
162 * byte from the instruction's memory and advance the cursor.
164 * @param insn - The instruction with the reader function to use. The cursor
165 * for this instruction is advanced.
166 * @param byte - A pointer to a pre-allocated memory buffer to be populated
167 * with the data read.
168 * @return - 0 if the read was successful; nonzero otherwise.
170 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
171 int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
174 ++(insn->readerCursor);
180 * lookAtByte - Like consumeByte, but does not advance the cursor.
182 * @param insn - See consumeByte().
183 * @param byte - See consumeByte().
184 * @return - See consumeByte().
186 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
187 return insn->reader(insn->readerArg, byte, insn->readerCursor);
190 static void unconsumeByte(struct InternalInstruction* insn) {
191 insn->readerCursor--;
194 #define CONSUME_FUNC(name, type) \
195 static int name(struct InternalInstruction* insn, type* ptr) { \
198 for (offset = 0; offset < sizeof(type); ++offset) { \
200 int ret = insn->reader(insn->readerArg, \
202 insn->readerCursor + offset); \
205 combined = combined | ((type)byte << ((type)offset * 8)); \
208 insn->readerCursor += sizeof(type); \
213 * consume* - Use the reader function provided by the user to consume data
214 * values of various sizes from the instruction's memory and advance the
215 * cursor appropriately. These readers perform endian conversion.
217 * @param insn - See consumeByte().
218 * @param ptr - A pointer to a pre-allocated memory of appropriate size to
219 * be populated with the data read.
220 * @return - See consumeByte().
222 CONSUME_FUNC(consumeInt8, int8_t)
223 CONSUME_FUNC(consumeInt16, int16_t)
224 CONSUME_FUNC(consumeInt32, int32_t)
225 CONSUME_FUNC(consumeUInt16, uint16_t)
226 CONSUME_FUNC(consumeUInt32, uint32_t)
227 CONSUME_FUNC(consumeUInt64, uint64_t)
230 * dbgprintf - Uses the logging function provided by the user to log a single
231 * message, typically without a carriage-return.
233 * @param insn - The instruction containing the logging function.
234 * @param format - See printf().
235 * @param ... - See printf().
237 static void dbgprintf(struct InternalInstruction* insn,
246 va_start(ap, format);
247 (void)vsnprintf(buffer, sizeof(buffer), format, ap);
250 insn->dlog(insn->dlogArg, buffer);
256 * setPrefixPresent - Marks that a particular prefix is present at a particular
259 * @param insn - The instruction to be marked as having the prefix.
260 * @param prefix - The prefix that is present.
261 * @param location - The location where the prefix is located (in the address
262 * space of the instruction's reader).
264 static void setPrefixPresent(struct InternalInstruction* insn,
268 insn->prefixPresent[prefix] = 1;
269 insn->prefixLocations[prefix] = location;
273 * isPrefixAtLocation - Queries an instruction to determine whether a prefix is
274 * present at a given location.
276 * @param insn - The instruction to be queried.
277 * @param prefix - The prefix.
278 * @param location - The location to query.
279 * @return - Whether the prefix is at that location.
281 static BOOL isPrefixAtLocation(struct InternalInstruction* insn,
285 if (insn->prefixPresent[prefix] == 1 &&
286 insn->prefixLocations[prefix] == location)
293 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
294 * instruction as having them. Also sets the instruction's default operand,
295 * address, and other relevant data sizes to report operands correctly.
297 * @param insn - The instruction whose prefixes are to be read.
298 * @return - 0 if the instruction could be read until the end of the prefix
299 * bytes, and no prefixes conflicted; nonzero otherwise.
301 static int readPrefixes(struct InternalInstruction* insn) {
302 BOOL isPrefix = TRUE;
303 BOOL prefixGroups[4] = { FALSE };
304 uint64_t prefixLocation;
307 BOOL hasAdSize = FALSE;
308 BOOL hasOpSize = FALSE;
310 dbgprintf(insn, "readPrefixes()");
313 prefixLocation = insn->readerCursor;
315 if (consumeByte(insn, &byte))
319 case 0xf0: /* LOCK */
320 case 0xf2: /* REPNE/REPNZ */
321 case 0xf3: /* REP or REPE/REPZ */
323 dbgprintf(insn, "Redundant Group 1 prefix");
324 prefixGroups[0] = TRUE;
325 setPrefixPresent(insn, byte, prefixLocation);
327 case 0x2e: /* CS segment override -OR- Branch not taken */
328 case 0x36: /* SS segment override -OR- Branch taken */
329 case 0x3e: /* DS segment override */
330 case 0x26: /* ES segment override */
331 case 0x64: /* FS segment override */
332 case 0x65: /* GS segment override */
335 insn->segmentOverride = SEG_OVERRIDE_CS;
338 insn->segmentOverride = SEG_OVERRIDE_SS;
341 insn->segmentOverride = SEG_OVERRIDE_DS;
344 insn->segmentOverride = SEG_OVERRIDE_ES;
347 insn->segmentOverride = SEG_OVERRIDE_FS;
350 insn->segmentOverride = SEG_OVERRIDE_GS;
353 debug("Unhandled override");
357 dbgprintf(insn, "Redundant Group 2 prefix");
358 prefixGroups[1] = TRUE;
359 setPrefixPresent(insn, byte, prefixLocation);
361 case 0x66: /* Operand-size override */
363 dbgprintf(insn, "Redundant Group 3 prefix");
364 prefixGroups[2] = TRUE;
366 setPrefixPresent(insn, byte, prefixLocation);
368 case 0x67: /* Address-size override */
370 dbgprintf(insn, "Redundant Group 4 prefix");
371 prefixGroups[3] = TRUE;
373 setPrefixPresent(insn, byte, prefixLocation);
375 default: /* Not a prefix byte */
381 dbgprintf(insn, "Found prefix 0x%hhx", byte);
389 if (lookAtByte(insn, &byte1)) {
390 dbgprintf(insn, "Couldn't read second byte of VEX");
394 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
396 insn->necessaryPrefixLocation = insn->readerCursor - 1;
400 insn->necessaryPrefixLocation = insn->readerCursor - 1;
403 if (insn->vexSize == 3) {
404 insn->vexPrefix[0] = byte;
405 consumeByte(insn, &insn->vexPrefix[1]);
406 consumeByte(insn, &insn->vexPrefix[2]);
408 /* We simulate the REX prefix for simplicity's sake */
410 if (insn->mode == MODE_64BIT) {
411 insn->rexPrefix = 0x40
412 | (wFromVEX3of3(insn->vexPrefix[2]) << 3)
413 | (rFromVEX2of3(insn->vexPrefix[1]) << 2)
414 | (xFromVEX2of3(insn->vexPrefix[1]) << 1)
415 | (bFromVEX2of3(insn->vexPrefix[1]) << 0);
418 switch (ppFromVEX3of3(insn->vexPrefix[2]))
427 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1], insn->vexPrefix[2]);
430 else if (byte == 0xc5) {
433 if (lookAtByte(insn, &byte1)) {
434 dbgprintf(insn, "Couldn't read second byte of VEX");
438 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
445 if (insn->vexSize == 2) {
446 insn->vexPrefix[0] = byte;
447 consumeByte(insn, &insn->vexPrefix[1]);
449 if (insn->mode == MODE_64BIT) {
450 insn->rexPrefix = 0x40
451 | (rFromVEX2of2(insn->vexPrefix[1]) << 2);
454 switch (ppFromVEX2of2(insn->vexPrefix[1]))
463 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1]);
467 if (insn->mode == MODE_64BIT) {
468 if ((byte & 0xf0) == 0x40) {
471 if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
472 dbgprintf(insn, "Redundant REX prefix");
476 insn->rexPrefix = byte;
477 insn->necessaryPrefixLocation = insn->readerCursor - 2;
479 dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
482 insn->necessaryPrefixLocation = insn->readerCursor - 1;
486 insn->necessaryPrefixLocation = insn->readerCursor - 1;
490 if (insn->mode == MODE_16BIT) {
491 insn->registerSize = (hasOpSize ? 4 : 2);
492 insn->addressSize = (hasAdSize ? 4 : 2);
493 insn->displacementSize = (hasAdSize ? 4 : 2);
494 insn->immediateSize = (hasOpSize ? 4 : 2);
495 } else if (insn->mode == MODE_32BIT) {
496 insn->registerSize = (hasOpSize ? 2 : 4);
497 insn->addressSize = (hasAdSize ? 2 : 4);
498 insn->displacementSize = (hasAdSize ? 2 : 4);
499 insn->immediateSize = (hasOpSize ? 2 : 4);
500 } else if (insn->mode == MODE_64BIT) {
501 if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
502 insn->registerSize = 8;
503 insn->addressSize = (hasAdSize ? 4 : 8);
504 insn->displacementSize = 4;
505 insn->immediateSize = 4;
506 } else if (insn->rexPrefix) {
507 insn->registerSize = (hasOpSize ? 2 : 4);
508 insn->addressSize = (hasAdSize ? 4 : 8);
509 insn->displacementSize = (hasOpSize ? 2 : 4);
510 insn->immediateSize = (hasOpSize ? 2 : 4);
512 insn->registerSize = (hasOpSize ? 2 : 4);
513 insn->addressSize = (hasAdSize ? 4 : 8);
514 insn->displacementSize = (hasOpSize ? 2 : 4);
515 insn->immediateSize = (hasOpSize ? 2 : 4);
523 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
524 * extended or escape opcodes).
526 * @param insn - The instruction whose opcode is to be read.
527 * @return - 0 if the opcode could be read successfully; nonzero otherwise.
529 static int readOpcode(struct InternalInstruction* insn) {
530 /* Determine the length of the primary opcode */
534 dbgprintf(insn, "readOpcode()");
536 insn->opcodeType = ONEBYTE;
538 if (insn->vexSize == 3)
540 switch (mmmmmFromVEX2of3(insn->vexPrefix[1]))
543 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)", mmmmmFromVEX2of3(insn->vexPrefix[1]));
548 insn->twoByteEscape = 0x0f;
549 insn->opcodeType = TWOBYTE;
550 return consumeByte(insn, &insn->opcode);
552 insn->twoByteEscape = 0x0f;
553 insn->threeByteEscape = 0x38;
554 insn->opcodeType = THREEBYTE_38;
555 return consumeByte(insn, &insn->opcode);
557 insn->twoByteEscape = 0x0f;
558 insn->threeByteEscape = 0x3a;
559 insn->opcodeType = THREEBYTE_3A;
560 return consumeByte(insn, &insn->opcode);
563 else if (insn->vexSize == 2)
565 insn->twoByteEscape = 0x0f;
566 insn->opcodeType = TWOBYTE;
567 return consumeByte(insn, &insn->opcode);
570 if (consumeByte(insn, ¤t))
573 if (current == 0x0f) {
574 dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
576 insn->twoByteEscape = current;
578 if (consumeByte(insn, ¤t))
581 if (current == 0x38) {
582 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
584 insn->threeByteEscape = current;
586 if (consumeByte(insn, ¤t))
589 insn->opcodeType = THREEBYTE_38;
590 } else if (current == 0x3a) {
591 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
593 insn->threeByteEscape = current;
595 if (consumeByte(insn, ¤t))
598 insn->opcodeType = THREEBYTE_3A;
599 } else if (current == 0xa6) {
600 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
602 insn->threeByteEscape = current;
604 if (consumeByte(insn, ¤t))
607 insn->opcodeType = THREEBYTE_A6;
608 } else if (current == 0xa7) {
609 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
611 insn->threeByteEscape = current;
613 if (consumeByte(insn, ¤t))
616 insn->opcodeType = THREEBYTE_A7;
618 dbgprintf(insn, "Didn't find a three-byte escape prefix");
620 insn->opcodeType = TWOBYTE;
625 * At this point we have consumed the full opcode.
626 * Anything we consume from here on must be unconsumed.
629 insn->opcode = current;
634 static int readModRM(struct InternalInstruction* insn);
637 * getIDWithAttrMask - Determines the ID of an instruction, consuming
638 * the ModR/M byte as appropriate for extended and escape opcodes,
639 * and using a supplied attribute mask.
641 * @param instructionID - A pointer whose target is filled in with the ID of the
643 * @param insn - The instruction whose ID is to be determined.
644 * @param attrMask - The attribute mask to search.
645 * @return - 0 if the ModR/M could be read when needed or was not
646 * needed; nonzero otherwise.
648 static int getIDWithAttrMask(uint16_t* instructionID,
649 struct InternalInstruction* insn,
651 BOOL hasModRMExtension;
653 uint8_t instructionClass;
655 instructionClass = contextForAttrs(attrMask);
657 hasModRMExtension = modRMRequired(insn->opcodeType,
661 if (hasModRMExtension) {
665 *instructionID = decode(insn->opcodeType,
670 *instructionID = decode(insn->opcodeType,
680 * is16BitEquivalent - Determines whether two instruction names refer to
681 * equivalent instructions but one is 16-bit whereas the other is not.
683 * @param orig - The instruction that is not 16-bit
684 * @param equiv - The instruction that is 16-bit
686 static BOOL is16BitEquvalent(const char* orig, const char* equiv) {
690 if (orig[i] == '\0' && equiv[i] == '\0')
692 if (orig[i] == '\0' || equiv[i] == '\0')
694 if (orig[i] != equiv[i]) {
695 if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
697 if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
699 if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
707 * is64BitEquivalent - Determines whether two instruction names refer to
708 * equivalent instructions but one is 64-bit whereas the other is not.
710 * @param orig - The instruction that is not 64-bit
711 * @param equiv - The instruction that is 64-bit
713 static BOOL is64BitEquivalent(const char* orig, const char* equiv) {
717 if (orig[i] == '\0' && equiv[i] == '\0')
719 if (orig[i] == '\0' || equiv[i] == '\0')
721 if (orig[i] != equiv[i]) {
722 if ((orig[i] == 'W' || orig[i] == 'L') && equiv[i] == 'Q')
724 if ((orig[i] == '1' || orig[i] == '3') && equiv[i] == '6')
726 if ((orig[i] == '6' || orig[i] == '2') && equiv[i] == '4')
735 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
736 * appropriate for extended and escape opcodes. Determines the attributes and
737 * context for the instruction before doing so.
739 * @param insn - The instruction whose ID is to be determined.
740 * @return - 0 if the ModR/M could be read when needed or was not needed;
743 static int getID(struct InternalInstruction* insn) {
745 uint16_t instructionID;
747 dbgprintf(insn, "getID()");
749 attrMask = ATTR_NONE;
751 if (insn->mode == MODE_64BIT)
752 attrMask |= ATTR_64BIT;
755 attrMask |= ATTR_VEX;
757 if (insn->vexSize == 3) {
758 switch (ppFromVEX3of3(insn->vexPrefix[2])) {
760 attrMask |= ATTR_OPSIZE;
770 if (lFromVEX3of3(insn->vexPrefix[2]))
771 attrMask |= ATTR_VEXL;
773 else if (insn->vexSize == 2) {
774 switch (ppFromVEX2of2(insn->vexPrefix[1])) {
776 attrMask |= ATTR_OPSIZE;
786 if (lFromVEX2of2(insn->vexPrefix[1]))
787 attrMask |= ATTR_VEXL;
794 if (isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
795 attrMask |= ATTR_OPSIZE;
796 else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
798 else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
802 if (insn->rexPrefix & 0x08)
803 attrMask |= ATTR_REXW;
805 if (getIDWithAttrMask(&instructionID, insn, attrMask))
808 /* The following clauses compensate for limitations of the tables. */
810 if ((attrMask & ATTR_VEXL) && (attrMask & ATTR_REXW)) {
812 * Some VEX instructions ignore the L-bit, but use the W-bit. Normally L-bit
813 * has precedence since there are no L-bit with W-bit entries in the tables.
814 * So if the L-bit isn't significant we should use the W-bit instead.
817 const struct InstructionSpecifier *spec;
818 uint16_t instructionIDWithWBit;
819 const struct InstructionSpecifier *specWithWBit;
821 spec = specifierForUID(instructionID);
823 if (getIDWithAttrMask(&instructionIDWithWBit,
825 (attrMask & (~ATTR_VEXL)) | ATTR_REXW)) {
826 insn->instructionID = instructionID;
831 specWithWBit = specifierForUID(instructionIDWithWBit);
833 if (instructionID != instructionIDWithWBit) {
834 insn->instructionID = instructionIDWithWBit;
835 insn->spec = specWithWBit;
837 insn->instructionID = instructionID;
843 if ((attrMask & ATTR_XD) && (attrMask & ATTR_REXW)) {
845 * Although for SSE instructions it is usually necessary to treat REX.W+F2
846 * as F2 for decode (in the absence of a 64BIT_REXW_XD category) there is
847 * an occasional instruction where F2 is incidental and REX.W is the more
848 * significant. If the decoded instruction is 32-bit and adding REX.W
849 * instead of F2 changes a 32 to a 64, we adopt the new encoding.
852 const struct InstructionSpecifier *spec;
853 uint16_t instructionIDWithREXw;
854 const struct InstructionSpecifier *specWithREXw;
856 spec = specifierForUID(instructionID);
858 if (getIDWithAttrMask(&instructionIDWithREXw,
860 attrMask & (~ATTR_XD))) {
862 * Decoding with REX.w would yield nothing; give up and return original
866 insn->instructionID = instructionID;
871 specWithREXw = specifierForUID(instructionIDWithREXw);
873 if (is64BitEquivalent(spec->name, specWithREXw->name)) {
874 insn->instructionID = instructionIDWithREXw;
875 insn->spec = specWithREXw;
877 insn->instructionID = instructionID;
883 if (insn->prefixPresent[0x66] && !(attrMask & ATTR_OPSIZE)) {
885 * The instruction tables make no distinction between instructions that
886 * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
887 * particular spot (i.e., many MMX operations). In general we're
888 * conservative, but in the specific case where OpSize is present but not
889 * in the right place we check if there's a 16-bit operation.
892 const struct InstructionSpecifier *spec;
893 uint16_t instructionIDWithOpsize;
894 const struct InstructionSpecifier *specWithOpsize;
896 spec = specifierForUID(instructionID);
898 if (getIDWithAttrMask(&instructionIDWithOpsize,
900 attrMask | ATTR_OPSIZE)) {
902 * ModRM required with OpSize but not present; give up and return version
906 insn->instructionID = instructionID;
911 specWithOpsize = specifierForUID(instructionIDWithOpsize);
913 if (is16BitEquvalent(spec->name, specWithOpsize->name)) {
914 insn->instructionID = instructionIDWithOpsize;
915 insn->spec = specWithOpsize;
917 insn->instructionID = instructionID;
923 if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
924 insn->rexPrefix & 0x01) {
926 * NOOP shouldn't decode as NOOP if REX.b is set. Instead
927 * it should decode as XCHG %r8, %eax.
930 const struct InstructionSpecifier *spec;
931 uint16_t instructionIDWithNewOpcode;
932 const struct InstructionSpecifier *specWithNewOpcode;
934 spec = specifierForUID(instructionID);
936 /* Borrow opcode from one of the other XCHGar opcodes */
939 if (getIDWithAttrMask(&instructionIDWithNewOpcode,
944 insn->instructionID = instructionID;
949 specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
954 insn->instructionID = instructionIDWithNewOpcode;
955 insn->spec = specWithNewOpcode;
960 insn->instructionID = instructionID;
961 insn->spec = specifierForUID(insn->instructionID);
967 * readSIB - Consumes the SIB byte to determine addressing information for an
970 * @param insn - The instruction whose SIB byte is to be read.
971 * @return - 0 if the SIB byte was successfully read; nonzero otherwise.
973 static int readSIB(struct InternalInstruction* insn) {
974 SIBIndex sibIndexBase = 0;
975 SIBBase sibBaseBase = 0;
978 dbgprintf(insn, "readSIB()");
980 if (insn->consumedSIB)
983 insn->consumedSIB = TRUE;
985 switch (insn->addressSize) {
987 dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
991 sibIndexBase = SIB_INDEX_EAX;
992 sibBaseBase = SIB_BASE_EAX;
995 sibIndexBase = SIB_INDEX_RAX;
996 sibBaseBase = SIB_BASE_RAX;
1000 if (consumeByte(insn, &insn->sib))
1003 index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1007 insn->sibIndex = SIB_INDEX_NONE;
1010 insn->sibIndex = (SIBIndex)(sibIndexBase + index);
1011 if (insn->sibIndex == SIB_INDEX_sib ||
1012 insn->sibIndex == SIB_INDEX_sib64)
1013 insn->sibIndex = SIB_INDEX_NONE;
1017 switch (scaleFromSIB(insn->sib)) {
1032 base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1036 switch (modFromModRM(insn->modRM)) {
1038 insn->eaDisplacement = EA_DISP_32;
1039 insn->sibBase = SIB_BASE_NONE;
1042 insn->eaDisplacement = EA_DISP_8;
1043 insn->sibBase = (insn->addressSize == 4 ?
1044 SIB_BASE_EBP : SIB_BASE_RBP);
1047 insn->eaDisplacement = EA_DISP_32;
1048 insn->sibBase = (insn->addressSize == 4 ?
1049 SIB_BASE_EBP : SIB_BASE_RBP);
1052 debug("Cannot have Mod = 0b11 and a SIB byte");
1057 insn->sibBase = (SIBBase)(sibBaseBase + base);
1065 * readDisplacement - Consumes the displacement of an instruction.
1067 * @param insn - The instruction whose displacement is to be read.
1068 * @return - 0 if the displacement byte was successfully read; nonzero
1071 static int readDisplacement(struct InternalInstruction* insn) {
1076 dbgprintf(insn, "readDisplacement()");
1078 if (insn->consumedDisplacement)
1081 insn->consumedDisplacement = TRUE;
1083 switch (insn->eaDisplacement) {
1085 insn->consumedDisplacement = FALSE;
1088 if (consumeInt8(insn, &d8))
1090 insn->displacement = d8;
1093 if (consumeInt16(insn, &d16))
1095 insn->displacement = d16;
1098 if (consumeInt32(insn, &d32))
1100 insn->displacement = d32;
1104 insn->consumedDisplacement = TRUE;
1109 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1110 * displacement) for an instruction and interprets it.
1112 * @param insn - The instruction whose addressing information is to be read.
1113 * @return - 0 if the information was successfully read; nonzero otherwise.
1115 static int readModRM(struct InternalInstruction* insn) {
1116 uint8_t mod, rm, reg;
1118 dbgprintf(insn, "readModRM()");
1120 if (insn->consumedModRM)
1123 if (consumeByte(insn, &insn->modRM))
1125 insn->consumedModRM = TRUE;
1127 mod = modFromModRM(insn->modRM);
1128 rm = rmFromModRM(insn->modRM);
1129 reg = regFromModRM(insn->modRM);
1132 * This goes by insn->registerSize to pick the correct register, which messes
1133 * up if we're using (say) XMM or 8-bit register operands. That gets fixed in
1136 switch (insn->registerSize) {
1138 insn->regBase = MODRM_REG_AX;
1139 insn->eaRegBase = EA_REG_AX;
1142 insn->regBase = MODRM_REG_EAX;
1143 insn->eaRegBase = EA_REG_EAX;
1146 insn->regBase = MODRM_REG_RAX;
1147 insn->eaRegBase = EA_REG_RAX;
1151 reg |= rFromREX(insn->rexPrefix) << 3;
1152 rm |= bFromREX(insn->rexPrefix) << 3;
1154 insn->reg = (Reg)(insn->regBase + reg);
1156 switch (insn->addressSize) {
1158 insn->eaBaseBase = EA_BASE_BX_SI;
1163 insn->eaBase = EA_BASE_NONE;
1164 insn->eaDisplacement = EA_DISP_16;
1165 if (readDisplacement(insn))
1168 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1169 insn->eaDisplacement = EA_DISP_NONE;
1173 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1174 insn->eaDisplacement = EA_DISP_8;
1175 if (readDisplacement(insn))
1179 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1180 insn->eaDisplacement = EA_DISP_16;
1181 if (readDisplacement(insn))
1185 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1186 if (readDisplacement(insn))
1193 insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1197 insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1200 case 0xc: /* in case REXW.b is set */
1201 insn->eaBase = (insn->addressSize == 4 ?
1202 EA_BASE_sib : EA_BASE_sib64);
1204 if (readDisplacement(insn))
1208 insn->eaBase = EA_BASE_NONE;
1209 insn->eaDisplacement = EA_DISP_32;
1210 if (readDisplacement(insn))
1214 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1220 insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1223 case 0xc: /* in case REXW.b is set */
1224 insn->eaBase = EA_BASE_sib;
1226 if (readDisplacement(insn))
1230 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1231 if (readDisplacement(insn))
1237 insn->eaDisplacement = EA_DISP_NONE;
1238 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1242 } /* switch (insn->addressSize) */
1247 #define GENERIC_FIXUP_FUNC(name, base, prefix) \
1248 static uint8_t name(struct InternalInstruction *insn, \
1255 debug("Unhandled register type"); \
1259 return base + index; \
1261 if (insn->rexPrefix && \
1262 index >= 4 && index <= 7) { \
1263 return prefix##_SPL + (index - 4); \
1265 return prefix##_AL + index; \
1268 return prefix##_AX + index; \
1270 return prefix##_EAX + index; \
1272 return prefix##_RAX + index; \
1274 return prefix##_YMM0 + index; \
1279 return prefix##_XMM0 + index; \
1285 return prefix##_MM0 + index; \
1286 case TYPE_SEGMENTREG: \
1289 return prefix##_ES + index; \
1290 case TYPE_DEBUGREG: \
1293 return prefix##_DR0 + index; \
1294 case TYPE_CONTROLREG: \
1297 return prefix##_CR0 + index; \
1302 * fixup*Value - Consults an operand type to determine the meaning of the
1303 * reg or R/M field. If the operand is an XMM operand, for example, an
1304 * operand would be XMM0 instead of AX, which readModRM() would otherwise
1305 * misinterpret it as.
1307 * @param insn - The instruction containing the operand.
1308 * @param type - The operand type.
1309 * @param index - The existing value of the field as reported by readModRM().
1310 * @param valid - The address of a uint8_t. The target is set to 1 if the
1311 * field is valid for the register class; 0 if not.
1312 * @return - The proper value.
1314 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG)
1315 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG)
1318 * fixupReg - Consults an operand specifier to determine which of the
1319 * fixup*Value functions to use in correcting readModRM()'ss interpretation.
1321 * @param insn - See fixup*Value().
1322 * @param op - The operand specifier.
1323 * @return - 0 if fixup was successful; -1 if the register returned was
1324 * invalid for its class.
1326 static int fixupReg(struct InternalInstruction *insn,
1327 const struct OperandSpecifier *op) {
1330 dbgprintf(insn, "fixupReg()");
1332 switch ((OperandEncoding)op->encoding) {
1334 debug("Expected a REG or R/M encoding in fixupReg");
1337 insn->vvvv = (Reg)fixupRegValue(insn,
1338 (OperandType)op->type,
1345 insn->reg = (Reg)fixupRegValue(insn,
1346 (OperandType)op->type,
1347 insn->reg - insn->regBase,
1353 if (insn->eaBase >= insn->eaRegBase) {
1354 insn->eaBase = (EABase)fixupRMValue(insn,
1355 (OperandType)op->type,
1356 insn->eaBase - insn->eaRegBase,
1368 * readOpcodeModifier - Reads an operand from the opcode field of an
1369 * instruction. Handles AddRegFrm instructions.
1371 * @param insn - The instruction whose opcode field is to be read.
1372 * @param inModRM - Indicates that the opcode field is to be read from the
1373 * ModR/M extension; useful for escape opcodes
1374 * @return - 0 on success; nonzero otherwise.
1376 static int readOpcodeModifier(struct InternalInstruction* insn) {
1377 dbgprintf(insn, "readOpcodeModifier()");
1379 if (insn->consumedOpcodeModifier)
1382 insn->consumedOpcodeModifier = TRUE;
1384 switch (insn->spec->modifierType) {
1386 debug("Unknown modifier type.");
1389 debug("No modifier but an operand expects one.");
1391 case MODIFIER_OPCODE:
1392 insn->opcodeModifier = insn->opcode - insn->spec->modifierBase;
1394 case MODIFIER_MODRM:
1395 insn->opcodeModifier = insn->modRM - insn->spec->modifierBase;
1401 * readOpcodeRegister - Reads an operand from the opcode field of an
1402 * instruction and interprets it appropriately given the operand width.
1403 * Handles AddRegFrm instructions.
1405 * @param insn - See readOpcodeModifier().
1406 * @param size - The width (in bytes) of the register being specified.
1407 * 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1409 * @return - 0 on success; nonzero otherwise.
1411 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1412 dbgprintf(insn, "readOpcodeRegister()");
1414 if (readOpcodeModifier(insn))
1418 size = insn->registerSize;
1422 insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1423 | insn->opcodeModifier));
1424 if (insn->rexPrefix &&
1425 insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1426 insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1427 insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1428 + (insn->opcodeRegister - MODRM_REG_AL - 4));
1433 insn->opcodeRegister = (Reg)(MODRM_REG_AX
1434 + ((bFromREX(insn->rexPrefix) << 3)
1435 | insn->opcodeModifier));
1438 insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1439 + ((bFromREX(insn->rexPrefix) << 3)
1440 | insn->opcodeModifier));
1443 insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1444 + ((bFromREX(insn->rexPrefix) << 3)
1445 | insn->opcodeModifier));
1453 * readImmediate - Consumes an immediate operand from an instruction, given the
1454 * desired operand size.
1456 * @param insn - The instruction whose operand is to be read.
1457 * @param size - The width (in bytes) of the operand.
1458 * @return - 0 if the immediate was successfully consumed; nonzero
1461 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1467 dbgprintf(insn, "readImmediate()");
1469 if (insn->numImmediatesConsumed == 2) {
1470 debug("Already consumed two immediates");
1475 size = insn->immediateSize;
1477 insn->immediateSize = size;
1481 if (consumeByte(insn, &imm8))
1483 insn->immediates[insn->numImmediatesConsumed] = imm8;
1486 if (consumeUInt16(insn, &imm16))
1488 insn->immediates[insn->numImmediatesConsumed] = imm16;
1491 if (consumeUInt32(insn, &imm32))
1493 insn->immediates[insn->numImmediatesConsumed] = imm32;
1496 if (consumeUInt64(insn, &imm64))
1498 insn->immediates[insn->numImmediatesConsumed] = imm64;
1502 insn->numImmediatesConsumed++;
1508 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1510 * @param insn - The instruction whose operand is to be read.
1511 * @return - 0 if the vvvv was successfully consumed; nonzero
1514 static int readVVVV(struct InternalInstruction* insn) {
1515 dbgprintf(insn, "readVVVV()");
1517 if (insn->vexSize == 3)
1518 insn->vvvv = vvvvFromVEX3of3(insn->vexPrefix[2]);
1519 else if (insn->vexSize == 2)
1520 insn->vvvv = vvvvFromVEX2of2(insn->vexPrefix[1]);
1524 if (insn->mode != MODE_64BIT)
1531 * readOperands - Consults the specifier for an instruction and consumes all
1532 * operands for that instruction, interpreting them as it goes.
1534 * @param insn - The instruction whose operands are to be read and interpreted.
1535 * @return - 0 if all operands could be read; nonzero otherwise.
1537 static int readOperands(struct InternalInstruction* insn) {
1539 int hasVVVV, needVVVV;
1541 dbgprintf(insn, "readOperands()");
1543 /* If non-zero vvvv specified, need to make sure one of the operands
1545 hasVVVV = !readVVVV(insn);
1546 needVVVV = hasVVVV && (insn->vvvv != 0);
1548 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
1549 switch (insn->spec->operands[index].encoding) {
1554 if (readModRM(insn))
1556 if (fixupReg(insn, &insn->spec->operands[index]))
1565 dbgprintf(insn, "We currently don't hande code-offset encodings");
1568 if (readImmediate(insn, 1))
1570 if (insn->spec->operands[index].type == TYPE_IMM3 &&
1571 insn->immediates[insn->numImmediatesConsumed - 1] > 7)
1575 if (readImmediate(insn, 2))
1579 if (readImmediate(insn, 4))
1583 if (readImmediate(insn, 8))
1587 if (readImmediate(insn, insn->immediateSize))
1591 if (readImmediate(insn, insn->addressSize))
1595 if (readOpcodeRegister(insn, 1))
1599 if (readOpcodeRegister(insn, 2))
1603 if (readOpcodeRegister(insn, 4))
1607 if (readOpcodeRegister(insn, 8))
1611 if (readOpcodeRegister(insn, 0))
1615 if (readOpcodeModifier(insn))
1619 needVVVV = 0; /* Mark that we have found a VVVV operand. */
1622 if (fixupReg(insn, &insn->spec->operands[index]))
1628 dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1633 /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1634 if (needVVVV) return -1;
1640 * decodeInstruction - Reads and interprets a full instruction provided by the
1643 * @param insn - A pointer to the instruction to be populated. Must be
1645 * @param reader - The function to be used to read the instruction's bytes.
1646 * @param readerArg - A generic argument to be passed to the reader to store
1647 * any internal state.
1648 * @param logger - If non-NULL, the function to be used to write log messages
1650 * @param loggerArg - A generic argument to be passed to the logger to store
1651 * any internal state.
1652 * @param startLoc - The address (in the reader's address space) of the first
1653 * byte in the instruction.
1654 * @param mode - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1655 * decode the instruction in.
1656 * @return - 0 if the instruction's memory could be read; nonzero if
1659 int decodeInstruction(struct InternalInstruction* insn,
1660 byteReader_t reader,
1665 DisassemblerMode mode) {
1666 memset(insn, 0, sizeof(struct InternalInstruction));
1668 insn->reader = reader;
1669 insn->readerArg = readerArg;
1670 insn->dlog = logger;
1671 insn->dlogArg = loggerArg;
1672 insn->startLocation = startLoc;
1673 insn->readerCursor = startLoc;
1675 insn->numImmediatesConsumed = 0;
1677 if (readPrefixes(insn) ||
1680 insn->instructionID == 0 ||
1684 insn->length = insn->readerCursor - insn->startLocation;
1686 dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1687 startLoc, insn->readerCursor, insn->length);
1689 if (insn->length > 15)
1690 dbgprintf(insn, "Instruction exceeds 15-byte limit");