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;
91 * decode - Reads the appropriate instruction table to obtain the unique ID of
94 * @param type - See modRMRequired().
95 * @param insnContext - See modRMRequired().
96 * @param opcode - See modRMRequired().
97 * @param modRM - The ModR/M byte if required, or any value if not.
98 * @return - The UID of the instruction, or 0 on failure.
100 static InstrUID decode(OpcodeType type,
101 InstructionContext insnContext,
104 const struct ModRMDecision* dec = 0;
108 dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
111 dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
114 dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
117 dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
120 dec = &THREEBYTEA6_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
123 dec = &THREEBYTEA7_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
127 switch (dec->modrm_type) {
129 debug("Corrupt table! Unknown modrm_type");
132 return modRMTable[dec->instructionIDs];
134 if (modFromModRM(modRM) == 0x3)
135 return modRMTable[dec->instructionIDs+1];
136 return modRMTable[dec->instructionIDs];
138 if (modFromModRM(modRM) == 0x3)
139 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)+8];
140 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
142 return modRMTable[dec->instructionIDs+modRM];
147 * specifierForUID - Given a UID, returns the name and operand specification for
150 * @param uid - The unique ID for the instruction. This should be returned by
151 * decode(); specifierForUID will not check bounds.
152 * @return - A pointer to the specification for that instruction.
154 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
155 return &INSTRUCTIONS_SYM[uid];
159 * consumeByte - Uses the reader function provided by the user to consume one
160 * byte from the instruction's memory and advance the cursor.
162 * @param insn - The instruction with the reader function to use. The cursor
163 * for this instruction is advanced.
164 * @param byte - A pointer to a pre-allocated memory buffer to be populated
165 * with the data read.
166 * @return - 0 if the read was successful; nonzero otherwise.
168 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
169 int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
172 ++(insn->readerCursor);
178 * lookAtByte - Like consumeByte, but does not advance the cursor.
180 * @param insn - See consumeByte().
181 * @param byte - See consumeByte().
182 * @return - See consumeByte().
184 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
185 return insn->reader(insn->readerArg, byte, insn->readerCursor);
188 static void unconsumeByte(struct InternalInstruction* insn) {
189 insn->readerCursor--;
192 #define CONSUME_FUNC(name, type) \
193 static int name(struct InternalInstruction* insn, type* ptr) { \
196 for (offset = 0; offset < sizeof(type); ++offset) { \
198 int ret = insn->reader(insn->readerArg, \
200 insn->readerCursor + offset); \
203 combined = combined | ((type)byte << ((type)offset * 8)); \
206 insn->readerCursor += sizeof(type); \
211 * consume* - Use the reader function provided by the user to consume data
212 * values of various sizes from the instruction's memory and advance the
213 * cursor appropriately. These readers perform endian conversion.
215 * @param insn - See consumeByte().
216 * @param ptr - A pointer to a pre-allocated memory of appropriate size to
217 * be populated with the data read.
218 * @return - See consumeByte().
220 CONSUME_FUNC(consumeInt8, int8_t)
221 CONSUME_FUNC(consumeInt16, int16_t)
222 CONSUME_FUNC(consumeInt32, int32_t)
223 CONSUME_FUNC(consumeUInt16, uint16_t)
224 CONSUME_FUNC(consumeUInt32, uint32_t)
225 CONSUME_FUNC(consumeUInt64, uint64_t)
228 * dbgprintf - Uses the logging function provided by the user to log a single
229 * message, typically without a carriage-return.
231 * @param insn - The instruction containing the logging function.
232 * @param format - See printf().
233 * @param ... - See printf().
235 static void dbgprintf(struct InternalInstruction* insn,
244 va_start(ap, format);
245 (void)vsnprintf(buffer, sizeof(buffer), format, ap);
248 insn->dlog(insn->dlogArg, buffer);
254 * setPrefixPresent - Marks that a particular prefix is present at a particular
257 * @param insn - The instruction to be marked as having the prefix.
258 * @param prefix - The prefix that is present.
259 * @param location - The location where the prefix is located (in the address
260 * space of the instruction's reader).
262 static void setPrefixPresent(struct InternalInstruction* insn,
266 insn->prefixPresent[prefix] = 1;
267 insn->prefixLocations[prefix] = location;
271 * isPrefixAtLocation - Queries an instruction to determine whether a prefix is
272 * present at a given location.
274 * @param insn - The instruction to be queried.
275 * @param prefix - The prefix.
276 * @param location - The location to query.
277 * @return - Whether the prefix is at that location.
279 static BOOL isPrefixAtLocation(struct InternalInstruction* insn,
283 if (insn->prefixPresent[prefix] == 1 &&
284 insn->prefixLocations[prefix] == location)
291 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
292 * instruction as having them. Also sets the instruction's default operand,
293 * address, and other relevant data sizes to report operands correctly.
295 * @param insn - The instruction whose prefixes are to be read.
296 * @return - 0 if the instruction could be read until the end of the prefix
297 * bytes, and no prefixes conflicted; nonzero otherwise.
299 static int readPrefixes(struct InternalInstruction* insn) {
300 BOOL isPrefix = TRUE;
301 BOOL prefixGroups[4] = { FALSE };
302 uint64_t prefixLocation;
305 BOOL hasAdSize = FALSE;
306 BOOL hasOpSize = FALSE;
308 dbgprintf(insn, "readPrefixes()");
311 prefixLocation = insn->readerCursor;
313 if (consumeByte(insn, &byte))
316 // If the the first byte is a LOCK prefix break and let it be disassembled
317 // as a lock "instruction", by creating an <MCInst #xxxx LOCK_PREFIX>.
318 // FIXME there is currently no way to get the disassembler to print the
319 // lock prefix if it is not the first byte.
320 if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0)
324 case 0xf0: /* LOCK */
325 case 0xf2: /* REPNE/REPNZ */
326 case 0xf3: /* REP or REPE/REPZ */
328 dbgprintf(insn, "Redundant Group 1 prefix");
329 prefixGroups[0] = TRUE;
330 setPrefixPresent(insn, byte, prefixLocation);
332 case 0x2e: /* CS segment override -OR- Branch not taken */
333 case 0x36: /* SS segment override -OR- Branch taken */
334 case 0x3e: /* DS segment override */
335 case 0x26: /* ES segment override */
336 case 0x64: /* FS segment override */
337 case 0x65: /* GS segment override */
340 insn->segmentOverride = SEG_OVERRIDE_CS;
343 insn->segmentOverride = SEG_OVERRIDE_SS;
346 insn->segmentOverride = SEG_OVERRIDE_DS;
349 insn->segmentOverride = SEG_OVERRIDE_ES;
352 insn->segmentOverride = SEG_OVERRIDE_FS;
355 insn->segmentOverride = SEG_OVERRIDE_GS;
358 debug("Unhandled override");
362 dbgprintf(insn, "Redundant Group 2 prefix");
363 prefixGroups[1] = TRUE;
364 setPrefixPresent(insn, byte, prefixLocation);
366 case 0x66: /* Operand-size override */
368 dbgprintf(insn, "Redundant Group 3 prefix");
369 prefixGroups[2] = TRUE;
371 setPrefixPresent(insn, byte, prefixLocation);
373 case 0x67: /* Address-size override */
375 dbgprintf(insn, "Redundant Group 4 prefix");
376 prefixGroups[3] = TRUE;
378 setPrefixPresent(insn, byte, prefixLocation);
380 default: /* Not a prefix byte */
386 dbgprintf(insn, "Found prefix 0x%hhx", byte);
394 if (lookAtByte(insn, &byte1)) {
395 dbgprintf(insn, "Couldn't read second byte of VEX");
399 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
401 insn->necessaryPrefixLocation = insn->readerCursor - 1;
405 insn->necessaryPrefixLocation = insn->readerCursor - 1;
408 if (insn->vexSize == 3) {
409 insn->vexPrefix[0] = byte;
410 consumeByte(insn, &insn->vexPrefix[1]);
411 consumeByte(insn, &insn->vexPrefix[2]);
413 /* We simulate the REX prefix for simplicity's sake */
415 if (insn->mode == MODE_64BIT) {
416 insn->rexPrefix = 0x40
417 | (wFromVEX3of3(insn->vexPrefix[2]) << 3)
418 | (rFromVEX2of3(insn->vexPrefix[1]) << 2)
419 | (xFromVEX2of3(insn->vexPrefix[1]) << 1)
420 | (bFromVEX2of3(insn->vexPrefix[1]) << 0);
423 switch (ppFromVEX3of3(insn->vexPrefix[2]))
432 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1], insn->vexPrefix[2]);
435 else if (byte == 0xc5) {
438 if (lookAtByte(insn, &byte1)) {
439 dbgprintf(insn, "Couldn't read second byte of VEX");
443 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
450 if (insn->vexSize == 2) {
451 insn->vexPrefix[0] = byte;
452 consumeByte(insn, &insn->vexPrefix[1]);
454 if (insn->mode == MODE_64BIT) {
455 insn->rexPrefix = 0x40
456 | (rFromVEX2of2(insn->vexPrefix[1]) << 2);
459 switch (ppFromVEX2of2(insn->vexPrefix[1]))
468 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1]);
472 if (insn->mode == MODE_64BIT) {
473 if ((byte & 0xf0) == 0x40) {
476 if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
477 dbgprintf(insn, "Redundant REX prefix");
481 insn->rexPrefix = byte;
482 insn->necessaryPrefixLocation = insn->readerCursor - 2;
484 dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
487 insn->necessaryPrefixLocation = insn->readerCursor - 1;
491 insn->necessaryPrefixLocation = insn->readerCursor - 1;
495 if (insn->mode == MODE_16BIT) {
496 insn->registerSize = (hasOpSize ? 4 : 2);
497 insn->addressSize = (hasAdSize ? 4 : 2);
498 insn->displacementSize = (hasAdSize ? 4 : 2);
499 insn->immediateSize = (hasOpSize ? 4 : 2);
500 } else if (insn->mode == MODE_32BIT) {
501 insn->registerSize = (hasOpSize ? 2 : 4);
502 insn->addressSize = (hasAdSize ? 2 : 4);
503 insn->displacementSize = (hasAdSize ? 2 : 4);
504 insn->immediateSize = (hasOpSize ? 2 : 4);
505 } else if (insn->mode == MODE_64BIT) {
506 if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
507 insn->registerSize = 8;
508 insn->addressSize = (hasAdSize ? 4 : 8);
509 insn->displacementSize = 4;
510 insn->immediateSize = 4;
511 } else if (insn->rexPrefix) {
512 insn->registerSize = (hasOpSize ? 2 : 4);
513 insn->addressSize = (hasAdSize ? 4 : 8);
514 insn->displacementSize = (hasOpSize ? 2 : 4);
515 insn->immediateSize = (hasOpSize ? 2 : 4);
517 insn->registerSize = (hasOpSize ? 2 : 4);
518 insn->addressSize = (hasAdSize ? 4 : 8);
519 insn->displacementSize = (hasOpSize ? 2 : 4);
520 insn->immediateSize = (hasOpSize ? 2 : 4);
528 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
529 * extended or escape opcodes).
531 * @param insn - The instruction whose opcode is to be read.
532 * @return - 0 if the opcode could be read successfully; nonzero otherwise.
534 static int readOpcode(struct InternalInstruction* insn) {
535 /* Determine the length of the primary opcode */
539 dbgprintf(insn, "readOpcode()");
541 insn->opcodeType = ONEBYTE;
543 if (insn->vexSize == 3)
545 switch (mmmmmFromVEX2of3(insn->vexPrefix[1]))
548 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)", mmmmmFromVEX2of3(insn->vexPrefix[1]));
553 insn->twoByteEscape = 0x0f;
554 insn->opcodeType = TWOBYTE;
555 return consumeByte(insn, &insn->opcode);
557 insn->twoByteEscape = 0x0f;
558 insn->threeByteEscape = 0x38;
559 insn->opcodeType = THREEBYTE_38;
560 return consumeByte(insn, &insn->opcode);
562 insn->twoByteEscape = 0x0f;
563 insn->threeByteEscape = 0x3a;
564 insn->opcodeType = THREEBYTE_3A;
565 return consumeByte(insn, &insn->opcode);
568 else if (insn->vexSize == 2)
570 insn->twoByteEscape = 0x0f;
571 insn->opcodeType = TWOBYTE;
572 return consumeByte(insn, &insn->opcode);
575 if (consumeByte(insn, ¤t))
578 if (current == 0x0f) {
579 dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
581 insn->twoByteEscape = current;
583 if (consumeByte(insn, ¤t))
586 if (current == 0x38) {
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_38;
595 } else if (current == 0x3a) {
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_3A;
604 } else if (current == 0xa6) {
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_A6;
613 } else if (current == 0xa7) {
614 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
616 insn->threeByteEscape = current;
618 if (consumeByte(insn, ¤t))
621 insn->opcodeType = THREEBYTE_A7;
623 dbgprintf(insn, "Didn't find a three-byte escape prefix");
625 insn->opcodeType = TWOBYTE;
630 * At this point we have consumed the full opcode.
631 * Anything we consume from here on must be unconsumed.
634 insn->opcode = current;
639 static int readModRM(struct InternalInstruction* insn);
642 * getIDWithAttrMask - Determines the ID of an instruction, consuming
643 * the ModR/M byte as appropriate for extended and escape opcodes,
644 * and using a supplied attribute mask.
646 * @param instructionID - A pointer whose target is filled in with the ID of the
648 * @param insn - The instruction whose ID is to be determined.
649 * @param attrMask - The attribute mask to search.
650 * @return - 0 if the ModR/M could be read when needed or was not
651 * needed; nonzero otherwise.
653 static int getIDWithAttrMask(uint16_t* instructionID,
654 struct InternalInstruction* insn,
656 BOOL hasModRMExtension;
658 uint8_t instructionClass;
660 instructionClass = contextForAttrs(attrMask);
662 hasModRMExtension = modRMRequired(insn->opcodeType,
666 if (hasModRMExtension) {
670 *instructionID = decode(insn->opcodeType,
675 *instructionID = decode(insn->opcodeType,
685 * is16BitEquivalent - Determines whether two instruction names refer to
686 * equivalent instructions but one is 16-bit whereas the other is not.
688 * @param orig - The instruction that is not 16-bit
689 * @param equiv - The instruction that is 16-bit
691 static BOOL is16BitEquvalent(const char* orig, const char* equiv) {
695 if (orig[i] == '\0' && equiv[i] == '\0')
697 if (orig[i] == '\0' || equiv[i] == '\0')
699 if (orig[i] != equiv[i]) {
700 if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
702 if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
704 if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
712 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
713 * appropriate for extended and escape opcodes. Determines the attributes and
714 * context for the instruction before doing so.
716 * @param insn - The instruction whose ID is to be determined.
717 * @return - 0 if the ModR/M could be read when needed or was not needed;
720 static int getID(struct InternalInstruction* insn, void *miiArg) {
722 uint16_t instructionID;
724 dbgprintf(insn, "getID()");
726 attrMask = ATTR_NONE;
728 if (insn->mode == MODE_64BIT)
729 attrMask |= ATTR_64BIT;
732 attrMask |= ATTR_VEX;
734 if (insn->vexSize == 3) {
735 switch (ppFromVEX3of3(insn->vexPrefix[2])) {
737 attrMask |= ATTR_OPSIZE;
747 if (lFromVEX3of3(insn->vexPrefix[2]))
748 attrMask |= ATTR_VEXL;
750 else if (insn->vexSize == 2) {
751 switch (ppFromVEX2of2(insn->vexPrefix[1])) {
753 attrMask |= ATTR_OPSIZE;
763 if (lFromVEX2of2(insn->vexPrefix[1]))
764 attrMask |= ATTR_VEXL;
771 if (isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
772 attrMask |= ATTR_OPSIZE;
773 else if (isPrefixAtLocation(insn, 0x67, insn->necessaryPrefixLocation))
774 attrMask |= ATTR_ADSIZE;
775 else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
777 else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
781 if (insn->rexPrefix & 0x08)
782 attrMask |= ATTR_REXW;
784 if (getIDWithAttrMask(&instructionID, insn, attrMask))
787 /* The following clauses compensate for limitations of the tables. */
789 if ((attrMask & ATTR_VEXL) && (attrMask & ATTR_REXW) &&
790 !(attrMask & ATTR_OPSIZE)) {
792 * Some VEX instructions ignore the L-bit, but use the W-bit. Normally L-bit
793 * has precedence since there are no L-bit with W-bit entries in the tables.
794 * So if the L-bit isn't significant we should use the W-bit instead.
795 * We only need to do this if the instruction doesn't specify OpSize since
796 * there is a VEX_L_W_OPSIZE table.
799 const struct InstructionSpecifier *spec;
800 uint16_t instructionIDWithWBit;
801 const struct InstructionSpecifier *specWithWBit;
803 spec = specifierForUID(instructionID);
805 if (getIDWithAttrMask(&instructionIDWithWBit,
807 (attrMask & (~ATTR_VEXL)) | ATTR_REXW)) {
808 insn->instructionID = instructionID;
813 specWithWBit = specifierForUID(instructionIDWithWBit);
815 if (instructionID != instructionIDWithWBit) {
816 insn->instructionID = instructionIDWithWBit;
817 insn->spec = specWithWBit;
819 insn->instructionID = instructionID;
825 if (insn->prefixPresent[0x66] && !(attrMask & ATTR_OPSIZE)) {
827 * The instruction tables make no distinction between instructions that
828 * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
829 * particular spot (i.e., many MMX operations). In general we're
830 * conservative, but in the specific case where OpSize is present but not
831 * in the right place we check if there's a 16-bit operation.
834 const struct InstructionSpecifier *spec;
835 uint16_t instructionIDWithOpsize;
836 const char *specName, *specWithOpSizeName;
838 spec = specifierForUID(instructionID);
840 if (getIDWithAttrMask(&instructionIDWithOpsize,
842 attrMask | ATTR_OPSIZE)) {
844 * ModRM required with OpSize but not present; give up and return version
848 insn->instructionID = instructionID;
853 specName = x86DisassemblerGetInstrName(instructionID, miiArg);
855 x86DisassemblerGetInstrName(instructionIDWithOpsize, miiArg);
857 if (is16BitEquvalent(specName, specWithOpSizeName)) {
858 insn->instructionID = instructionIDWithOpsize;
859 insn->spec = specifierForUID(instructionIDWithOpsize);
861 insn->instructionID = instructionID;
867 if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
868 insn->rexPrefix & 0x01) {
870 * NOOP shouldn't decode as NOOP if REX.b is set. Instead
871 * it should decode as XCHG %r8, %eax.
874 const struct InstructionSpecifier *spec;
875 uint16_t instructionIDWithNewOpcode;
876 const struct InstructionSpecifier *specWithNewOpcode;
878 spec = specifierForUID(instructionID);
880 /* Borrow opcode from one of the other XCHGar opcodes */
883 if (getIDWithAttrMask(&instructionIDWithNewOpcode,
888 insn->instructionID = instructionID;
893 specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
898 insn->instructionID = instructionIDWithNewOpcode;
899 insn->spec = specWithNewOpcode;
904 insn->instructionID = instructionID;
905 insn->spec = specifierForUID(insn->instructionID);
911 * readSIB - Consumes the SIB byte to determine addressing information for an
914 * @param insn - The instruction whose SIB byte is to be read.
915 * @return - 0 if the SIB byte was successfully read; nonzero otherwise.
917 static int readSIB(struct InternalInstruction* insn) {
918 SIBIndex sibIndexBase = 0;
919 SIBBase sibBaseBase = 0;
922 dbgprintf(insn, "readSIB()");
924 if (insn->consumedSIB)
927 insn->consumedSIB = TRUE;
929 switch (insn->addressSize) {
931 dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
935 sibIndexBase = SIB_INDEX_EAX;
936 sibBaseBase = SIB_BASE_EAX;
939 sibIndexBase = SIB_INDEX_RAX;
940 sibBaseBase = SIB_BASE_RAX;
944 if (consumeByte(insn, &insn->sib))
947 index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
951 insn->sibIndex = SIB_INDEX_NONE;
954 insn->sibIndex = (SIBIndex)(sibIndexBase + index);
955 if (insn->sibIndex == SIB_INDEX_sib ||
956 insn->sibIndex == SIB_INDEX_sib64)
957 insn->sibIndex = SIB_INDEX_NONE;
961 switch (scaleFromSIB(insn->sib)) {
976 base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
980 switch (modFromModRM(insn->modRM)) {
982 insn->eaDisplacement = EA_DISP_32;
983 insn->sibBase = SIB_BASE_NONE;
986 insn->eaDisplacement = EA_DISP_8;
987 insn->sibBase = (insn->addressSize == 4 ?
988 SIB_BASE_EBP : SIB_BASE_RBP);
991 insn->eaDisplacement = EA_DISP_32;
992 insn->sibBase = (insn->addressSize == 4 ?
993 SIB_BASE_EBP : SIB_BASE_RBP);
996 debug("Cannot have Mod = 0b11 and a SIB byte");
1001 insn->sibBase = (SIBBase)(sibBaseBase + base);
1009 * readDisplacement - Consumes the displacement of an instruction.
1011 * @param insn - The instruction whose displacement is to be read.
1012 * @return - 0 if the displacement byte was successfully read; nonzero
1015 static int readDisplacement(struct InternalInstruction* insn) {
1020 dbgprintf(insn, "readDisplacement()");
1022 if (insn->consumedDisplacement)
1025 insn->consumedDisplacement = TRUE;
1026 insn->displacementOffset = insn->readerCursor - insn->startLocation;
1028 switch (insn->eaDisplacement) {
1030 insn->consumedDisplacement = FALSE;
1033 if (consumeInt8(insn, &d8))
1035 insn->displacement = d8;
1038 if (consumeInt16(insn, &d16))
1040 insn->displacement = d16;
1043 if (consumeInt32(insn, &d32))
1045 insn->displacement = d32;
1049 insn->consumedDisplacement = TRUE;
1054 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1055 * displacement) for an instruction and interprets it.
1057 * @param insn - The instruction whose addressing information is to be read.
1058 * @return - 0 if the information was successfully read; nonzero otherwise.
1060 static int readModRM(struct InternalInstruction* insn) {
1061 uint8_t mod, rm, reg;
1063 dbgprintf(insn, "readModRM()");
1065 if (insn->consumedModRM)
1068 if (consumeByte(insn, &insn->modRM))
1070 insn->consumedModRM = TRUE;
1072 mod = modFromModRM(insn->modRM);
1073 rm = rmFromModRM(insn->modRM);
1074 reg = regFromModRM(insn->modRM);
1077 * This goes by insn->registerSize to pick the correct register, which messes
1078 * up if we're using (say) XMM or 8-bit register operands. That gets fixed in
1081 switch (insn->registerSize) {
1083 insn->regBase = MODRM_REG_AX;
1084 insn->eaRegBase = EA_REG_AX;
1087 insn->regBase = MODRM_REG_EAX;
1088 insn->eaRegBase = EA_REG_EAX;
1091 insn->regBase = MODRM_REG_RAX;
1092 insn->eaRegBase = EA_REG_RAX;
1096 reg |= rFromREX(insn->rexPrefix) << 3;
1097 rm |= bFromREX(insn->rexPrefix) << 3;
1099 insn->reg = (Reg)(insn->regBase + reg);
1101 switch (insn->addressSize) {
1103 insn->eaBaseBase = EA_BASE_BX_SI;
1108 insn->eaBase = EA_BASE_NONE;
1109 insn->eaDisplacement = EA_DISP_16;
1110 if (readDisplacement(insn))
1113 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1114 insn->eaDisplacement = EA_DISP_NONE;
1118 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1119 insn->eaDisplacement = EA_DISP_8;
1120 if (readDisplacement(insn))
1124 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1125 insn->eaDisplacement = EA_DISP_16;
1126 if (readDisplacement(insn))
1130 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1131 if (readDisplacement(insn))
1138 insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1142 insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1145 case 0xc: /* in case REXW.b is set */
1146 insn->eaBase = (insn->addressSize == 4 ?
1147 EA_BASE_sib : EA_BASE_sib64);
1149 if (readDisplacement(insn))
1153 insn->eaBase = EA_BASE_NONE;
1154 insn->eaDisplacement = EA_DISP_32;
1155 if (readDisplacement(insn))
1159 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1165 insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1168 case 0xc: /* in case REXW.b is set */
1169 insn->eaBase = EA_BASE_sib;
1171 if (readDisplacement(insn))
1175 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1176 if (readDisplacement(insn))
1182 insn->eaDisplacement = EA_DISP_NONE;
1183 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1187 } /* switch (insn->addressSize) */
1192 #define GENERIC_FIXUP_FUNC(name, base, prefix) \
1193 static uint8_t name(struct InternalInstruction *insn, \
1200 debug("Unhandled register type"); \
1204 return base + index; \
1206 if (insn->rexPrefix && \
1207 index >= 4 && index <= 7) { \
1208 return prefix##_SPL + (index - 4); \
1210 return prefix##_AL + index; \
1213 return prefix##_AX + index; \
1215 return prefix##_EAX + index; \
1217 return prefix##_RAX + index; \
1219 return prefix##_YMM0 + index; \
1224 return prefix##_XMM0 + index; \
1230 return prefix##_MM0 + index; \
1231 case TYPE_SEGMENTREG: \
1234 return prefix##_ES + index; \
1235 case TYPE_DEBUGREG: \
1238 return prefix##_DR0 + index; \
1239 case TYPE_CONTROLREG: \
1242 return prefix##_CR0 + index; \
1247 * fixup*Value - Consults an operand type to determine the meaning of the
1248 * reg or R/M field. If the operand is an XMM operand, for example, an
1249 * operand would be XMM0 instead of AX, which readModRM() would otherwise
1250 * misinterpret it as.
1252 * @param insn - The instruction containing the operand.
1253 * @param type - The operand type.
1254 * @param index - The existing value of the field as reported by readModRM().
1255 * @param valid - The address of a uint8_t. The target is set to 1 if the
1256 * field is valid for the register class; 0 if not.
1257 * @return - The proper value.
1259 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG)
1260 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG)
1263 * fixupReg - Consults an operand specifier to determine which of the
1264 * fixup*Value functions to use in correcting readModRM()'ss interpretation.
1266 * @param insn - See fixup*Value().
1267 * @param op - The operand specifier.
1268 * @return - 0 if fixup was successful; -1 if the register returned was
1269 * invalid for its class.
1271 static int fixupReg(struct InternalInstruction *insn,
1272 const struct OperandSpecifier *op) {
1275 dbgprintf(insn, "fixupReg()");
1277 switch ((OperandEncoding)op->encoding) {
1279 debug("Expected a REG or R/M encoding in fixupReg");
1282 insn->vvvv = (Reg)fixupRegValue(insn,
1283 (OperandType)op->type,
1290 insn->reg = (Reg)fixupRegValue(insn,
1291 (OperandType)op->type,
1292 insn->reg - insn->regBase,
1298 if (insn->eaBase >= insn->eaRegBase) {
1299 insn->eaBase = (EABase)fixupRMValue(insn,
1300 (OperandType)op->type,
1301 insn->eaBase - insn->eaRegBase,
1313 * readOpcodeModifier - Reads an operand from the opcode field of an
1314 * instruction. Handles AddRegFrm instructions.
1316 * @param insn - The instruction whose opcode field is to be read.
1317 * @param inModRM - Indicates that the opcode field is to be read from the
1318 * ModR/M extension; useful for escape opcodes
1319 * @return - 0 on success; nonzero otherwise.
1321 static int readOpcodeModifier(struct InternalInstruction* insn) {
1322 dbgprintf(insn, "readOpcodeModifier()");
1324 if (insn->consumedOpcodeModifier)
1327 insn->consumedOpcodeModifier = TRUE;
1329 switch (insn->spec->modifierType) {
1331 debug("Unknown modifier type.");
1334 debug("No modifier but an operand expects one.");
1336 case MODIFIER_OPCODE:
1337 insn->opcodeModifier = insn->opcode - insn->spec->modifierBase;
1339 case MODIFIER_MODRM:
1340 insn->opcodeModifier = insn->modRM - insn->spec->modifierBase;
1346 * readOpcodeRegister - Reads an operand from the opcode field of an
1347 * instruction and interprets it appropriately given the operand width.
1348 * Handles AddRegFrm instructions.
1350 * @param insn - See readOpcodeModifier().
1351 * @param size - The width (in bytes) of the register being specified.
1352 * 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1354 * @return - 0 on success; nonzero otherwise.
1356 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1357 dbgprintf(insn, "readOpcodeRegister()");
1359 if (readOpcodeModifier(insn))
1363 size = insn->registerSize;
1367 insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1368 | insn->opcodeModifier));
1369 if (insn->rexPrefix &&
1370 insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1371 insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1372 insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1373 + (insn->opcodeRegister - MODRM_REG_AL - 4));
1378 insn->opcodeRegister = (Reg)(MODRM_REG_AX
1379 + ((bFromREX(insn->rexPrefix) << 3)
1380 | insn->opcodeModifier));
1383 insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1384 + ((bFromREX(insn->rexPrefix) << 3)
1385 | insn->opcodeModifier));
1388 insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1389 + ((bFromREX(insn->rexPrefix) << 3)
1390 | insn->opcodeModifier));
1398 * readImmediate - Consumes an immediate operand from an instruction, given the
1399 * desired operand size.
1401 * @param insn - The instruction whose operand is to be read.
1402 * @param size - The width (in bytes) of the operand.
1403 * @return - 0 if the immediate was successfully consumed; nonzero
1406 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1412 dbgprintf(insn, "readImmediate()");
1414 if (insn->numImmediatesConsumed == 2) {
1415 debug("Already consumed two immediates");
1420 size = insn->immediateSize;
1422 insn->immediateSize = size;
1423 insn->immediateOffset = insn->readerCursor - insn->startLocation;
1427 if (consumeByte(insn, &imm8))
1429 insn->immediates[insn->numImmediatesConsumed] = imm8;
1432 if (consumeUInt16(insn, &imm16))
1434 insn->immediates[insn->numImmediatesConsumed] = imm16;
1437 if (consumeUInt32(insn, &imm32))
1439 insn->immediates[insn->numImmediatesConsumed] = imm32;
1442 if (consumeUInt64(insn, &imm64))
1444 insn->immediates[insn->numImmediatesConsumed] = imm64;
1448 insn->numImmediatesConsumed++;
1454 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1456 * @param insn - The instruction whose operand is to be read.
1457 * @return - 0 if the vvvv was successfully consumed; nonzero
1460 static int readVVVV(struct InternalInstruction* insn) {
1461 dbgprintf(insn, "readVVVV()");
1463 if (insn->vexSize == 3)
1464 insn->vvvv = vvvvFromVEX3of3(insn->vexPrefix[2]);
1465 else if (insn->vexSize == 2)
1466 insn->vvvv = vvvvFromVEX2of2(insn->vexPrefix[1]);
1470 if (insn->mode != MODE_64BIT)
1477 * readOperands - Consults the specifier for an instruction and consumes all
1478 * operands for that instruction, interpreting them as it goes.
1480 * @param insn - The instruction whose operands are to be read and interpreted.
1481 * @return - 0 if all operands could be read; nonzero otherwise.
1483 static int readOperands(struct InternalInstruction* insn) {
1485 int hasVVVV, needVVVV;
1488 dbgprintf(insn, "readOperands()");
1490 /* If non-zero vvvv specified, need to make sure one of the operands
1492 hasVVVV = !readVVVV(insn);
1493 needVVVV = hasVVVV && (insn->vvvv != 0);
1495 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
1496 switch (insn->spec->operands[index].encoding) {
1501 if (readModRM(insn))
1503 if (fixupReg(insn, &insn->spec->operands[index]))
1512 dbgprintf(insn, "We currently don't hande code-offset encodings");
1516 /* Saw a register immediate so don't read again and instead split the
1517 previous immediate. FIXME: This is a hack. */
1518 insn->immediates[insn->numImmediatesConsumed] =
1519 insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1520 ++insn->numImmediatesConsumed;
1523 if (readImmediate(insn, 1))
1525 if (insn->spec->operands[index].type == TYPE_IMM3 &&
1526 insn->immediates[insn->numImmediatesConsumed - 1] > 7)
1528 if (insn->spec->operands[index].type == TYPE_XMM128 ||
1529 insn->spec->operands[index].type == TYPE_XMM256)
1533 if (readImmediate(insn, 2))
1537 if (readImmediate(insn, 4))
1541 if (readImmediate(insn, 8))
1545 if (readImmediate(insn, insn->immediateSize))
1549 if (readImmediate(insn, insn->addressSize))
1553 if (readOpcodeRegister(insn, 1))
1557 if (readOpcodeRegister(insn, 2))
1561 if (readOpcodeRegister(insn, 4))
1565 if (readOpcodeRegister(insn, 8))
1569 if (readOpcodeRegister(insn, 0))
1573 if (readOpcodeModifier(insn))
1577 needVVVV = 0; /* Mark that we have found a VVVV operand. */
1580 if (fixupReg(insn, &insn->spec->operands[index]))
1586 dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1591 /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1592 if (needVVVV) return -1;
1598 * decodeInstruction - Reads and interprets a full instruction provided by the
1601 * @param insn - A pointer to the instruction to be populated. Must be
1603 * @param reader - The function to be used to read the instruction's bytes.
1604 * @param readerArg - A generic argument to be passed to the reader to store
1605 * any internal state.
1606 * @param logger - If non-NULL, the function to be used to write log messages
1608 * @param loggerArg - A generic argument to be passed to the logger to store
1609 * any internal state.
1610 * @param startLoc - The address (in the reader's address space) of the first
1611 * byte in the instruction.
1612 * @param mode - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1613 * decode the instruction in.
1614 * @return - 0 if the instruction's memory could be read; nonzero if
1617 int decodeInstruction(struct InternalInstruction* insn,
1618 byteReader_t reader,
1624 DisassemblerMode mode) {
1625 memset(insn, 0, sizeof(struct InternalInstruction));
1627 insn->reader = reader;
1628 insn->readerArg = readerArg;
1629 insn->dlog = logger;
1630 insn->dlogArg = loggerArg;
1631 insn->startLocation = startLoc;
1632 insn->readerCursor = startLoc;
1634 insn->numImmediatesConsumed = 0;
1636 if (readPrefixes(insn) ||
1638 getID(insn, miiArg) ||
1639 insn->instructionID == 0 ||
1643 insn->length = insn->readerCursor - insn->startLocation;
1645 dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1646 startLoc, insn->readerCursor, insn->length);
1648 if (insn->length > 15)
1649 dbgprintf(insn, "Instruction exceeds 15-byte limit");