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 = 0;
110 dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
113 dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
116 dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
119 dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
122 dec = &THREEBYTEA6_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
125 dec = &THREEBYTEA7_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
129 switch (dec->modrm_type) {
131 debug("Corrupt table! Unknown modrm_type");
134 return dec->instructionIDs[0];
136 if (modFromModRM(modRM) == 0x3)
137 return dec->instructionIDs[1];
139 return dec->instructionIDs[0];
141 return dec->instructionIDs[modRM];
146 * specifierForUID - Given a UID, returns the name and operand specification for
149 * @param uid - The unique ID for the instruction. This should be returned by
150 * decode(); specifierForUID will not check bounds.
151 * @return - A pointer to the specification for that instruction.
153 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
154 return &INSTRUCTIONS_SYM[uid];
158 * consumeByte - Uses the reader function provided by the user to consume one
159 * byte from the instruction's memory and advance the cursor.
161 * @param insn - The instruction with the reader function to use. The cursor
162 * for this instruction is advanced.
163 * @param byte - A pointer to a pre-allocated memory buffer to be populated
164 * with the data read.
165 * @return - 0 if the read was successful; nonzero otherwise.
167 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
168 int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
171 ++(insn->readerCursor);
177 * lookAtByte - Like consumeByte, but does not advance the cursor.
179 * @param insn - See consumeByte().
180 * @param byte - See consumeByte().
181 * @return - See consumeByte().
183 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
184 return insn->reader(insn->readerArg, byte, insn->readerCursor);
187 static void unconsumeByte(struct InternalInstruction* insn) {
188 insn->readerCursor--;
191 #define CONSUME_FUNC(name, type) \
192 static int name(struct InternalInstruction* insn, type* ptr) { \
195 for (offset = 0; offset < sizeof(type); ++offset) { \
197 int ret = insn->reader(insn->readerArg, \
199 insn->readerCursor + offset); \
202 combined = combined | ((type)byte << ((type)offset * 8)); \
205 insn->readerCursor += sizeof(type); \
210 * consume* - Use the reader function provided by the user to consume data
211 * values of various sizes from the instruction's memory and advance the
212 * cursor appropriately. These readers perform endian conversion.
214 * @param insn - See consumeByte().
215 * @param ptr - A pointer to a pre-allocated memory of appropriate size to
216 * be populated with the data read.
217 * @return - See consumeByte().
219 CONSUME_FUNC(consumeInt8, int8_t)
220 CONSUME_FUNC(consumeInt16, int16_t)
221 CONSUME_FUNC(consumeInt32, int32_t)
222 CONSUME_FUNC(consumeUInt16, uint16_t)
223 CONSUME_FUNC(consumeUInt32, uint32_t)
224 CONSUME_FUNC(consumeUInt64, uint64_t)
227 * dbgprintf - Uses the logging function provided by the user to log a single
228 * message, typically without a carriage-return.
230 * @param insn - The instruction containing the logging function.
231 * @param format - See printf().
232 * @param ... - See printf().
234 static void dbgprintf(struct InternalInstruction* insn,
243 va_start(ap, format);
244 (void)vsnprintf(buffer, sizeof(buffer), format, ap);
247 insn->dlog(insn->dlogArg, buffer);
253 * setPrefixPresent - Marks that a particular prefix is present at a particular
256 * @param insn - The instruction to be marked as having the prefix.
257 * @param prefix - The prefix that is present.
258 * @param location - The location where the prefix is located (in the address
259 * space of the instruction's reader).
261 static void setPrefixPresent(struct InternalInstruction* insn,
265 insn->prefixPresent[prefix] = 1;
266 insn->prefixLocations[prefix] = location;
270 * isPrefixAtLocation - Queries an instruction to determine whether a prefix is
271 * present at a given location.
273 * @param insn - The instruction to be queried.
274 * @param prefix - The prefix.
275 * @param location - The location to query.
276 * @return - Whether the prefix is at that location.
278 static BOOL isPrefixAtLocation(struct InternalInstruction* insn,
282 if (insn->prefixPresent[prefix] == 1 &&
283 insn->prefixLocations[prefix] == location)
290 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
291 * instruction as having them. Also sets the instruction's default operand,
292 * address, and other relevant data sizes to report operands correctly.
294 * @param insn - The instruction whose prefixes are to be read.
295 * @return - 0 if the instruction could be read until the end of the prefix
296 * bytes, and no prefixes conflicted; nonzero otherwise.
298 static int readPrefixes(struct InternalInstruction* insn) {
299 BOOL isPrefix = TRUE;
300 BOOL prefixGroups[4] = { FALSE };
301 uint64_t prefixLocation;
304 BOOL hasAdSize = FALSE;
305 BOOL hasOpSize = FALSE;
307 dbgprintf(insn, "readPrefixes()");
310 prefixLocation = insn->readerCursor;
312 if (consumeByte(insn, &byte))
316 case 0xf0: /* LOCK */
317 case 0xf2: /* REPNE/REPNZ */
318 case 0xf3: /* REP or REPE/REPZ */
320 dbgprintf(insn, "Redundant Group 1 prefix");
321 prefixGroups[0] = TRUE;
322 setPrefixPresent(insn, byte, prefixLocation);
324 case 0x2e: /* CS segment override -OR- Branch not taken */
325 case 0x36: /* SS segment override -OR- Branch taken */
326 case 0x3e: /* DS segment override */
327 case 0x26: /* ES segment override */
328 case 0x64: /* FS segment override */
329 case 0x65: /* GS segment override */
332 insn->segmentOverride = SEG_OVERRIDE_CS;
335 insn->segmentOverride = SEG_OVERRIDE_SS;
338 insn->segmentOverride = SEG_OVERRIDE_DS;
341 insn->segmentOverride = SEG_OVERRIDE_ES;
344 insn->segmentOverride = SEG_OVERRIDE_FS;
347 insn->segmentOverride = SEG_OVERRIDE_GS;
350 debug("Unhandled override");
354 dbgprintf(insn, "Redundant Group 2 prefix");
355 prefixGroups[1] = TRUE;
356 setPrefixPresent(insn, byte, prefixLocation);
358 case 0x66: /* Operand-size override */
360 dbgprintf(insn, "Redundant Group 3 prefix");
361 prefixGroups[2] = TRUE;
363 setPrefixPresent(insn, byte, prefixLocation);
365 case 0x67: /* Address-size override */
367 dbgprintf(insn, "Redundant Group 4 prefix");
368 prefixGroups[3] = TRUE;
370 setPrefixPresent(insn, byte, prefixLocation);
372 default: /* Not a prefix byte */
378 dbgprintf(insn, "Found prefix 0x%hhx", byte);
386 if (lookAtByte(insn, &byte1)) {
387 dbgprintf(insn, "Couldn't read second byte of VEX");
391 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
393 insn->necessaryPrefixLocation = insn->readerCursor - 1;
397 insn->necessaryPrefixLocation = insn->readerCursor - 1;
400 if (insn->vexSize == 3) {
401 insn->vexPrefix[0] = byte;
402 consumeByte(insn, &insn->vexPrefix[1]);
403 consumeByte(insn, &insn->vexPrefix[2]);
405 /* We simulate the REX prefix for simplicity's sake */
407 if (insn->mode == MODE_64BIT) {
408 insn->rexPrefix = 0x40
409 | (wFromVEX3of3(insn->vexPrefix[2]) << 3)
410 | (rFromVEX2of3(insn->vexPrefix[1]) << 2)
411 | (xFromVEX2of3(insn->vexPrefix[1]) << 1)
412 | (bFromVEX2of3(insn->vexPrefix[1]) << 0);
415 switch (ppFromVEX3of3(insn->vexPrefix[2]))
424 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1], insn->vexPrefix[2]);
427 else if (byte == 0xc5) {
430 if (lookAtByte(insn, &byte1)) {
431 dbgprintf(insn, "Couldn't read second byte of VEX");
435 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
442 if (insn->vexSize == 2) {
443 insn->vexPrefix[0] = byte;
444 consumeByte(insn, &insn->vexPrefix[1]);
446 if (insn->mode == MODE_64BIT) {
447 insn->rexPrefix = 0x40
448 | (rFromVEX2of2(insn->vexPrefix[1]) << 2);
451 switch (ppFromVEX2of2(insn->vexPrefix[1]))
460 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1]);
464 if (insn->mode == MODE_64BIT) {
465 if ((byte & 0xf0) == 0x40) {
468 if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
469 dbgprintf(insn, "Redundant REX prefix");
473 insn->rexPrefix = byte;
474 insn->necessaryPrefixLocation = insn->readerCursor - 2;
476 dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
479 insn->necessaryPrefixLocation = insn->readerCursor - 1;
483 insn->necessaryPrefixLocation = insn->readerCursor - 1;
487 if (insn->mode == MODE_16BIT) {
488 insn->registerSize = (hasOpSize ? 4 : 2);
489 insn->addressSize = (hasAdSize ? 4 : 2);
490 insn->displacementSize = (hasAdSize ? 4 : 2);
491 insn->immediateSize = (hasOpSize ? 4 : 2);
492 } else if (insn->mode == MODE_32BIT) {
493 insn->registerSize = (hasOpSize ? 2 : 4);
494 insn->addressSize = (hasAdSize ? 2 : 4);
495 insn->displacementSize = (hasAdSize ? 2 : 4);
496 insn->immediateSize = (hasOpSize ? 2 : 4);
497 } else if (insn->mode == MODE_64BIT) {
498 if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
499 insn->registerSize = 8;
500 insn->addressSize = (hasAdSize ? 4 : 8);
501 insn->displacementSize = 4;
502 insn->immediateSize = 4;
503 } else if (insn->rexPrefix) {
504 insn->registerSize = (hasOpSize ? 2 : 4);
505 insn->addressSize = (hasAdSize ? 4 : 8);
506 insn->displacementSize = (hasOpSize ? 2 : 4);
507 insn->immediateSize = (hasOpSize ? 2 : 4);
509 insn->registerSize = (hasOpSize ? 2 : 4);
510 insn->addressSize = (hasAdSize ? 4 : 8);
511 insn->displacementSize = (hasOpSize ? 2 : 4);
512 insn->immediateSize = (hasOpSize ? 2 : 4);
520 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
521 * extended or escape opcodes).
523 * @param insn - The instruction whose opcode is to be read.
524 * @return - 0 if the opcode could be read successfully; nonzero otherwise.
526 static int readOpcode(struct InternalInstruction* insn) {
527 /* Determine the length of the primary opcode */
531 dbgprintf(insn, "readOpcode()");
533 insn->opcodeType = ONEBYTE;
535 if (insn->vexSize == 3)
537 switch (mmmmmFromVEX2of3(insn->vexPrefix[1]))
540 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)", mmmmmFromVEX2of3(insn->vexPrefix[1]));
545 insn->twoByteEscape = 0x0f;
546 insn->opcodeType = TWOBYTE;
547 return consumeByte(insn, &insn->opcode);
549 insn->twoByteEscape = 0x0f;
550 insn->threeByteEscape = 0x38;
551 insn->opcodeType = THREEBYTE_38;
552 return consumeByte(insn, &insn->opcode);
554 insn->twoByteEscape = 0x0f;
555 insn->threeByteEscape = 0x3a;
556 insn->opcodeType = THREEBYTE_3A;
557 return consumeByte(insn, &insn->opcode);
560 else if (insn->vexSize == 2)
562 insn->twoByteEscape = 0x0f;
563 insn->opcodeType = TWOBYTE;
564 return consumeByte(insn, &insn->opcode);
567 if (consumeByte(insn, ¤t))
570 if (current == 0x0f) {
571 dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
573 insn->twoByteEscape = current;
575 if (consumeByte(insn, ¤t))
578 if (current == 0x38) {
579 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
581 insn->threeByteEscape = current;
583 if (consumeByte(insn, ¤t))
586 insn->opcodeType = THREEBYTE_38;
587 } else if (current == 0x3a) {
588 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
590 insn->threeByteEscape = current;
592 if (consumeByte(insn, ¤t))
595 insn->opcodeType = THREEBYTE_3A;
596 } else if (current == 0xa6) {
597 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
599 insn->threeByteEscape = current;
601 if (consumeByte(insn, ¤t))
604 insn->opcodeType = THREEBYTE_A6;
605 } else if (current == 0xa7) {
606 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
608 insn->threeByteEscape = current;
610 if (consumeByte(insn, ¤t))
613 insn->opcodeType = THREEBYTE_A7;
615 dbgprintf(insn, "Didn't find a three-byte escape prefix");
617 insn->opcodeType = TWOBYTE;
622 * At this point we have consumed the full opcode.
623 * Anything we consume from here on must be unconsumed.
626 insn->opcode = current;
631 static int readModRM(struct InternalInstruction* insn);
634 * getIDWithAttrMask - Determines the ID of an instruction, consuming
635 * the ModR/M byte as appropriate for extended and escape opcodes,
636 * and using a supplied attribute mask.
638 * @param instructionID - A pointer whose target is filled in with the ID of the
640 * @param insn - The instruction whose ID is to be determined.
641 * @param attrMask - The attribute mask to search.
642 * @return - 0 if the ModR/M could be read when needed or was not
643 * needed; nonzero otherwise.
645 static int getIDWithAttrMask(uint16_t* instructionID,
646 struct InternalInstruction* insn,
648 BOOL hasModRMExtension;
650 uint8_t instructionClass;
652 instructionClass = contextForAttrs(attrMask);
654 hasModRMExtension = modRMRequired(insn->opcodeType,
658 if (hasModRMExtension) {
662 *instructionID = decode(insn->opcodeType,
667 *instructionID = decode(insn->opcodeType,
677 * is16BitEquivalent - Determines whether two instruction names refer to
678 * equivalent instructions but one is 16-bit whereas the other is not.
680 * @param orig - The instruction that is not 16-bit
681 * @param equiv - The instruction that is 16-bit
683 static BOOL is16BitEquvalent(const char* orig, const char* equiv) {
687 if (orig[i] == '\0' && equiv[i] == '\0')
689 if (orig[i] == '\0' || equiv[i] == '\0')
691 if (orig[i] != equiv[i]) {
692 if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
694 if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
696 if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
704 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
705 * appropriate for extended and escape opcodes. Determines the attributes and
706 * context for the instruction before doing so.
708 * @param insn - The instruction whose ID is to be determined.
709 * @return - 0 if the ModR/M could be read when needed or was not needed;
712 static int getID(struct InternalInstruction* insn) {
714 uint16_t instructionID;
716 dbgprintf(insn, "getID()");
718 attrMask = ATTR_NONE;
720 if (insn->mode == MODE_64BIT)
721 attrMask |= ATTR_64BIT;
724 attrMask |= ATTR_VEX;
726 if (insn->vexSize == 3) {
727 switch (ppFromVEX3of3(insn->vexPrefix[2])) {
729 attrMask |= ATTR_OPSIZE;
739 if (lFromVEX3of3(insn->vexPrefix[2]))
740 attrMask |= ATTR_VEXL;
742 else if (insn->vexSize == 2) {
743 switch (ppFromVEX2of2(insn->vexPrefix[1])) {
745 attrMask |= ATTR_OPSIZE;
755 if (lFromVEX2of2(insn->vexPrefix[1]))
756 attrMask |= ATTR_VEXL;
763 if (isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
764 attrMask |= ATTR_OPSIZE;
765 else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
767 else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
771 if (insn->rexPrefix & 0x08)
772 attrMask |= ATTR_REXW;
774 if (getIDWithAttrMask(&instructionID, insn, attrMask))
777 /* The following clauses compensate for limitations of the tables. */
779 if ((attrMask & ATTR_VEXL) && (attrMask & ATTR_REXW) &&
780 !(attrMask & ATTR_OPSIZE)) {
782 * Some VEX instructions ignore the L-bit, but use the W-bit. Normally L-bit
783 * has precedence since there are no L-bit with W-bit entries in the tables.
784 * So if the L-bit isn't significant we should use the W-bit instead.
785 * We only need to do this if the instruction doesn't specify OpSize since
786 * there is a VEX_L_W_OPSIZE table.
789 const struct InstructionSpecifier *spec;
790 uint16_t instructionIDWithWBit;
791 const struct InstructionSpecifier *specWithWBit;
793 spec = specifierForUID(instructionID);
795 if (getIDWithAttrMask(&instructionIDWithWBit,
797 (attrMask & (~ATTR_VEXL)) | ATTR_REXW)) {
798 insn->instructionID = instructionID;
803 specWithWBit = specifierForUID(instructionIDWithWBit);
805 if (instructionID != instructionIDWithWBit) {
806 insn->instructionID = instructionIDWithWBit;
807 insn->spec = specWithWBit;
809 insn->instructionID = instructionID;
815 if (insn->prefixPresent[0x66] && !(attrMask & ATTR_OPSIZE)) {
817 * The instruction tables make no distinction between instructions that
818 * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
819 * particular spot (i.e., many MMX operations). In general we're
820 * conservative, but in the specific case where OpSize is present but not
821 * in the right place we check if there's a 16-bit operation.
824 const struct InstructionSpecifier *spec;
825 uint16_t instructionIDWithOpsize;
826 const struct InstructionSpecifier *specWithOpsize;
828 spec = specifierForUID(instructionID);
830 if (getIDWithAttrMask(&instructionIDWithOpsize,
832 attrMask | ATTR_OPSIZE)) {
834 * ModRM required with OpSize but not present; give up and return version
838 insn->instructionID = instructionID;
843 specWithOpsize = specifierForUID(instructionIDWithOpsize);
845 if (is16BitEquvalent(spec->name, specWithOpsize->name)) {
846 insn->instructionID = instructionIDWithOpsize;
847 insn->spec = specWithOpsize;
849 insn->instructionID = instructionID;
855 if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
856 insn->rexPrefix & 0x01) {
858 * NOOP shouldn't decode as NOOP if REX.b is set. Instead
859 * it should decode as XCHG %r8, %eax.
862 const struct InstructionSpecifier *spec;
863 uint16_t instructionIDWithNewOpcode;
864 const struct InstructionSpecifier *specWithNewOpcode;
866 spec = specifierForUID(instructionID);
868 /* Borrow opcode from one of the other XCHGar opcodes */
871 if (getIDWithAttrMask(&instructionIDWithNewOpcode,
876 insn->instructionID = instructionID;
881 specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
886 insn->instructionID = instructionIDWithNewOpcode;
887 insn->spec = specWithNewOpcode;
892 insn->instructionID = instructionID;
893 insn->spec = specifierForUID(insn->instructionID);
899 * readSIB - Consumes the SIB byte to determine addressing information for an
902 * @param insn - The instruction whose SIB byte is to be read.
903 * @return - 0 if the SIB byte was successfully read; nonzero otherwise.
905 static int readSIB(struct InternalInstruction* insn) {
906 SIBIndex sibIndexBase = 0;
907 SIBBase sibBaseBase = 0;
910 dbgprintf(insn, "readSIB()");
912 if (insn->consumedSIB)
915 insn->consumedSIB = TRUE;
917 switch (insn->addressSize) {
919 dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
923 sibIndexBase = SIB_INDEX_EAX;
924 sibBaseBase = SIB_BASE_EAX;
927 sibIndexBase = SIB_INDEX_RAX;
928 sibBaseBase = SIB_BASE_RAX;
932 if (consumeByte(insn, &insn->sib))
935 index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
939 insn->sibIndex = SIB_INDEX_NONE;
942 insn->sibIndex = (SIBIndex)(sibIndexBase + index);
943 if (insn->sibIndex == SIB_INDEX_sib ||
944 insn->sibIndex == SIB_INDEX_sib64)
945 insn->sibIndex = SIB_INDEX_NONE;
949 switch (scaleFromSIB(insn->sib)) {
964 base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
968 switch (modFromModRM(insn->modRM)) {
970 insn->eaDisplacement = EA_DISP_32;
971 insn->sibBase = SIB_BASE_NONE;
974 insn->eaDisplacement = EA_DISP_8;
975 insn->sibBase = (insn->addressSize == 4 ?
976 SIB_BASE_EBP : SIB_BASE_RBP);
979 insn->eaDisplacement = EA_DISP_32;
980 insn->sibBase = (insn->addressSize == 4 ?
981 SIB_BASE_EBP : SIB_BASE_RBP);
984 debug("Cannot have Mod = 0b11 and a SIB byte");
989 insn->sibBase = (SIBBase)(sibBaseBase + base);
997 * readDisplacement - Consumes the displacement of an instruction.
999 * @param insn - The instruction whose displacement is to be read.
1000 * @return - 0 if the displacement byte was successfully read; nonzero
1003 static int readDisplacement(struct InternalInstruction* insn) {
1008 dbgprintf(insn, "readDisplacement()");
1010 if (insn->consumedDisplacement)
1013 insn->consumedDisplacement = TRUE;
1015 switch (insn->eaDisplacement) {
1017 insn->consumedDisplacement = FALSE;
1020 if (consumeInt8(insn, &d8))
1022 insn->displacement = d8;
1025 if (consumeInt16(insn, &d16))
1027 insn->displacement = d16;
1030 if (consumeInt32(insn, &d32))
1032 insn->displacement = d32;
1036 insn->consumedDisplacement = TRUE;
1041 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1042 * displacement) for an instruction and interprets it.
1044 * @param insn - The instruction whose addressing information is to be read.
1045 * @return - 0 if the information was successfully read; nonzero otherwise.
1047 static int readModRM(struct InternalInstruction* insn) {
1048 uint8_t mod, rm, reg;
1050 dbgprintf(insn, "readModRM()");
1052 if (insn->consumedModRM)
1055 if (consumeByte(insn, &insn->modRM))
1057 insn->consumedModRM = TRUE;
1059 mod = modFromModRM(insn->modRM);
1060 rm = rmFromModRM(insn->modRM);
1061 reg = regFromModRM(insn->modRM);
1064 * This goes by insn->registerSize to pick the correct register, which messes
1065 * up if we're using (say) XMM or 8-bit register operands. That gets fixed in
1068 switch (insn->registerSize) {
1070 insn->regBase = MODRM_REG_AX;
1071 insn->eaRegBase = EA_REG_AX;
1074 insn->regBase = MODRM_REG_EAX;
1075 insn->eaRegBase = EA_REG_EAX;
1078 insn->regBase = MODRM_REG_RAX;
1079 insn->eaRegBase = EA_REG_RAX;
1083 reg |= rFromREX(insn->rexPrefix) << 3;
1084 rm |= bFromREX(insn->rexPrefix) << 3;
1086 insn->reg = (Reg)(insn->regBase + reg);
1088 switch (insn->addressSize) {
1090 insn->eaBaseBase = EA_BASE_BX_SI;
1095 insn->eaBase = EA_BASE_NONE;
1096 insn->eaDisplacement = EA_DISP_16;
1097 if (readDisplacement(insn))
1100 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1101 insn->eaDisplacement = EA_DISP_NONE;
1105 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1106 insn->eaDisplacement = EA_DISP_8;
1107 if (readDisplacement(insn))
1111 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1112 insn->eaDisplacement = EA_DISP_16;
1113 if (readDisplacement(insn))
1117 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1118 if (readDisplacement(insn))
1125 insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1129 insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1132 case 0xc: /* in case REXW.b is set */
1133 insn->eaBase = (insn->addressSize == 4 ?
1134 EA_BASE_sib : EA_BASE_sib64);
1136 if (readDisplacement(insn))
1140 insn->eaBase = EA_BASE_NONE;
1141 insn->eaDisplacement = EA_DISP_32;
1142 if (readDisplacement(insn))
1146 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1152 insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1155 case 0xc: /* in case REXW.b is set */
1156 insn->eaBase = EA_BASE_sib;
1158 if (readDisplacement(insn))
1162 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1163 if (readDisplacement(insn))
1169 insn->eaDisplacement = EA_DISP_NONE;
1170 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1174 } /* switch (insn->addressSize) */
1179 #define GENERIC_FIXUP_FUNC(name, base, prefix) \
1180 static uint8_t name(struct InternalInstruction *insn, \
1187 debug("Unhandled register type"); \
1191 return base + index; \
1193 if (insn->rexPrefix && \
1194 index >= 4 && index <= 7) { \
1195 return prefix##_SPL + (index - 4); \
1197 return prefix##_AL + index; \
1200 return prefix##_AX + index; \
1202 return prefix##_EAX + index; \
1204 return prefix##_RAX + index; \
1206 return prefix##_YMM0 + index; \
1211 return prefix##_XMM0 + index; \
1217 return prefix##_MM0 + index; \
1218 case TYPE_SEGMENTREG: \
1221 return prefix##_ES + index; \
1222 case TYPE_DEBUGREG: \
1225 return prefix##_DR0 + index; \
1226 case TYPE_CONTROLREG: \
1229 return prefix##_CR0 + index; \
1234 * fixup*Value - Consults an operand type to determine the meaning of the
1235 * reg or R/M field. If the operand is an XMM operand, for example, an
1236 * operand would be XMM0 instead of AX, which readModRM() would otherwise
1237 * misinterpret it as.
1239 * @param insn - The instruction containing the operand.
1240 * @param type - The operand type.
1241 * @param index - The existing value of the field as reported by readModRM().
1242 * @param valid - The address of a uint8_t. The target is set to 1 if the
1243 * field is valid for the register class; 0 if not.
1244 * @return - The proper value.
1246 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG)
1247 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG)
1250 * fixupReg - Consults an operand specifier to determine which of the
1251 * fixup*Value functions to use in correcting readModRM()'ss interpretation.
1253 * @param insn - See fixup*Value().
1254 * @param op - The operand specifier.
1255 * @return - 0 if fixup was successful; -1 if the register returned was
1256 * invalid for its class.
1258 static int fixupReg(struct InternalInstruction *insn,
1259 const struct OperandSpecifier *op) {
1262 dbgprintf(insn, "fixupReg()");
1264 switch ((OperandEncoding)op->encoding) {
1266 debug("Expected a REG or R/M encoding in fixupReg");
1269 insn->vvvv = (Reg)fixupRegValue(insn,
1270 (OperandType)op->type,
1277 insn->reg = (Reg)fixupRegValue(insn,
1278 (OperandType)op->type,
1279 insn->reg - insn->regBase,
1285 if (insn->eaBase >= insn->eaRegBase) {
1286 insn->eaBase = (EABase)fixupRMValue(insn,
1287 (OperandType)op->type,
1288 insn->eaBase - insn->eaRegBase,
1300 * readOpcodeModifier - Reads an operand from the opcode field of an
1301 * instruction. Handles AddRegFrm instructions.
1303 * @param insn - The instruction whose opcode field is to be read.
1304 * @param inModRM - Indicates that the opcode field is to be read from the
1305 * ModR/M extension; useful for escape opcodes
1306 * @return - 0 on success; nonzero otherwise.
1308 static int readOpcodeModifier(struct InternalInstruction* insn) {
1309 dbgprintf(insn, "readOpcodeModifier()");
1311 if (insn->consumedOpcodeModifier)
1314 insn->consumedOpcodeModifier = TRUE;
1316 switch (insn->spec->modifierType) {
1318 debug("Unknown modifier type.");
1321 debug("No modifier but an operand expects one.");
1323 case MODIFIER_OPCODE:
1324 insn->opcodeModifier = insn->opcode - insn->spec->modifierBase;
1326 case MODIFIER_MODRM:
1327 insn->opcodeModifier = insn->modRM - insn->spec->modifierBase;
1333 * readOpcodeRegister - Reads an operand from the opcode field of an
1334 * instruction and interprets it appropriately given the operand width.
1335 * Handles AddRegFrm instructions.
1337 * @param insn - See readOpcodeModifier().
1338 * @param size - The width (in bytes) of the register being specified.
1339 * 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1341 * @return - 0 on success; nonzero otherwise.
1343 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1344 dbgprintf(insn, "readOpcodeRegister()");
1346 if (readOpcodeModifier(insn))
1350 size = insn->registerSize;
1354 insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1355 | insn->opcodeModifier));
1356 if (insn->rexPrefix &&
1357 insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1358 insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1359 insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1360 + (insn->opcodeRegister - MODRM_REG_AL - 4));
1365 insn->opcodeRegister = (Reg)(MODRM_REG_AX
1366 + ((bFromREX(insn->rexPrefix) << 3)
1367 | insn->opcodeModifier));
1370 insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1371 + ((bFromREX(insn->rexPrefix) << 3)
1372 | insn->opcodeModifier));
1375 insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1376 + ((bFromREX(insn->rexPrefix) << 3)
1377 | insn->opcodeModifier));
1385 * readImmediate - Consumes an immediate operand from an instruction, given the
1386 * desired operand size.
1388 * @param insn - The instruction whose operand is to be read.
1389 * @param size - The width (in bytes) of the operand.
1390 * @return - 0 if the immediate was successfully consumed; nonzero
1393 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1399 dbgprintf(insn, "readImmediate()");
1401 if (insn->numImmediatesConsumed == 2) {
1402 debug("Already consumed two immediates");
1407 size = insn->immediateSize;
1409 insn->immediateSize = size;
1413 if (consumeByte(insn, &imm8))
1415 insn->immediates[insn->numImmediatesConsumed] = imm8;
1418 if (consumeUInt16(insn, &imm16))
1420 insn->immediates[insn->numImmediatesConsumed] = imm16;
1423 if (consumeUInt32(insn, &imm32))
1425 insn->immediates[insn->numImmediatesConsumed] = imm32;
1428 if (consumeUInt64(insn, &imm64))
1430 insn->immediates[insn->numImmediatesConsumed] = imm64;
1434 insn->numImmediatesConsumed++;
1440 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1442 * @param insn - The instruction whose operand is to be read.
1443 * @return - 0 if the vvvv was successfully consumed; nonzero
1446 static int readVVVV(struct InternalInstruction* insn) {
1447 dbgprintf(insn, "readVVVV()");
1449 if (insn->vexSize == 3)
1450 insn->vvvv = vvvvFromVEX3of3(insn->vexPrefix[2]);
1451 else if (insn->vexSize == 2)
1452 insn->vvvv = vvvvFromVEX2of2(insn->vexPrefix[1]);
1456 if (insn->mode != MODE_64BIT)
1463 * readOperands - Consults the specifier for an instruction and consumes all
1464 * operands for that instruction, interpreting them as it goes.
1466 * @param insn - The instruction whose operands are to be read and interpreted.
1467 * @return - 0 if all operands could be read; nonzero otherwise.
1469 static int readOperands(struct InternalInstruction* insn) {
1471 int hasVVVV, needVVVV;
1474 dbgprintf(insn, "readOperands()");
1476 /* If non-zero vvvv specified, need to make sure one of the operands
1478 hasVVVV = !readVVVV(insn);
1479 needVVVV = hasVVVV && (insn->vvvv != 0);
1481 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
1482 switch (insn->spec->operands[index].encoding) {
1487 if (readModRM(insn))
1489 if (fixupReg(insn, &insn->spec->operands[index]))
1498 dbgprintf(insn, "We currently don't hande code-offset encodings");
1502 /* Saw a register immediate so don't read again and instead split the
1503 previous immediate. FIXME: This is a hack. */
1504 insn->immediates[insn->numImmediatesConsumed] =
1505 insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1506 ++insn->numImmediatesConsumed;
1509 if (readImmediate(insn, 1))
1511 if (insn->spec->operands[index].type == TYPE_IMM3 &&
1512 insn->immediates[insn->numImmediatesConsumed - 1] > 7)
1514 if (insn->spec->operands[index].type == TYPE_XMM128 ||
1515 insn->spec->operands[index].type == TYPE_XMM256)
1519 if (readImmediate(insn, 2))
1523 if (readImmediate(insn, 4))
1527 if (readImmediate(insn, 8))
1531 if (readImmediate(insn, insn->immediateSize))
1535 if (readImmediate(insn, insn->addressSize))
1539 if (readOpcodeRegister(insn, 1))
1543 if (readOpcodeRegister(insn, 2))
1547 if (readOpcodeRegister(insn, 4))
1551 if (readOpcodeRegister(insn, 8))
1555 if (readOpcodeRegister(insn, 0))
1559 if (readOpcodeModifier(insn))
1563 needVVVV = 0; /* Mark that we have found a VVVV operand. */
1566 if (fixupReg(insn, &insn->spec->operands[index]))
1572 dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1577 /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1578 if (needVVVV) return -1;
1584 * decodeInstruction - Reads and interprets a full instruction provided by the
1587 * @param insn - A pointer to the instruction to be populated. Must be
1589 * @param reader - The function to be used to read the instruction's bytes.
1590 * @param readerArg - A generic argument to be passed to the reader to store
1591 * any internal state.
1592 * @param logger - If non-NULL, the function to be used to write log messages
1594 * @param loggerArg - A generic argument to be passed to the logger to store
1595 * any internal state.
1596 * @param startLoc - The address (in the reader's address space) of the first
1597 * byte in the instruction.
1598 * @param mode - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1599 * decode the instruction in.
1600 * @return - 0 if the instruction's memory could be read; nonzero if
1603 int decodeInstruction(struct InternalInstruction* insn,
1604 byteReader_t reader,
1609 DisassemblerMode mode) {
1610 memset(insn, 0, sizeof(struct InternalInstruction));
1612 insn->reader = reader;
1613 insn->readerArg = readerArg;
1614 insn->dlog = logger;
1615 insn->dlogArg = loggerArg;
1616 insn->startLocation = startLoc;
1617 insn->readerCursor = startLoc;
1619 insn->numImmediatesConsumed = 0;
1621 if (readPrefixes(insn) ||
1624 insn->instructionID == 0 ||
1628 insn->length = insn->readerCursor - insn->startLocation;
1630 dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1631 startLoc, insn->readerCursor, insn->length);
1633 if (insn->length > 15)
1634 dbgprintf(insn, "Instruction exceeds 15-byte limit");