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 modRMTable[dec->instructionIDs];
136 if (modFromModRM(modRM) == 0x3)
137 return modRMTable[dec->instructionIDs+1];
138 return modRMTable[dec->instructionIDs];
140 return modRMTable[dec->instructionIDs+modRM];
145 * specifierForUID - Given a UID, returns the name and operand specification for
148 * @param uid - The unique ID for the instruction. This should be returned by
149 * decode(); specifierForUID will not check bounds.
150 * @return - A pointer to the specification for that instruction.
152 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
153 return &INSTRUCTIONS_SYM[uid];
157 * consumeByte - Uses the reader function provided by the user to consume one
158 * byte from the instruction's memory and advance the cursor.
160 * @param insn - The instruction with the reader function to use. The cursor
161 * for this instruction is advanced.
162 * @param byte - A pointer to a pre-allocated memory buffer to be populated
163 * with the data read.
164 * @return - 0 if the read was successful; nonzero otherwise.
166 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
167 int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
170 ++(insn->readerCursor);
176 * lookAtByte - Like consumeByte, but does not advance the cursor.
178 * @param insn - See consumeByte().
179 * @param byte - See consumeByte().
180 * @return - See consumeByte().
182 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
183 return insn->reader(insn->readerArg, byte, insn->readerCursor);
186 static void unconsumeByte(struct InternalInstruction* insn) {
187 insn->readerCursor--;
190 #define CONSUME_FUNC(name, type) \
191 static int name(struct InternalInstruction* insn, type* ptr) { \
194 for (offset = 0; offset < sizeof(type); ++offset) { \
196 int ret = insn->reader(insn->readerArg, \
198 insn->readerCursor + offset); \
201 combined = combined | ((type)byte << ((type)offset * 8)); \
204 insn->readerCursor += sizeof(type); \
209 * consume* - Use the reader function provided by the user to consume data
210 * values of various sizes from the instruction's memory and advance the
211 * cursor appropriately. These readers perform endian conversion.
213 * @param insn - See consumeByte().
214 * @param ptr - A pointer to a pre-allocated memory of appropriate size to
215 * be populated with the data read.
216 * @return - See consumeByte().
218 CONSUME_FUNC(consumeInt8, int8_t)
219 CONSUME_FUNC(consumeInt16, int16_t)
220 CONSUME_FUNC(consumeInt32, int32_t)
221 CONSUME_FUNC(consumeUInt16, uint16_t)
222 CONSUME_FUNC(consumeUInt32, uint32_t)
223 CONSUME_FUNC(consumeUInt64, uint64_t)
226 * dbgprintf - Uses the logging function provided by the user to log a single
227 * message, typically without a carriage-return.
229 * @param insn - The instruction containing the logging function.
230 * @param format - See printf().
231 * @param ... - See printf().
233 static void dbgprintf(struct InternalInstruction* insn,
242 va_start(ap, format);
243 (void)vsnprintf(buffer, sizeof(buffer), format, ap);
246 insn->dlog(insn->dlogArg, buffer);
252 * setPrefixPresent - Marks that a particular prefix is present at a particular
255 * @param insn - The instruction to be marked as having the prefix.
256 * @param prefix - The prefix that is present.
257 * @param location - The location where the prefix is located (in the address
258 * space of the instruction's reader).
260 static void setPrefixPresent(struct InternalInstruction* insn,
264 insn->prefixPresent[prefix] = 1;
265 insn->prefixLocations[prefix] = location;
269 * isPrefixAtLocation - Queries an instruction to determine whether a prefix is
270 * present at a given location.
272 * @param insn - The instruction to be queried.
273 * @param prefix - The prefix.
274 * @param location - The location to query.
275 * @return - Whether the prefix is at that location.
277 static BOOL isPrefixAtLocation(struct InternalInstruction* insn,
281 if (insn->prefixPresent[prefix] == 1 &&
282 insn->prefixLocations[prefix] == location)
289 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
290 * instruction as having them. Also sets the instruction's default operand,
291 * address, and other relevant data sizes to report operands correctly.
293 * @param insn - The instruction whose prefixes are to be read.
294 * @return - 0 if the instruction could be read until the end of the prefix
295 * bytes, and no prefixes conflicted; nonzero otherwise.
297 static int readPrefixes(struct InternalInstruction* insn) {
298 BOOL isPrefix = TRUE;
299 BOOL prefixGroups[4] = { FALSE };
300 uint64_t prefixLocation;
303 BOOL hasAdSize = FALSE;
304 BOOL hasOpSize = FALSE;
306 dbgprintf(insn, "readPrefixes()");
309 prefixLocation = insn->readerCursor;
311 if (consumeByte(insn, &byte))
315 case 0xf0: /* LOCK */
316 case 0xf2: /* REPNE/REPNZ */
317 case 0xf3: /* REP or REPE/REPZ */
319 dbgprintf(insn, "Redundant Group 1 prefix");
320 prefixGroups[0] = TRUE;
321 setPrefixPresent(insn, byte, prefixLocation);
323 case 0x2e: /* CS segment override -OR- Branch not taken */
324 case 0x36: /* SS segment override -OR- Branch taken */
325 case 0x3e: /* DS segment override */
326 case 0x26: /* ES segment override */
327 case 0x64: /* FS segment override */
328 case 0x65: /* GS segment override */
331 insn->segmentOverride = SEG_OVERRIDE_CS;
334 insn->segmentOverride = SEG_OVERRIDE_SS;
337 insn->segmentOverride = SEG_OVERRIDE_DS;
340 insn->segmentOverride = SEG_OVERRIDE_ES;
343 insn->segmentOverride = SEG_OVERRIDE_FS;
346 insn->segmentOverride = SEG_OVERRIDE_GS;
349 debug("Unhandled override");
353 dbgprintf(insn, "Redundant Group 2 prefix");
354 prefixGroups[1] = TRUE;
355 setPrefixPresent(insn, byte, prefixLocation);
357 case 0x66: /* Operand-size override */
359 dbgprintf(insn, "Redundant Group 3 prefix");
360 prefixGroups[2] = TRUE;
362 setPrefixPresent(insn, byte, prefixLocation);
364 case 0x67: /* Address-size override */
366 dbgprintf(insn, "Redundant Group 4 prefix");
367 prefixGroups[3] = TRUE;
369 setPrefixPresent(insn, byte, prefixLocation);
371 default: /* Not a prefix byte */
377 dbgprintf(insn, "Found prefix 0x%hhx", byte);
385 if (lookAtByte(insn, &byte1)) {
386 dbgprintf(insn, "Couldn't read second byte of VEX");
390 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
392 insn->necessaryPrefixLocation = insn->readerCursor - 1;
396 insn->necessaryPrefixLocation = insn->readerCursor - 1;
399 if (insn->vexSize == 3) {
400 insn->vexPrefix[0] = byte;
401 consumeByte(insn, &insn->vexPrefix[1]);
402 consumeByte(insn, &insn->vexPrefix[2]);
404 /* We simulate the REX prefix for simplicity's sake */
406 if (insn->mode == MODE_64BIT) {
407 insn->rexPrefix = 0x40
408 | (wFromVEX3of3(insn->vexPrefix[2]) << 3)
409 | (rFromVEX2of3(insn->vexPrefix[1]) << 2)
410 | (xFromVEX2of3(insn->vexPrefix[1]) << 1)
411 | (bFromVEX2of3(insn->vexPrefix[1]) << 0);
414 switch (ppFromVEX3of3(insn->vexPrefix[2]))
423 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1], insn->vexPrefix[2]);
426 else if (byte == 0xc5) {
429 if (lookAtByte(insn, &byte1)) {
430 dbgprintf(insn, "Couldn't read second byte of VEX");
434 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
441 if (insn->vexSize == 2) {
442 insn->vexPrefix[0] = byte;
443 consumeByte(insn, &insn->vexPrefix[1]);
445 if (insn->mode == MODE_64BIT) {
446 insn->rexPrefix = 0x40
447 | (rFromVEX2of2(insn->vexPrefix[1]) << 2);
450 switch (ppFromVEX2of2(insn->vexPrefix[1]))
459 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1]);
463 if (insn->mode == MODE_64BIT) {
464 if ((byte & 0xf0) == 0x40) {
467 if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
468 dbgprintf(insn, "Redundant REX prefix");
472 insn->rexPrefix = byte;
473 insn->necessaryPrefixLocation = insn->readerCursor - 2;
475 dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
478 insn->necessaryPrefixLocation = insn->readerCursor - 1;
482 insn->necessaryPrefixLocation = insn->readerCursor - 1;
486 if (insn->mode == MODE_16BIT) {
487 insn->registerSize = (hasOpSize ? 4 : 2);
488 insn->addressSize = (hasAdSize ? 4 : 2);
489 insn->displacementSize = (hasAdSize ? 4 : 2);
490 insn->immediateSize = (hasOpSize ? 4 : 2);
491 } else if (insn->mode == MODE_32BIT) {
492 insn->registerSize = (hasOpSize ? 2 : 4);
493 insn->addressSize = (hasAdSize ? 2 : 4);
494 insn->displacementSize = (hasAdSize ? 2 : 4);
495 insn->immediateSize = (hasOpSize ? 2 : 4);
496 } else if (insn->mode == MODE_64BIT) {
497 if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
498 insn->registerSize = 8;
499 insn->addressSize = (hasAdSize ? 4 : 8);
500 insn->displacementSize = 4;
501 insn->immediateSize = 4;
502 } else if (insn->rexPrefix) {
503 insn->registerSize = (hasOpSize ? 2 : 4);
504 insn->addressSize = (hasAdSize ? 4 : 8);
505 insn->displacementSize = (hasOpSize ? 2 : 4);
506 insn->immediateSize = (hasOpSize ? 2 : 4);
508 insn->registerSize = (hasOpSize ? 2 : 4);
509 insn->addressSize = (hasAdSize ? 4 : 8);
510 insn->displacementSize = (hasOpSize ? 2 : 4);
511 insn->immediateSize = (hasOpSize ? 2 : 4);
519 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
520 * extended or escape opcodes).
522 * @param insn - The instruction whose opcode is to be read.
523 * @return - 0 if the opcode could be read successfully; nonzero otherwise.
525 static int readOpcode(struct InternalInstruction* insn) {
526 /* Determine the length of the primary opcode */
530 dbgprintf(insn, "readOpcode()");
532 insn->opcodeType = ONEBYTE;
534 if (insn->vexSize == 3)
536 switch (mmmmmFromVEX2of3(insn->vexPrefix[1]))
539 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)", mmmmmFromVEX2of3(insn->vexPrefix[1]));
544 insn->twoByteEscape = 0x0f;
545 insn->opcodeType = TWOBYTE;
546 return consumeByte(insn, &insn->opcode);
548 insn->twoByteEscape = 0x0f;
549 insn->threeByteEscape = 0x38;
550 insn->opcodeType = THREEBYTE_38;
551 return consumeByte(insn, &insn->opcode);
553 insn->twoByteEscape = 0x0f;
554 insn->threeByteEscape = 0x3a;
555 insn->opcodeType = THREEBYTE_3A;
556 return consumeByte(insn, &insn->opcode);
559 else if (insn->vexSize == 2)
561 insn->twoByteEscape = 0x0f;
562 insn->opcodeType = TWOBYTE;
563 return consumeByte(insn, &insn->opcode);
566 if (consumeByte(insn, ¤t))
569 if (current == 0x0f) {
570 dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
572 insn->twoByteEscape = current;
574 if (consumeByte(insn, ¤t))
577 if (current == 0x38) {
578 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
580 insn->threeByteEscape = current;
582 if (consumeByte(insn, ¤t))
585 insn->opcodeType = THREEBYTE_38;
586 } else if (current == 0x3a) {
587 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
589 insn->threeByteEscape = current;
591 if (consumeByte(insn, ¤t))
594 insn->opcodeType = THREEBYTE_3A;
595 } else if (current == 0xa6) {
596 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
598 insn->threeByteEscape = current;
600 if (consumeByte(insn, ¤t))
603 insn->opcodeType = THREEBYTE_A6;
604 } else if (current == 0xa7) {
605 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
607 insn->threeByteEscape = current;
609 if (consumeByte(insn, ¤t))
612 insn->opcodeType = THREEBYTE_A7;
614 dbgprintf(insn, "Didn't find a three-byte escape prefix");
616 insn->opcodeType = TWOBYTE;
621 * At this point we have consumed the full opcode.
622 * Anything we consume from here on must be unconsumed.
625 insn->opcode = current;
630 static int readModRM(struct InternalInstruction* insn);
633 * getIDWithAttrMask - Determines the ID of an instruction, consuming
634 * the ModR/M byte as appropriate for extended and escape opcodes,
635 * and using a supplied attribute mask.
637 * @param instructionID - A pointer whose target is filled in with the ID of the
639 * @param insn - The instruction whose ID is to be determined.
640 * @param attrMask - The attribute mask to search.
641 * @return - 0 if the ModR/M could be read when needed or was not
642 * needed; nonzero otherwise.
644 static int getIDWithAttrMask(uint16_t* instructionID,
645 struct InternalInstruction* insn,
647 BOOL hasModRMExtension;
649 uint8_t instructionClass;
651 instructionClass = contextForAttrs(attrMask);
653 hasModRMExtension = modRMRequired(insn->opcodeType,
657 if (hasModRMExtension) {
661 *instructionID = decode(insn->opcodeType,
666 *instructionID = decode(insn->opcodeType,
676 * is16BitEquivalent - Determines whether two instruction names refer to
677 * equivalent instructions but one is 16-bit whereas the other is not.
679 * @param orig - The instruction that is not 16-bit
680 * @param equiv - The instruction that is 16-bit
682 static BOOL is16BitEquvalent(const char* orig, const char* equiv) {
686 if (orig[i] == '\0' && equiv[i] == '\0')
688 if (orig[i] == '\0' || equiv[i] == '\0')
690 if (orig[i] != equiv[i]) {
691 if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
693 if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
695 if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
703 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
704 * appropriate for extended and escape opcodes. Determines the attributes and
705 * context for the instruction before doing so.
707 * @param insn - The instruction whose ID is to be determined.
708 * @return - 0 if the ModR/M could be read when needed or was not needed;
711 static int getID(struct InternalInstruction* insn) {
713 uint16_t instructionID;
715 dbgprintf(insn, "getID()");
717 attrMask = ATTR_NONE;
719 if (insn->mode == MODE_64BIT)
720 attrMask |= ATTR_64BIT;
723 attrMask |= ATTR_VEX;
725 if (insn->vexSize == 3) {
726 switch (ppFromVEX3of3(insn->vexPrefix[2])) {
728 attrMask |= ATTR_OPSIZE;
738 if (lFromVEX3of3(insn->vexPrefix[2]))
739 attrMask |= ATTR_VEXL;
741 else if (insn->vexSize == 2) {
742 switch (ppFromVEX2of2(insn->vexPrefix[1])) {
744 attrMask |= ATTR_OPSIZE;
754 if (lFromVEX2of2(insn->vexPrefix[1]))
755 attrMask |= ATTR_VEXL;
762 if (isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
763 attrMask |= ATTR_OPSIZE;
764 else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
766 else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
770 if (insn->rexPrefix & 0x08)
771 attrMask |= ATTR_REXW;
773 if (getIDWithAttrMask(&instructionID, insn, attrMask))
776 /* The following clauses compensate for limitations of the tables. */
778 if ((attrMask & ATTR_VEXL) && (attrMask & ATTR_REXW) &&
779 !(attrMask & ATTR_OPSIZE)) {
781 * Some VEX instructions ignore the L-bit, but use the W-bit. Normally L-bit
782 * has precedence since there are no L-bit with W-bit entries in the tables.
783 * So if the L-bit isn't significant we should use the W-bit instead.
784 * We only need to do this if the instruction doesn't specify OpSize since
785 * there is a VEX_L_W_OPSIZE table.
788 const struct InstructionSpecifier *spec;
789 uint16_t instructionIDWithWBit;
790 const struct InstructionSpecifier *specWithWBit;
792 spec = specifierForUID(instructionID);
794 if (getIDWithAttrMask(&instructionIDWithWBit,
796 (attrMask & (~ATTR_VEXL)) | ATTR_REXW)) {
797 insn->instructionID = instructionID;
802 specWithWBit = specifierForUID(instructionIDWithWBit);
804 if (instructionID != instructionIDWithWBit) {
805 insn->instructionID = instructionIDWithWBit;
806 insn->spec = specWithWBit;
808 insn->instructionID = instructionID;
814 if (insn->prefixPresent[0x66] && !(attrMask & ATTR_OPSIZE)) {
816 * The instruction tables make no distinction between instructions that
817 * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
818 * particular spot (i.e., many MMX operations). In general we're
819 * conservative, but in the specific case where OpSize is present but not
820 * in the right place we check if there's a 16-bit operation.
823 const struct InstructionSpecifier *spec;
824 uint16_t instructionIDWithOpsize;
825 const struct InstructionSpecifier *specWithOpsize;
827 spec = specifierForUID(instructionID);
829 if (getIDWithAttrMask(&instructionIDWithOpsize,
831 attrMask | ATTR_OPSIZE)) {
833 * ModRM required with OpSize but not present; give up and return version
837 insn->instructionID = instructionID;
842 specWithOpsize = specifierForUID(instructionIDWithOpsize);
844 if (is16BitEquvalent(spec->name, specWithOpsize->name)) {
845 insn->instructionID = instructionIDWithOpsize;
846 insn->spec = specWithOpsize;
848 insn->instructionID = instructionID;
854 if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
855 insn->rexPrefix & 0x01) {
857 * NOOP shouldn't decode as NOOP if REX.b is set. Instead
858 * it should decode as XCHG %r8, %eax.
861 const struct InstructionSpecifier *spec;
862 uint16_t instructionIDWithNewOpcode;
863 const struct InstructionSpecifier *specWithNewOpcode;
865 spec = specifierForUID(instructionID);
867 /* Borrow opcode from one of the other XCHGar opcodes */
870 if (getIDWithAttrMask(&instructionIDWithNewOpcode,
875 insn->instructionID = instructionID;
880 specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
885 insn->instructionID = instructionIDWithNewOpcode;
886 insn->spec = specWithNewOpcode;
891 insn->instructionID = instructionID;
892 insn->spec = specifierForUID(insn->instructionID);
898 * readSIB - Consumes the SIB byte to determine addressing information for an
901 * @param insn - The instruction whose SIB byte is to be read.
902 * @return - 0 if the SIB byte was successfully read; nonzero otherwise.
904 static int readSIB(struct InternalInstruction* insn) {
905 SIBIndex sibIndexBase = 0;
906 SIBBase sibBaseBase = 0;
909 dbgprintf(insn, "readSIB()");
911 if (insn->consumedSIB)
914 insn->consumedSIB = TRUE;
916 switch (insn->addressSize) {
918 dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
922 sibIndexBase = SIB_INDEX_EAX;
923 sibBaseBase = SIB_BASE_EAX;
926 sibIndexBase = SIB_INDEX_RAX;
927 sibBaseBase = SIB_BASE_RAX;
931 if (consumeByte(insn, &insn->sib))
934 index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
938 insn->sibIndex = SIB_INDEX_NONE;
941 insn->sibIndex = (SIBIndex)(sibIndexBase + index);
942 if (insn->sibIndex == SIB_INDEX_sib ||
943 insn->sibIndex == SIB_INDEX_sib64)
944 insn->sibIndex = SIB_INDEX_NONE;
948 switch (scaleFromSIB(insn->sib)) {
963 base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
967 switch (modFromModRM(insn->modRM)) {
969 insn->eaDisplacement = EA_DISP_32;
970 insn->sibBase = SIB_BASE_NONE;
973 insn->eaDisplacement = EA_DISP_8;
974 insn->sibBase = (insn->addressSize == 4 ?
975 SIB_BASE_EBP : SIB_BASE_RBP);
978 insn->eaDisplacement = EA_DISP_32;
979 insn->sibBase = (insn->addressSize == 4 ?
980 SIB_BASE_EBP : SIB_BASE_RBP);
983 debug("Cannot have Mod = 0b11 and a SIB byte");
988 insn->sibBase = (SIBBase)(sibBaseBase + base);
996 * readDisplacement - Consumes the displacement of an instruction.
998 * @param insn - The instruction whose displacement is to be read.
999 * @return - 0 if the displacement byte was successfully read; nonzero
1002 static int readDisplacement(struct InternalInstruction* insn) {
1007 dbgprintf(insn, "readDisplacement()");
1009 if (insn->consumedDisplacement)
1012 insn->consumedDisplacement = TRUE;
1014 switch (insn->eaDisplacement) {
1016 insn->consumedDisplacement = FALSE;
1019 if (consumeInt8(insn, &d8))
1021 insn->displacement = d8;
1024 if (consumeInt16(insn, &d16))
1026 insn->displacement = d16;
1029 if (consumeInt32(insn, &d32))
1031 insn->displacement = d32;
1035 insn->consumedDisplacement = TRUE;
1040 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1041 * displacement) for an instruction and interprets it.
1043 * @param insn - The instruction whose addressing information is to be read.
1044 * @return - 0 if the information was successfully read; nonzero otherwise.
1046 static int readModRM(struct InternalInstruction* insn) {
1047 uint8_t mod, rm, reg;
1049 dbgprintf(insn, "readModRM()");
1051 if (insn->consumedModRM)
1054 if (consumeByte(insn, &insn->modRM))
1056 insn->consumedModRM = TRUE;
1058 mod = modFromModRM(insn->modRM);
1059 rm = rmFromModRM(insn->modRM);
1060 reg = regFromModRM(insn->modRM);
1063 * This goes by insn->registerSize to pick the correct register, which messes
1064 * up if we're using (say) XMM or 8-bit register operands. That gets fixed in
1067 switch (insn->registerSize) {
1069 insn->regBase = MODRM_REG_AX;
1070 insn->eaRegBase = EA_REG_AX;
1073 insn->regBase = MODRM_REG_EAX;
1074 insn->eaRegBase = EA_REG_EAX;
1077 insn->regBase = MODRM_REG_RAX;
1078 insn->eaRegBase = EA_REG_RAX;
1082 reg |= rFromREX(insn->rexPrefix) << 3;
1083 rm |= bFromREX(insn->rexPrefix) << 3;
1085 insn->reg = (Reg)(insn->regBase + reg);
1087 switch (insn->addressSize) {
1089 insn->eaBaseBase = EA_BASE_BX_SI;
1094 insn->eaBase = EA_BASE_NONE;
1095 insn->eaDisplacement = EA_DISP_16;
1096 if (readDisplacement(insn))
1099 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1100 insn->eaDisplacement = EA_DISP_NONE;
1104 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1105 insn->eaDisplacement = EA_DISP_8;
1106 if (readDisplacement(insn))
1110 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1111 insn->eaDisplacement = EA_DISP_16;
1112 if (readDisplacement(insn))
1116 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1117 if (readDisplacement(insn))
1124 insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1128 insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1131 case 0xc: /* in case REXW.b is set */
1132 insn->eaBase = (insn->addressSize == 4 ?
1133 EA_BASE_sib : EA_BASE_sib64);
1135 if (readDisplacement(insn))
1139 insn->eaBase = EA_BASE_NONE;
1140 insn->eaDisplacement = EA_DISP_32;
1141 if (readDisplacement(insn))
1145 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1151 insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1154 case 0xc: /* in case REXW.b is set */
1155 insn->eaBase = EA_BASE_sib;
1157 if (readDisplacement(insn))
1161 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1162 if (readDisplacement(insn))
1168 insn->eaDisplacement = EA_DISP_NONE;
1169 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1173 } /* switch (insn->addressSize) */
1178 #define GENERIC_FIXUP_FUNC(name, base, prefix) \
1179 static uint8_t name(struct InternalInstruction *insn, \
1186 debug("Unhandled register type"); \
1190 return base + index; \
1192 if (insn->rexPrefix && \
1193 index >= 4 && index <= 7) { \
1194 return prefix##_SPL + (index - 4); \
1196 return prefix##_AL + index; \
1199 return prefix##_AX + index; \
1201 return prefix##_EAX + index; \
1203 return prefix##_RAX + index; \
1205 return prefix##_YMM0 + index; \
1210 return prefix##_XMM0 + index; \
1216 return prefix##_MM0 + index; \
1217 case TYPE_SEGMENTREG: \
1220 return prefix##_ES + index; \
1221 case TYPE_DEBUGREG: \
1224 return prefix##_DR0 + index; \
1225 case TYPE_CONTROLREG: \
1228 return prefix##_CR0 + index; \
1233 * fixup*Value - Consults an operand type to determine the meaning of the
1234 * reg or R/M field. If the operand is an XMM operand, for example, an
1235 * operand would be XMM0 instead of AX, which readModRM() would otherwise
1236 * misinterpret it as.
1238 * @param insn - The instruction containing the operand.
1239 * @param type - The operand type.
1240 * @param index - The existing value of the field as reported by readModRM().
1241 * @param valid - The address of a uint8_t. The target is set to 1 if the
1242 * field is valid for the register class; 0 if not.
1243 * @return - The proper value.
1245 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG)
1246 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG)
1249 * fixupReg - Consults an operand specifier to determine which of the
1250 * fixup*Value functions to use in correcting readModRM()'ss interpretation.
1252 * @param insn - See fixup*Value().
1253 * @param op - The operand specifier.
1254 * @return - 0 if fixup was successful; -1 if the register returned was
1255 * invalid for its class.
1257 static int fixupReg(struct InternalInstruction *insn,
1258 const struct OperandSpecifier *op) {
1261 dbgprintf(insn, "fixupReg()");
1263 switch ((OperandEncoding)op->encoding) {
1265 debug("Expected a REG or R/M encoding in fixupReg");
1268 insn->vvvv = (Reg)fixupRegValue(insn,
1269 (OperandType)op->type,
1276 insn->reg = (Reg)fixupRegValue(insn,
1277 (OperandType)op->type,
1278 insn->reg - insn->regBase,
1284 if (insn->eaBase >= insn->eaRegBase) {
1285 insn->eaBase = (EABase)fixupRMValue(insn,
1286 (OperandType)op->type,
1287 insn->eaBase - insn->eaRegBase,
1299 * readOpcodeModifier - Reads an operand from the opcode field of an
1300 * instruction. Handles AddRegFrm instructions.
1302 * @param insn - The instruction whose opcode field is to be read.
1303 * @param inModRM - Indicates that the opcode field is to be read from the
1304 * ModR/M extension; useful for escape opcodes
1305 * @return - 0 on success; nonzero otherwise.
1307 static int readOpcodeModifier(struct InternalInstruction* insn) {
1308 dbgprintf(insn, "readOpcodeModifier()");
1310 if (insn->consumedOpcodeModifier)
1313 insn->consumedOpcodeModifier = TRUE;
1315 switch (insn->spec->modifierType) {
1317 debug("Unknown modifier type.");
1320 debug("No modifier but an operand expects one.");
1322 case MODIFIER_OPCODE:
1323 insn->opcodeModifier = insn->opcode - insn->spec->modifierBase;
1325 case MODIFIER_MODRM:
1326 insn->opcodeModifier = insn->modRM - insn->spec->modifierBase;
1332 * readOpcodeRegister - Reads an operand from the opcode field of an
1333 * instruction and interprets it appropriately given the operand width.
1334 * Handles AddRegFrm instructions.
1336 * @param insn - See readOpcodeModifier().
1337 * @param size - The width (in bytes) of the register being specified.
1338 * 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1340 * @return - 0 on success; nonzero otherwise.
1342 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1343 dbgprintf(insn, "readOpcodeRegister()");
1345 if (readOpcodeModifier(insn))
1349 size = insn->registerSize;
1353 insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1354 | insn->opcodeModifier));
1355 if (insn->rexPrefix &&
1356 insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1357 insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1358 insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1359 + (insn->opcodeRegister - MODRM_REG_AL - 4));
1364 insn->opcodeRegister = (Reg)(MODRM_REG_AX
1365 + ((bFromREX(insn->rexPrefix) << 3)
1366 | insn->opcodeModifier));
1369 insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1370 + ((bFromREX(insn->rexPrefix) << 3)
1371 | insn->opcodeModifier));
1374 insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1375 + ((bFromREX(insn->rexPrefix) << 3)
1376 | insn->opcodeModifier));
1384 * readImmediate - Consumes an immediate operand from an instruction, given the
1385 * desired operand size.
1387 * @param insn - The instruction whose operand is to be read.
1388 * @param size - The width (in bytes) of the operand.
1389 * @return - 0 if the immediate was successfully consumed; nonzero
1392 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1398 dbgprintf(insn, "readImmediate()");
1400 if (insn->numImmediatesConsumed == 2) {
1401 debug("Already consumed two immediates");
1406 size = insn->immediateSize;
1408 insn->immediateSize = size;
1412 if (consumeByte(insn, &imm8))
1414 insn->immediates[insn->numImmediatesConsumed] = imm8;
1417 if (consumeUInt16(insn, &imm16))
1419 insn->immediates[insn->numImmediatesConsumed] = imm16;
1422 if (consumeUInt32(insn, &imm32))
1424 insn->immediates[insn->numImmediatesConsumed] = imm32;
1427 if (consumeUInt64(insn, &imm64))
1429 insn->immediates[insn->numImmediatesConsumed] = imm64;
1433 insn->numImmediatesConsumed++;
1439 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1441 * @param insn - The instruction whose operand is to be read.
1442 * @return - 0 if the vvvv was successfully consumed; nonzero
1445 static int readVVVV(struct InternalInstruction* insn) {
1446 dbgprintf(insn, "readVVVV()");
1448 if (insn->vexSize == 3)
1449 insn->vvvv = vvvvFromVEX3of3(insn->vexPrefix[2]);
1450 else if (insn->vexSize == 2)
1451 insn->vvvv = vvvvFromVEX2of2(insn->vexPrefix[1]);
1455 if (insn->mode != MODE_64BIT)
1462 * readOperands - Consults the specifier for an instruction and consumes all
1463 * operands for that instruction, interpreting them as it goes.
1465 * @param insn - The instruction whose operands are to be read and interpreted.
1466 * @return - 0 if all operands could be read; nonzero otherwise.
1468 static int readOperands(struct InternalInstruction* insn) {
1470 int hasVVVV, needVVVV;
1473 dbgprintf(insn, "readOperands()");
1475 /* If non-zero vvvv specified, need to make sure one of the operands
1477 hasVVVV = !readVVVV(insn);
1478 needVVVV = hasVVVV && (insn->vvvv != 0);
1480 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
1481 switch (insn->spec->operands[index].encoding) {
1486 if (readModRM(insn))
1488 if (fixupReg(insn, &insn->spec->operands[index]))
1497 dbgprintf(insn, "We currently don't hande code-offset encodings");
1501 /* Saw a register immediate so don't read again and instead split the
1502 previous immediate. FIXME: This is a hack. */
1503 insn->immediates[insn->numImmediatesConsumed] =
1504 insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1505 ++insn->numImmediatesConsumed;
1508 if (readImmediate(insn, 1))
1510 if (insn->spec->operands[index].type == TYPE_IMM3 &&
1511 insn->immediates[insn->numImmediatesConsumed - 1] > 7)
1513 if (insn->spec->operands[index].type == TYPE_XMM128 ||
1514 insn->spec->operands[index].type == TYPE_XMM256)
1518 if (readImmediate(insn, 2))
1522 if (readImmediate(insn, 4))
1526 if (readImmediate(insn, 8))
1530 if (readImmediate(insn, insn->immediateSize))
1534 if (readImmediate(insn, insn->addressSize))
1538 if (readOpcodeRegister(insn, 1))
1542 if (readOpcodeRegister(insn, 2))
1546 if (readOpcodeRegister(insn, 4))
1550 if (readOpcodeRegister(insn, 8))
1554 if (readOpcodeRegister(insn, 0))
1558 if (readOpcodeModifier(insn))
1562 needVVVV = 0; /* Mark that we have found a VVVV operand. */
1565 if (fixupReg(insn, &insn->spec->operands[index]))
1571 dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1576 /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1577 if (needVVVV) return -1;
1583 * decodeInstruction - Reads and interprets a full instruction provided by the
1586 * @param insn - A pointer to the instruction to be populated. Must be
1588 * @param reader - The function to be used to read the instruction's bytes.
1589 * @param readerArg - A generic argument to be passed to the reader to store
1590 * any internal state.
1591 * @param logger - If non-NULL, the function to be used to write log messages
1593 * @param loggerArg - A generic argument to be passed to the logger to store
1594 * any internal state.
1595 * @param startLoc - The address (in the reader's address space) of the first
1596 * byte in the instruction.
1597 * @param mode - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1598 * decode the instruction in.
1599 * @return - 0 if the instruction's memory could be read; nonzero if
1602 int decodeInstruction(struct InternalInstruction* insn,
1603 byteReader_t reader,
1608 DisassemblerMode mode) {
1609 memset(insn, 0, sizeof(struct InternalInstruction));
1611 insn->reader = reader;
1612 insn->readerArg = readerArg;
1613 insn->dlog = logger;
1614 insn->dlogArg = loggerArg;
1615 insn->startLocation = startLoc;
1616 insn->readerCursor = startLoc;
1618 insn->numImmediatesConsumed = 0;
1620 if (readPrefixes(insn) ||
1623 insn->instructionID == 0 ||
1627 insn->length = insn->readerCursor - insn->startLocation;
1629 dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1630 startLoc, insn->readerCursor, insn->length);
1632 if (insn->length > 15)
1633 dbgprintf(insn, "Instruction exceeds 15-byte limit");