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)];
141 case MODRM_SPLITMISC:
142 if (modFromModRM(modRM) == 0x3)
143 return modRMTable[dec->instructionIDs+(modRM & 0x3f)+8];
144 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
146 return modRMTable[dec->instructionIDs+modRM];
151 * specifierForUID - Given a UID, returns the name and operand specification for
154 * @param uid - The unique ID for the instruction. This should be returned by
155 * decode(); specifierForUID will not check bounds.
156 * @return - A pointer to the specification for that instruction.
158 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
159 return &INSTRUCTIONS_SYM[uid];
163 * consumeByte - Uses the reader function provided by the user to consume one
164 * byte from the instruction's memory and advance the cursor.
166 * @param insn - The instruction with the reader function to use. The cursor
167 * for this instruction is advanced.
168 * @param byte - A pointer to a pre-allocated memory buffer to be populated
169 * with the data read.
170 * @return - 0 if the read was successful; nonzero otherwise.
172 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
173 int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
176 ++(insn->readerCursor);
182 * lookAtByte - Like consumeByte, but does not advance the cursor.
184 * @param insn - See consumeByte().
185 * @param byte - See consumeByte().
186 * @return - See consumeByte().
188 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
189 return insn->reader(insn->readerArg, byte, insn->readerCursor);
192 static void unconsumeByte(struct InternalInstruction* insn) {
193 insn->readerCursor--;
196 #define CONSUME_FUNC(name, type) \
197 static int name(struct InternalInstruction* insn, type* ptr) { \
200 for (offset = 0; offset < sizeof(type); ++offset) { \
202 int ret = insn->reader(insn->readerArg, \
204 insn->readerCursor + offset); \
207 combined = combined | ((uint64_t)byte << (offset * 8)); \
210 insn->readerCursor += sizeof(type); \
215 * consume* - Use the reader function provided by the user to consume data
216 * values of various sizes from the instruction's memory and advance the
217 * cursor appropriately. These readers perform endian conversion.
219 * @param insn - See consumeByte().
220 * @param ptr - A pointer to a pre-allocated memory of appropriate size to
221 * be populated with the data read.
222 * @return - See consumeByte().
224 CONSUME_FUNC(consumeInt8, int8_t)
225 CONSUME_FUNC(consumeInt16, int16_t)
226 CONSUME_FUNC(consumeInt32, int32_t)
227 CONSUME_FUNC(consumeUInt16, uint16_t)
228 CONSUME_FUNC(consumeUInt32, uint32_t)
229 CONSUME_FUNC(consumeUInt64, uint64_t)
232 * dbgprintf - Uses the logging function provided by the user to log a single
233 * message, typically without a carriage-return.
235 * @param insn - The instruction containing the logging function.
236 * @param format - See printf().
237 * @param ... - See printf().
239 static void dbgprintf(struct InternalInstruction* insn,
248 va_start(ap, format);
249 (void)vsnprintf(buffer, sizeof(buffer), format, ap);
252 insn->dlog(insn->dlogArg, buffer);
258 * setPrefixPresent - Marks that a particular prefix is present at a particular
261 * @param insn - The instruction to be marked as having the prefix.
262 * @param prefix - The prefix that is present.
263 * @param location - The location where the prefix is located (in the address
264 * space of the instruction's reader).
266 static void setPrefixPresent(struct InternalInstruction* insn,
270 insn->prefixPresent[prefix] = 1;
271 insn->prefixLocations[prefix] = location;
275 * isPrefixAtLocation - Queries an instruction to determine whether a prefix is
276 * present at a given location.
278 * @param insn - The instruction to be queried.
279 * @param prefix - The prefix.
280 * @param location - The location to query.
281 * @return - Whether the prefix is at that location.
283 static BOOL isPrefixAtLocation(struct InternalInstruction* insn,
287 if (insn->prefixPresent[prefix] == 1 &&
288 insn->prefixLocations[prefix] == location)
295 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
296 * instruction as having them. Also sets the instruction's default operand,
297 * address, and other relevant data sizes to report operands correctly.
299 * @param insn - The instruction whose prefixes are to be read.
300 * @return - 0 if the instruction could be read until the end of the prefix
301 * bytes, and no prefixes conflicted; nonzero otherwise.
303 static int readPrefixes(struct InternalInstruction* insn) {
304 BOOL isPrefix = TRUE;
305 BOOL prefixGroups[4] = { FALSE };
306 uint64_t prefixLocation;
309 BOOL hasAdSize = FALSE;
310 BOOL hasOpSize = FALSE;
312 dbgprintf(insn, "readPrefixes()");
315 prefixLocation = insn->readerCursor;
317 if (consumeByte(insn, &byte))
321 * If the byte is a LOCK/REP/REPNE prefix and not a part of the opcode, then
322 * break and let it be disassembled as a normal "instruction".
324 if (insn->readerCursor - 1 == insn->startLocation
325 && (byte == 0xf0 || byte == 0xf2 || byte == 0xf3)) {
329 if (lookAtByte(insn, &nextByte))
331 if (insn->mode == MODE_64BIT && (nextByte & 0xf0) == 0x40) {
332 if (consumeByte(insn, &nextByte))
334 if (lookAtByte(insn, &nextByte))
338 if (nextByte != 0x0f && nextByte != 0x90)
343 case 0xf0: /* LOCK */
344 case 0xf2: /* REPNE/REPNZ */
345 case 0xf3: /* REP or REPE/REPZ */
347 dbgprintf(insn, "Redundant Group 1 prefix");
348 prefixGroups[0] = TRUE;
349 setPrefixPresent(insn, byte, prefixLocation);
351 case 0x2e: /* CS segment override -OR- Branch not taken */
352 case 0x36: /* SS segment override -OR- Branch taken */
353 case 0x3e: /* DS segment override */
354 case 0x26: /* ES segment override */
355 case 0x64: /* FS segment override */
356 case 0x65: /* GS segment override */
359 insn->segmentOverride = SEG_OVERRIDE_CS;
362 insn->segmentOverride = SEG_OVERRIDE_SS;
365 insn->segmentOverride = SEG_OVERRIDE_DS;
368 insn->segmentOverride = SEG_OVERRIDE_ES;
371 insn->segmentOverride = SEG_OVERRIDE_FS;
374 insn->segmentOverride = SEG_OVERRIDE_GS;
377 debug("Unhandled override");
381 dbgprintf(insn, "Redundant Group 2 prefix");
382 prefixGroups[1] = TRUE;
383 setPrefixPresent(insn, byte, prefixLocation);
385 case 0x66: /* Operand-size override */
387 dbgprintf(insn, "Redundant Group 3 prefix");
388 prefixGroups[2] = TRUE;
390 setPrefixPresent(insn, byte, prefixLocation);
392 case 0x67: /* Address-size override */
394 dbgprintf(insn, "Redundant Group 4 prefix");
395 prefixGroups[3] = TRUE;
397 setPrefixPresent(insn, byte, prefixLocation);
399 default: /* Not a prefix byte */
405 dbgprintf(insn, "Found prefix 0x%hhx", byte);
413 if (lookAtByte(insn, &byte1)) {
414 dbgprintf(insn, "Couldn't read second byte of VEX");
418 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
420 insn->necessaryPrefixLocation = insn->readerCursor - 1;
424 insn->necessaryPrefixLocation = insn->readerCursor - 1;
427 if (insn->vexSize == 3) {
428 insn->vexPrefix[0] = byte;
429 consumeByte(insn, &insn->vexPrefix[1]);
430 consumeByte(insn, &insn->vexPrefix[2]);
432 /* We simulate the REX prefix for simplicity's sake */
434 if (insn->mode == MODE_64BIT) {
435 insn->rexPrefix = 0x40
436 | (wFromVEX3of3(insn->vexPrefix[2]) << 3)
437 | (rFromVEX2of3(insn->vexPrefix[1]) << 2)
438 | (xFromVEX2of3(insn->vexPrefix[1]) << 1)
439 | (bFromVEX2of3(insn->vexPrefix[1]) << 0);
442 switch (ppFromVEX3of3(insn->vexPrefix[2]))
451 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1], insn->vexPrefix[2]);
454 else if (byte == 0xc5) {
457 if (lookAtByte(insn, &byte1)) {
458 dbgprintf(insn, "Couldn't read second byte of VEX");
462 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
469 if (insn->vexSize == 2) {
470 insn->vexPrefix[0] = byte;
471 consumeByte(insn, &insn->vexPrefix[1]);
473 if (insn->mode == MODE_64BIT) {
474 insn->rexPrefix = 0x40
475 | (rFromVEX2of2(insn->vexPrefix[1]) << 2);
478 switch (ppFromVEX2of2(insn->vexPrefix[1]))
487 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1]);
491 if (insn->mode == MODE_64BIT) {
492 if ((byte & 0xf0) == 0x40) {
495 if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
496 dbgprintf(insn, "Redundant REX prefix");
500 insn->rexPrefix = byte;
501 insn->necessaryPrefixLocation = insn->readerCursor - 2;
503 dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
506 insn->necessaryPrefixLocation = insn->readerCursor - 1;
510 insn->necessaryPrefixLocation = insn->readerCursor - 1;
514 if (insn->mode == MODE_16BIT) {
515 insn->registerSize = (hasOpSize ? 4 : 2);
516 insn->addressSize = (hasAdSize ? 4 : 2);
517 insn->displacementSize = (hasAdSize ? 4 : 2);
518 insn->immediateSize = (hasOpSize ? 4 : 2);
519 } else if (insn->mode == MODE_32BIT) {
520 insn->registerSize = (hasOpSize ? 2 : 4);
521 insn->addressSize = (hasAdSize ? 2 : 4);
522 insn->displacementSize = (hasAdSize ? 2 : 4);
523 insn->immediateSize = (hasOpSize ? 2 : 4);
524 } else if (insn->mode == MODE_64BIT) {
525 if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
526 insn->registerSize = 8;
527 insn->addressSize = (hasAdSize ? 4 : 8);
528 insn->displacementSize = 4;
529 insn->immediateSize = 4;
530 } else if (insn->rexPrefix) {
531 insn->registerSize = (hasOpSize ? 2 : 4);
532 insn->addressSize = (hasAdSize ? 4 : 8);
533 insn->displacementSize = (hasOpSize ? 2 : 4);
534 insn->immediateSize = (hasOpSize ? 2 : 4);
536 insn->registerSize = (hasOpSize ? 2 : 4);
537 insn->addressSize = (hasAdSize ? 4 : 8);
538 insn->displacementSize = (hasOpSize ? 2 : 4);
539 insn->immediateSize = (hasOpSize ? 2 : 4);
547 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
548 * extended or escape opcodes).
550 * @param insn - The instruction whose opcode is to be read.
551 * @return - 0 if the opcode could be read successfully; nonzero otherwise.
553 static int readOpcode(struct InternalInstruction* insn) {
554 /* Determine the length of the primary opcode */
558 dbgprintf(insn, "readOpcode()");
560 insn->opcodeType = ONEBYTE;
562 if (insn->vexSize == 3)
564 switch (mmmmmFromVEX2of3(insn->vexPrefix[1]))
567 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)", mmmmmFromVEX2of3(insn->vexPrefix[1]));
572 insn->twoByteEscape = 0x0f;
573 insn->opcodeType = TWOBYTE;
574 return consumeByte(insn, &insn->opcode);
576 insn->twoByteEscape = 0x0f;
577 insn->threeByteEscape = 0x38;
578 insn->opcodeType = THREEBYTE_38;
579 return consumeByte(insn, &insn->opcode);
581 insn->twoByteEscape = 0x0f;
582 insn->threeByteEscape = 0x3a;
583 insn->opcodeType = THREEBYTE_3A;
584 return consumeByte(insn, &insn->opcode);
587 else if (insn->vexSize == 2)
589 insn->twoByteEscape = 0x0f;
590 insn->opcodeType = TWOBYTE;
591 return consumeByte(insn, &insn->opcode);
594 if (consumeByte(insn, ¤t))
597 if (current == 0x0f) {
598 dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
600 insn->twoByteEscape = current;
602 if (consumeByte(insn, ¤t))
605 if (current == 0x38) {
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_38;
614 } else if (current == 0x3a) {
615 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
617 insn->threeByteEscape = current;
619 if (consumeByte(insn, ¤t))
622 insn->opcodeType = THREEBYTE_3A;
623 } else if (current == 0xa6) {
624 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
626 insn->threeByteEscape = current;
628 if (consumeByte(insn, ¤t))
631 insn->opcodeType = THREEBYTE_A6;
632 } else if (current == 0xa7) {
633 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
635 insn->threeByteEscape = current;
637 if (consumeByte(insn, ¤t))
640 insn->opcodeType = THREEBYTE_A7;
642 dbgprintf(insn, "Didn't find a three-byte escape prefix");
644 insn->opcodeType = TWOBYTE;
649 * At this point we have consumed the full opcode.
650 * Anything we consume from here on must be unconsumed.
653 insn->opcode = current;
658 static int readModRM(struct InternalInstruction* insn);
661 * getIDWithAttrMask - Determines the ID of an instruction, consuming
662 * the ModR/M byte as appropriate for extended and escape opcodes,
663 * and using a supplied attribute mask.
665 * @param instructionID - A pointer whose target is filled in with the ID of the
667 * @param insn - The instruction whose ID is to be determined.
668 * @param attrMask - The attribute mask to search.
669 * @return - 0 if the ModR/M could be read when needed or was not
670 * needed; nonzero otherwise.
672 static int getIDWithAttrMask(uint16_t* instructionID,
673 struct InternalInstruction* insn,
675 BOOL hasModRMExtension;
677 uint8_t instructionClass;
679 instructionClass = contextForAttrs(attrMask);
681 hasModRMExtension = modRMRequired(insn->opcodeType,
685 if (hasModRMExtension) {
689 *instructionID = decode(insn->opcodeType,
694 *instructionID = decode(insn->opcodeType,
704 * is16BitEquivalent - Determines whether two instruction names refer to
705 * equivalent instructions but one is 16-bit whereas the other is not.
707 * @param orig - The instruction that is not 16-bit
708 * @param equiv - The instruction that is 16-bit
710 static BOOL is16BitEquivalent(const char* orig, const char* equiv) {
714 if (orig[i] == '\0' && equiv[i] == '\0')
716 if (orig[i] == '\0' || equiv[i] == '\0')
718 if (orig[i] != equiv[i]) {
719 if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
721 if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
723 if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
731 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
732 * appropriate for extended and escape opcodes. Determines the attributes and
733 * context for the instruction before doing so.
735 * @param insn - The instruction whose ID is to be determined.
736 * @return - 0 if the ModR/M could be read when needed or was not needed;
739 static int getID(struct InternalInstruction* insn, const void *miiArg) {
741 uint16_t instructionID;
743 dbgprintf(insn, "getID()");
745 attrMask = ATTR_NONE;
747 if (insn->mode == MODE_64BIT)
748 attrMask |= ATTR_64BIT;
751 attrMask |= ATTR_VEX;
753 if (insn->vexSize == 3) {
754 switch (ppFromVEX3of3(insn->vexPrefix[2])) {
756 attrMask |= ATTR_OPSIZE;
766 if (lFromVEX3of3(insn->vexPrefix[2]))
767 attrMask |= ATTR_VEXL;
769 else if (insn->vexSize == 2) {
770 switch (ppFromVEX2of2(insn->vexPrefix[1])) {
772 attrMask |= ATTR_OPSIZE;
782 if (lFromVEX2of2(insn->vexPrefix[1]))
783 attrMask |= ATTR_VEXL;
790 if (isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
791 attrMask |= ATTR_OPSIZE;
792 else if (isPrefixAtLocation(insn, 0x67, insn->necessaryPrefixLocation))
793 attrMask |= ATTR_ADSIZE;
794 else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
796 else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
800 if (insn->rexPrefix & 0x08)
801 attrMask |= ATTR_REXW;
803 if (getIDWithAttrMask(&instructionID, insn, attrMask))
806 /* The following clauses compensate for limitations of the tables. */
808 if ((attrMask & ATTR_VEXL) && (attrMask & ATTR_REXW) &&
809 !(attrMask & ATTR_OPSIZE)) {
811 * Some VEX instructions ignore the L-bit, but use the W-bit. Normally L-bit
812 * has precedence since there are no L-bit with W-bit entries in the tables.
813 * So if the L-bit isn't significant we should use the W-bit instead.
814 * We only need to do this if the instruction doesn't specify OpSize since
815 * there is a VEX_L_W_OPSIZE table.
818 const struct InstructionSpecifier *spec;
819 uint16_t instructionIDWithWBit;
820 const struct InstructionSpecifier *specWithWBit;
822 spec = specifierForUID(instructionID);
824 if (getIDWithAttrMask(&instructionIDWithWBit,
826 (attrMask & (~ATTR_VEXL)) | ATTR_REXW)) {
827 insn->instructionID = instructionID;
832 specWithWBit = specifierForUID(instructionIDWithWBit);
834 if (instructionID != instructionIDWithWBit) {
835 insn->instructionID = instructionIDWithWBit;
836 insn->spec = specWithWBit;
838 insn->instructionID = instructionID;
844 if (insn->prefixPresent[0x66] && !(attrMask & ATTR_OPSIZE)) {
846 * The instruction tables make no distinction between instructions that
847 * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
848 * particular spot (i.e., many MMX operations). In general we're
849 * conservative, but in the specific case where OpSize is present but not
850 * in the right place we check if there's a 16-bit operation.
853 const struct InstructionSpecifier *spec;
854 uint16_t instructionIDWithOpsize;
855 const char *specName, *specWithOpSizeName;
857 spec = specifierForUID(instructionID);
859 if (getIDWithAttrMask(&instructionIDWithOpsize,
861 attrMask | ATTR_OPSIZE)) {
863 * ModRM required with OpSize but not present; give up and return version
867 insn->instructionID = instructionID;
872 specName = x86DisassemblerGetInstrName(instructionID, miiArg);
874 x86DisassemblerGetInstrName(instructionIDWithOpsize, miiArg);
876 if (is16BitEquivalent(specName, specWithOpSizeName)) {
877 insn->instructionID = instructionIDWithOpsize;
878 insn->spec = specifierForUID(instructionIDWithOpsize);
880 insn->instructionID = instructionID;
886 if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
887 insn->rexPrefix & 0x01) {
889 * NOOP shouldn't decode as NOOP if REX.b is set. Instead
890 * it should decode as XCHG %r8, %eax.
893 const struct InstructionSpecifier *spec;
894 uint16_t instructionIDWithNewOpcode;
895 const struct InstructionSpecifier *specWithNewOpcode;
897 spec = specifierForUID(instructionID);
899 /* Borrow opcode from one of the other XCHGar opcodes */
902 if (getIDWithAttrMask(&instructionIDWithNewOpcode,
907 insn->instructionID = instructionID;
912 specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
917 insn->instructionID = instructionIDWithNewOpcode;
918 insn->spec = specWithNewOpcode;
923 insn->instructionID = instructionID;
924 insn->spec = specifierForUID(insn->instructionID);
930 * readSIB - Consumes the SIB byte to determine addressing information for an
933 * @param insn - The instruction whose SIB byte is to be read.
934 * @return - 0 if the SIB byte was successfully read; nonzero otherwise.
936 static int readSIB(struct InternalInstruction* insn) {
937 SIBIndex sibIndexBase = 0;
938 SIBBase sibBaseBase = 0;
941 dbgprintf(insn, "readSIB()");
943 if (insn->consumedSIB)
946 insn->consumedSIB = TRUE;
948 switch (insn->addressSize) {
950 dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
954 sibIndexBase = SIB_INDEX_EAX;
955 sibBaseBase = SIB_BASE_EAX;
958 sibIndexBase = SIB_INDEX_RAX;
959 sibBaseBase = SIB_BASE_RAX;
963 if (consumeByte(insn, &insn->sib))
966 index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
970 insn->sibIndex = SIB_INDEX_NONE;
973 insn->sibIndex = (SIBIndex)(sibIndexBase + index);
974 if (insn->sibIndex == SIB_INDEX_sib ||
975 insn->sibIndex == SIB_INDEX_sib64)
976 insn->sibIndex = SIB_INDEX_NONE;
980 switch (scaleFromSIB(insn->sib)) {
995 base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
999 switch (modFromModRM(insn->modRM)) {
1001 insn->eaDisplacement = EA_DISP_32;
1002 insn->sibBase = SIB_BASE_NONE;
1005 insn->eaDisplacement = EA_DISP_8;
1006 insn->sibBase = (insn->addressSize == 4 ?
1007 SIB_BASE_EBP : SIB_BASE_RBP);
1010 insn->eaDisplacement = EA_DISP_32;
1011 insn->sibBase = (insn->addressSize == 4 ?
1012 SIB_BASE_EBP : SIB_BASE_RBP);
1015 debug("Cannot have Mod = 0b11 and a SIB byte");
1020 insn->sibBase = (SIBBase)(sibBaseBase + base);
1028 * readDisplacement - Consumes the displacement of an instruction.
1030 * @param insn - The instruction whose displacement is to be read.
1031 * @return - 0 if the displacement byte was successfully read; nonzero
1034 static int readDisplacement(struct InternalInstruction* insn) {
1039 dbgprintf(insn, "readDisplacement()");
1041 if (insn->consumedDisplacement)
1044 insn->consumedDisplacement = TRUE;
1045 insn->displacementOffset = insn->readerCursor - insn->startLocation;
1047 switch (insn->eaDisplacement) {
1049 insn->consumedDisplacement = FALSE;
1052 if (consumeInt8(insn, &d8))
1054 insn->displacement = d8;
1057 if (consumeInt16(insn, &d16))
1059 insn->displacement = d16;
1062 if (consumeInt32(insn, &d32))
1064 insn->displacement = d32;
1068 insn->consumedDisplacement = TRUE;
1073 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1074 * displacement) for an instruction and interprets it.
1076 * @param insn - The instruction whose addressing information is to be read.
1077 * @return - 0 if the information was successfully read; nonzero otherwise.
1079 static int readModRM(struct InternalInstruction* insn) {
1080 uint8_t mod, rm, reg;
1082 dbgprintf(insn, "readModRM()");
1084 if (insn->consumedModRM)
1087 if (consumeByte(insn, &insn->modRM))
1089 insn->consumedModRM = TRUE;
1091 mod = modFromModRM(insn->modRM);
1092 rm = rmFromModRM(insn->modRM);
1093 reg = regFromModRM(insn->modRM);
1096 * This goes by insn->registerSize to pick the correct register, which messes
1097 * up if we're using (say) XMM or 8-bit register operands. That gets fixed in
1100 switch (insn->registerSize) {
1102 insn->regBase = MODRM_REG_AX;
1103 insn->eaRegBase = EA_REG_AX;
1106 insn->regBase = MODRM_REG_EAX;
1107 insn->eaRegBase = EA_REG_EAX;
1110 insn->regBase = MODRM_REG_RAX;
1111 insn->eaRegBase = EA_REG_RAX;
1115 reg |= rFromREX(insn->rexPrefix) << 3;
1116 rm |= bFromREX(insn->rexPrefix) << 3;
1118 insn->reg = (Reg)(insn->regBase + reg);
1120 switch (insn->addressSize) {
1122 insn->eaBaseBase = EA_BASE_BX_SI;
1127 insn->eaBase = EA_BASE_NONE;
1128 insn->eaDisplacement = EA_DISP_16;
1129 if (readDisplacement(insn))
1132 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1133 insn->eaDisplacement = EA_DISP_NONE;
1137 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1138 insn->eaDisplacement = EA_DISP_8;
1139 if (readDisplacement(insn))
1143 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1144 insn->eaDisplacement = EA_DISP_16;
1145 if (readDisplacement(insn))
1149 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1150 if (readDisplacement(insn))
1157 insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1161 insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1164 case 0xc: /* in case REXW.b is set */
1165 insn->eaBase = (insn->addressSize == 4 ?
1166 EA_BASE_sib : EA_BASE_sib64);
1168 if (readDisplacement(insn))
1172 insn->eaBase = EA_BASE_NONE;
1173 insn->eaDisplacement = EA_DISP_32;
1174 if (readDisplacement(insn))
1178 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1184 insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1187 case 0xc: /* in case REXW.b is set */
1188 insn->eaBase = EA_BASE_sib;
1190 if (readDisplacement(insn))
1194 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1195 if (readDisplacement(insn))
1201 insn->eaDisplacement = EA_DISP_NONE;
1202 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1206 } /* switch (insn->addressSize) */
1211 #define GENERIC_FIXUP_FUNC(name, base, prefix) \
1212 static uint8_t name(struct InternalInstruction *insn, \
1219 debug("Unhandled register type"); \
1223 return base + index; \
1225 if (insn->rexPrefix && \
1226 index >= 4 && index <= 7) { \
1227 return prefix##_SPL + (index - 4); \
1229 return prefix##_AL + index; \
1232 return prefix##_AX + index; \
1234 return prefix##_EAX + index; \
1236 return prefix##_RAX + index; \
1238 return prefix##_YMM0 + index; \
1243 return prefix##_XMM0 + index; \
1249 return prefix##_MM0 + index; \
1250 case TYPE_SEGMENTREG: \
1253 return prefix##_ES + index; \
1254 case TYPE_DEBUGREG: \
1257 return prefix##_DR0 + index; \
1258 case TYPE_CONTROLREG: \
1261 return prefix##_CR0 + index; \
1266 * fixup*Value - Consults an operand type to determine the meaning of the
1267 * reg or R/M field. If the operand is an XMM operand, for example, an
1268 * operand would be XMM0 instead of AX, which readModRM() would otherwise
1269 * misinterpret it as.
1271 * @param insn - The instruction containing the operand.
1272 * @param type - The operand type.
1273 * @param index - The existing value of the field as reported by readModRM().
1274 * @param valid - The address of a uint8_t. The target is set to 1 if the
1275 * field is valid for the register class; 0 if not.
1276 * @return - The proper value.
1278 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG)
1279 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG)
1282 * fixupReg - Consults an operand specifier to determine which of the
1283 * fixup*Value functions to use in correcting readModRM()'ss interpretation.
1285 * @param insn - See fixup*Value().
1286 * @param op - The operand specifier.
1287 * @return - 0 if fixup was successful; -1 if the register returned was
1288 * invalid for its class.
1290 static int fixupReg(struct InternalInstruction *insn,
1291 const struct OperandSpecifier *op) {
1294 dbgprintf(insn, "fixupReg()");
1296 switch ((OperandEncoding)op->encoding) {
1298 debug("Expected a REG or R/M encoding in fixupReg");
1301 insn->vvvv = (Reg)fixupRegValue(insn,
1302 (OperandType)op->type,
1309 insn->reg = (Reg)fixupRegValue(insn,
1310 (OperandType)op->type,
1311 insn->reg - insn->regBase,
1317 if (insn->eaBase >= insn->eaRegBase) {
1318 insn->eaBase = (EABase)fixupRMValue(insn,
1319 (OperandType)op->type,
1320 insn->eaBase - insn->eaRegBase,
1332 * readOpcodeModifier - Reads an operand from the opcode field of an
1333 * instruction. Handles AddRegFrm instructions.
1335 * @param insn - The instruction whose opcode field is to be read.
1336 * @param inModRM - Indicates that the opcode field is to be read from the
1337 * ModR/M extension; useful for escape opcodes
1338 * @return - 0 on success; nonzero otherwise.
1340 static int readOpcodeModifier(struct InternalInstruction* insn) {
1341 dbgprintf(insn, "readOpcodeModifier()");
1343 if (insn->consumedOpcodeModifier)
1346 insn->consumedOpcodeModifier = TRUE;
1348 switch (insn->spec->modifierType) {
1350 debug("Unknown modifier type.");
1353 debug("No modifier but an operand expects one.");
1355 case MODIFIER_OPCODE:
1356 insn->opcodeModifier = insn->opcode - insn->spec->modifierBase;
1358 case MODIFIER_MODRM:
1359 insn->opcodeModifier = insn->modRM - insn->spec->modifierBase;
1365 * readOpcodeRegister - Reads an operand from the opcode field of an
1366 * instruction and interprets it appropriately given the operand width.
1367 * Handles AddRegFrm instructions.
1369 * @param insn - See readOpcodeModifier().
1370 * @param size - The width (in bytes) of the register being specified.
1371 * 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1373 * @return - 0 on success; nonzero otherwise.
1375 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1376 dbgprintf(insn, "readOpcodeRegister()");
1378 if (readOpcodeModifier(insn))
1382 size = insn->registerSize;
1386 insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1387 | insn->opcodeModifier));
1388 if (insn->rexPrefix &&
1389 insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1390 insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1391 insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1392 + (insn->opcodeRegister - MODRM_REG_AL - 4));
1397 insn->opcodeRegister = (Reg)(MODRM_REG_AX
1398 + ((bFromREX(insn->rexPrefix) << 3)
1399 | insn->opcodeModifier));
1402 insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1403 + ((bFromREX(insn->rexPrefix) << 3)
1404 | insn->opcodeModifier));
1407 insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1408 + ((bFromREX(insn->rexPrefix) << 3)
1409 | insn->opcodeModifier));
1417 * readImmediate - Consumes an immediate operand from an instruction, given the
1418 * desired operand size.
1420 * @param insn - The instruction whose operand is to be read.
1421 * @param size - The width (in bytes) of the operand.
1422 * @return - 0 if the immediate was successfully consumed; nonzero
1425 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1431 dbgprintf(insn, "readImmediate()");
1433 if (insn->numImmediatesConsumed == 2) {
1434 debug("Already consumed two immediates");
1439 size = insn->immediateSize;
1441 insn->immediateSize = size;
1442 insn->immediateOffset = insn->readerCursor - insn->startLocation;
1446 if (consumeByte(insn, &imm8))
1448 insn->immediates[insn->numImmediatesConsumed] = imm8;
1451 if (consumeUInt16(insn, &imm16))
1453 insn->immediates[insn->numImmediatesConsumed] = imm16;
1456 if (consumeUInt32(insn, &imm32))
1458 insn->immediates[insn->numImmediatesConsumed] = imm32;
1461 if (consumeUInt64(insn, &imm64))
1463 insn->immediates[insn->numImmediatesConsumed] = imm64;
1467 insn->numImmediatesConsumed++;
1473 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1475 * @param insn - The instruction whose operand is to be read.
1476 * @return - 0 if the vvvv was successfully consumed; nonzero
1479 static int readVVVV(struct InternalInstruction* insn) {
1480 dbgprintf(insn, "readVVVV()");
1482 if (insn->vexSize == 3)
1483 insn->vvvv = vvvvFromVEX3of3(insn->vexPrefix[2]);
1484 else if (insn->vexSize == 2)
1485 insn->vvvv = vvvvFromVEX2of2(insn->vexPrefix[1]);
1489 if (insn->mode != MODE_64BIT)
1496 * readOperands - Consults the specifier for an instruction and consumes all
1497 * operands for that instruction, interpreting them as it goes.
1499 * @param insn - The instruction whose operands are to be read and interpreted.
1500 * @return - 0 if all operands could be read; nonzero otherwise.
1502 static int readOperands(struct InternalInstruction* insn) {
1504 int hasVVVV, needVVVV;
1507 dbgprintf(insn, "readOperands()");
1509 /* If non-zero vvvv specified, need to make sure one of the operands
1511 hasVVVV = !readVVVV(insn);
1512 needVVVV = hasVVVV && (insn->vvvv != 0);
1514 for (index = 0; index < X86_MAX_OPERANDS; ++index) {
1515 switch (x86OperandSets[insn->spec->operands][index].encoding) {
1520 if (readModRM(insn))
1522 if (fixupReg(insn, &x86OperandSets[insn->spec->operands][index]))
1531 dbgprintf(insn, "We currently don't hande code-offset encodings");
1535 /* Saw a register immediate so don't read again and instead split the
1536 previous immediate. FIXME: This is a hack. */
1537 insn->immediates[insn->numImmediatesConsumed] =
1538 insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1539 ++insn->numImmediatesConsumed;
1542 if (readImmediate(insn, 1))
1544 if (x86OperandSets[insn->spec->operands][index].type == TYPE_IMM3 &&
1545 insn->immediates[insn->numImmediatesConsumed - 1] > 7)
1547 if (x86OperandSets[insn->spec->operands][index].type == TYPE_IMM5 &&
1548 insn->immediates[insn->numImmediatesConsumed - 1] > 31)
1550 if (x86OperandSets[insn->spec->operands][index].type == TYPE_XMM128 ||
1551 x86OperandSets[insn->spec->operands][index].type == TYPE_XMM256)
1555 if (readImmediate(insn, 2))
1559 if (readImmediate(insn, 4))
1563 if (readImmediate(insn, 8))
1567 if (readImmediate(insn, insn->immediateSize))
1571 if (readImmediate(insn, insn->addressSize))
1575 if (readOpcodeRegister(insn, 1))
1579 if (readOpcodeRegister(insn, 2))
1583 if (readOpcodeRegister(insn, 4))
1587 if (readOpcodeRegister(insn, 8))
1591 if (readOpcodeRegister(insn, 0))
1595 if (readOpcodeModifier(insn))
1599 needVVVV = 0; /* Mark that we have found a VVVV operand. */
1602 if (fixupReg(insn, &x86OperandSets[insn->spec->operands][index]))
1608 dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1613 /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1614 if (needVVVV) return -1;
1620 * decodeInstruction - Reads and interprets a full instruction provided by the
1623 * @param insn - A pointer to the instruction to be populated. Must be
1625 * @param reader - The function to be used to read the instruction's bytes.
1626 * @param readerArg - A generic argument to be passed to the reader to store
1627 * any internal state.
1628 * @param logger - If non-NULL, the function to be used to write log messages
1630 * @param loggerArg - A generic argument to be passed to the logger to store
1631 * any internal state.
1632 * @param startLoc - The address (in the reader's address space) of the first
1633 * byte in the instruction.
1634 * @param mode - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1635 * decode the instruction in.
1636 * @return - 0 if the instruction's memory could be read; nonzero if
1639 int decodeInstruction(struct InternalInstruction* insn,
1640 byteReader_t reader,
1641 const void* readerArg,
1646 DisassemblerMode mode) {
1647 memset(insn, 0, sizeof(struct InternalInstruction));
1649 insn->reader = reader;
1650 insn->readerArg = readerArg;
1651 insn->dlog = logger;
1652 insn->dlogArg = loggerArg;
1653 insn->startLocation = startLoc;
1654 insn->readerCursor = startLoc;
1656 insn->numImmediatesConsumed = 0;
1658 if (readPrefixes(insn) ||
1660 getID(insn, miiArg) ||
1661 insn->instructionID == 0 ||
1665 insn->operands = &x86OperandSets[insn->spec->operands][0];
1667 insn->length = insn->readerCursor - insn->startLocation;
1669 dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1670 startLoc, insn->readerCursor, insn->length);
1672 if (insn->length > 15)
1673 dbgprintf(insn, "Instruction exceeds 15-byte limit");