1 //===-- X86DisassemblerDecoder.cpp - Disassembler decoder -----------------===//
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 <cstdarg> /* for va_*() */
17 #include <cstdio> /* for vsnprintf() */
18 #include <cstdlib> /* for exit() */
19 #include <cstring> /* for memset() */
21 #include "X86DisassemblerDecoder.h"
23 using namespace llvm::X86Disassembler;
25 /// Specifies whether a ModR/M byte is needed and (if so) which
26 /// instruction each possible value of the ModR/M byte corresponds to. Once
27 /// this information is known, we have narrowed down to a single instruction.
28 struct ModRMDecision {
30 uint16_t instructionIDs;
33 /// Specifies which set of ModR/M->instruction tables to look at
34 /// given a particular opcode.
35 struct OpcodeDecision {
36 ModRMDecision modRMDecisions[256];
39 /// Specifies which opcode->instruction tables to look at given
40 /// a particular context (set of attributes). Since there are many possible
41 /// contexts, the decoder first uses CONTEXTS_SYM to determine which context
42 /// applies given a specific set of attributes. Hence there are only IC_max
43 /// entries in this table, rather than 2^(ATTR_max).
44 struct ContextDecision {
45 OpcodeDecision opcodeDecisions[IC_max];
48 #include "X86GenDisassemblerTables.inc"
51 #define debug(s) do { Debug(__FILE__, __LINE__, s); } while (0)
53 #define debug(s) do { } while (0)
58 * contextForAttrs - Client for the instruction context table. Takes a set of
59 * attributes and returns the appropriate decode context.
61 * @param attrMask - Attributes, from the enumeration attributeBits.
62 * @return - The InstructionContext to use when looking up an
63 * an instruction with these attributes.
65 static InstructionContext contextForAttrs(uint16_t attrMask) {
66 return static_cast<InstructionContext>(CONTEXTS_SYM[attrMask]);
70 * modRMRequired - Reads the appropriate instruction table to determine whether
71 * the ModR/M byte is required to decode a particular instruction.
73 * @param type - The opcode type (i.e., how many bytes it has).
74 * @param insnContext - The context for the instruction, as returned by
76 * @param opcode - The last byte of the instruction's opcode, not counting
77 * ModR/M extensions and escapes.
78 * @return - true if the ModR/M byte is required, false otherwise.
80 static int modRMRequired(OpcodeType type,
81 InstructionContext insnContext,
83 const struct ContextDecision* decision = nullptr;
87 decision = &ONEBYTE_SYM;
90 decision = &TWOBYTE_SYM;
93 decision = &THREEBYTE38_SYM;
96 decision = &THREEBYTE3A_SYM;
99 decision = &XOP8_MAP_SYM;
102 decision = &XOP9_MAP_SYM;
105 decision = &XOPA_MAP_SYM;
109 return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].
110 modrm_type != MODRM_ONEENTRY;
114 * decode - Reads the appropriate instruction table to obtain the unique ID of
117 * @param type - See modRMRequired().
118 * @param insnContext - See modRMRequired().
119 * @param opcode - See modRMRequired().
120 * @param modRM - The ModR/M byte if required, or any value if not.
121 * @return - The UID of the instruction, or 0 on failure.
123 static InstrUID decode(OpcodeType type,
124 InstructionContext insnContext,
127 const struct ModRMDecision* dec = nullptr;
131 dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
134 dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
137 dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
140 dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
143 dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
146 dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
149 dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
153 switch (dec->modrm_type) {
155 debug("Corrupt table! Unknown modrm_type");
158 return modRMTable[dec->instructionIDs];
160 if (modFromModRM(modRM) == 0x3)
161 return modRMTable[dec->instructionIDs+1];
162 return modRMTable[dec->instructionIDs];
164 if (modFromModRM(modRM) == 0x3)
165 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)+8];
166 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
167 case MODRM_SPLITMISC:
168 if (modFromModRM(modRM) == 0x3)
169 return modRMTable[dec->instructionIDs+(modRM & 0x3f)+8];
170 return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
172 return modRMTable[dec->instructionIDs+modRM];
177 * specifierForUID - Given a UID, returns the name and operand specification for
180 * @param uid - The unique ID for the instruction. This should be returned by
181 * decode(); specifierForUID will not check bounds.
182 * @return - A pointer to the specification for that instruction.
184 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
185 return &INSTRUCTIONS_SYM[uid];
189 * consumeByte - Uses the reader function provided by the user to consume one
190 * byte from the instruction's memory and advance the cursor.
192 * @param insn - The instruction with the reader function to use. The cursor
193 * for this instruction is advanced.
194 * @param byte - A pointer to a pre-allocated memory buffer to be populated
195 * with the data read.
196 * @return - 0 if the read was successful; nonzero otherwise.
198 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
199 int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
202 ++(insn->readerCursor);
208 * lookAtByte - Like consumeByte, but does not advance the cursor.
210 * @param insn - See consumeByte().
211 * @param byte - See consumeByte().
212 * @return - See consumeByte().
214 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
215 return insn->reader(insn->readerArg, byte, insn->readerCursor);
218 static void unconsumeByte(struct InternalInstruction* insn) {
219 insn->readerCursor--;
222 #define CONSUME_FUNC(name, type) \
223 static int name(struct InternalInstruction* insn, type* ptr) { \
226 for (offset = 0; offset < sizeof(type); ++offset) { \
228 int ret = insn->reader(insn->readerArg, \
230 insn->readerCursor + offset); \
233 combined = combined | ((uint64_t)byte << (offset * 8)); \
236 insn->readerCursor += sizeof(type); \
241 * consume* - Use the reader function provided by the user to consume data
242 * values of various sizes from the instruction's memory and advance the
243 * cursor appropriately. These readers perform endian conversion.
245 * @param insn - See consumeByte().
246 * @param ptr - A pointer to a pre-allocated memory of appropriate size to
247 * be populated with the data read.
248 * @return - See consumeByte().
250 CONSUME_FUNC(consumeInt8, int8_t)
251 CONSUME_FUNC(consumeInt16, int16_t)
252 CONSUME_FUNC(consumeInt32, int32_t)
253 CONSUME_FUNC(consumeUInt16, uint16_t)
254 CONSUME_FUNC(consumeUInt32, uint32_t)
255 CONSUME_FUNC(consumeUInt64, uint64_t)
258 * dbgprintf - Uses the logging function provided by the user to log a single
259 * message, typically without a carriage-return.
261 * @param insn - The instruction containing the logging function.
262 * @param format - See printf().
263 * @param ... - See printf().
265 static void dbgprintf(struct InternalInstruction* insn,
274 va_start(ap, format);
275 (void)vsnprintf(buffer, sizeof(buffer), format, ap);
278 insn->dlog(insn->dlogArg, buffer);
284 * setPrefixPresent - Marks that a particular prefix is present at a particular
287 * @param insn - The instruction to be marked as having the prefix.
288 * @param prefix - The prefix that is present.
289 * @param location - The location where the prefix is located (in the address
290 * space of the instruction's reader).
292 static void setPrefixPresent(struct InternalInstruction* insn,
296 insn->prefixPresent[prefix] = 1;
297 insn->prefixLocations[prefix] = location;
301 * isPrefixAtLocation - Queries an instruction to determine whether a prefix is
302 * present at a given location.
304 * @param insn - The instruction to be queried.
305 * @param prefix - The prefix.
306 * @param location - The location to query.
307 * @return - Whether the prefix is at that location.
309 static bool isPrefixAtLocation(struct InternalInstruction* insn,
313 return insn->prefixPresent[prefix] == 1 &&
314 insn->prefixLocations[prefix] == location;
318 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
319 * instruction as having them. Also sets the instruction's default operand,
320 * address, and other relevant data sizes to report operands correctly.
322 * @param insn - The instruction whose prefixes are to be read.
323 * @return - 0 if the instruction could be read until the end of the prefix
324 * bytes, and no prefixes conflicted; nonzero otherwise.
326 static int readPrefixes(struct InternalInstruction* insn) {
327 bool isPrefix = true;
328 bool prefixGroups[4] = { false };
329 uint64_t prefixLocation;
333 bool hasAdSize = false;
334 bool hasOpSize = false;
336 dbgprintf(insn, "readPrefixes()");
339 prefixLocation = insn->readerCursor;
341 /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
342 if (consumeByte(insn, &byte))
346 * If the byte is a LOCK/REP/REPNE prefix and not a part of the opcode, then
347 * break and let it be disassembled as a normal "instruction".
349 if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0)
352 if (insn->readerCursor - 1 == insn->startLocation
353 && (byte == 0xf2 || byte == 0xf3)
354 && !lookAtByte(insn, &nextByte))
357 * If the byte is 0xf2 or 0xf3, and any of the following conditions are
359 * - it is followed by a LOCK (0xf0) prefix
360 * - it is followed by an xchg instruction
361 * then it should be disassembled as a xacquire/xrelease not repne/rep.
363 if ((byte == 0xf2 || byte == 0xf3) &&
364 ((nextByte == 0xf0) |
365 ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90)))
366 insn->xAcquireRelease = true;
368 * Also if the byte is 0xf3, and the following condition is met:
369 * - it is followed by a "mov mem, reg" (opcode 0x88/0x89) or
370 * "mov mem, imm" (opcode 0xc6/0xc7) instructions.
371 * then it should be disassembled as an xrelease not rep.
374 (nextByte == 0x88 || nextByte == 0x89 ||
375 nextByte == 0xc6 || nextByte == 0xc7))
376 insn->xAcquireRelease = true;
377 if (insn->mode == MODE_64BIT && (nextByte & 0xf0) == 0x40) {
378 if (consumeByte(insn, &nextByte))
380 if (lookAtByte(insn, &nextByte))
384 if (nextByte != 0x0f && nextByte != 0x90)
389 case 0xf0: /* LOCK */
390 case 0xf2: /* REPNE/REPNZ */
391 case 0xf3: /* REP or REPE/REPZ */
393 dbgprintf(insn, "Redundant Group 1 prefix");
394 prefixGroups[0] = true;
395 setPrefixPresent(insn, byte, prefixLocation);
397 case 0x2e: /* CS segment override -OR- Branch not taken */
398 case 0x36: /* SS segment override -OR- Branch taken */
399 case 0x3e: /* DS segment override */
400 case 0x26: /* ES segment override */
401 case 0x64: /* FS segment override */
402 case 0x65: /* GS segment override */
405 insn->segmentOverride = SEG_OVERRIDE_CS;
408 insn->segmentOverride = SEG_OVERRIDE_SS;
411 insn->segmentOverride = SEG_OVERRIDE_DS;
414 insn->segmentOverride = SEG_OVERRIDE_ES;
417 insn->segmentOverride = SEG_OVERRIDE_FS;
420 insn->segmentOverride = SEG_OVERRIDE_GS;
423 debug("Unhandled override");
427 dbgprintf(insn, "Redundant Group 2 prefix");
428 prefixGroups[1] = true;
429 setPrefixPresent(insn, byte, prefixLocation);
431 case 0x66: /* Operand-size override */
433 dbgprintf(insn, "Redundant Group 3 prefix");
434 prefixGroups[2] = true;
436 setPrefixPresent(insn, byte, prefixLocation);
438 case 0x67: /* Address-size override */
440 dbgprintf(insn, "Redundant Group 4 prefix");
441 prefixGroups[3] = true;
443 setPrefixPresent(insn, byte, prefixLocation);
445 default: /* Not a prefix byte */
451 dbgprintf(insn, "Found prefix 0x%hhx", byte);
454 insn->vectorExtensionType = TYPE_NO_VEX_XOP;
457 uint8_t byte1, byte2;
459 if (consumeByte(insn, &byte1)) {
460 dbgprintf(insn, "Couldn't read second byte of EVEX prefix");
464 if (lookAtByte(insn, &byte2)) {
465 dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
469 if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
470 ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
471 insn->vectorExtensionType = TYPE_EVEX;
473 unconsumeByte(insn); /* unconsume byte1 */
474 unconsumeByte(insn); /* unconsume byte */
475 insn->necessaryPrefixLocation = insn->readerCursor - 2;
478 if (insn->vectorExtensionType == TYPE_EVEX) {
479 insn->vectorExtensionPrefix[0] = byte;
480 insn->vectorExtensionPrefix[1] = byte1;
481 if (consumeByte(insn, &insn->vectorExtensionPrefix[2])) {
482 dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
485 if (consumeByte(insn, &insn->vectorExtensionPrefix[3])) {
486 dbgprintf(insn, "Couldn't read fourth byte of EVEX prefix");
490 /* We simulate the REX prefix for simplicity's sake */
491 if (insn->mode == MODE_64BIT) {
492 insn->rexPrefix = 0x40
493 | (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3)
494 | (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2)
495 | (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1)
496 | (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
499 dbgprintf(insn, "Found EVEX prefix 0x%hhx 0x%hhx 0x%hhx 0x%hhx",
500 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
501 insn->vectorExtensionPrefix[2], insn->vectorExtensionPrefix[3]);
503 } else if (byte == 0xc4) {
506 if (lookAtByte(insn, &byte1)) {
507 dbgprintf(insn, "Couldn't read second byte of VEX");
511 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
512 insn->vectorExtensionType = TYPE_VEX_3B;
513 insn->necessaryPrefixLocation = insn->readerCursor - 1;
516 insn->necessaryPrefixLocation = insn->readerCursor - 1;
519 if (insn->vectorExtensionType == TYPE_VEX_3B) {
520 insn->vectorExtensionPrefix[0] = byte;
521 consumeByte(insn, &insn->vectorExtensionPrefix[1]);
522 consumeByte(insn, &insn->vectorExtensionPrefix[2]);
524 /* We simulate the REX prefix for simplicity's sake */
526 if (insn->mode == MODE_64BIT) {
527 insn->rexPrefix = 0x40
528 | (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3)
529 | (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2)
530 | (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1)
531 | (bFromVEX2of3(insn->vectorExtensionPrefix[1]) << 0);
534 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx",
535 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
536 insn->vectorExtensionPrefix[2]);
538 } else if (byte == 0xc5) {
541 if (lookAtByte(insn, &byte1)) {
542 dbgprintf(insn, "Couldn't read second byte of VEX");
546 if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
547 insn->vectorExtensionType = TYPE_VEX_2B;
552 if (insn->vectorExtensionType == TYPE_VEX_2B) {
553 insn->vectorExtensionPrefix[0] = byte;
554 consumeByte(insn, &insn->vectorExtensionPrefix[1]);
556 if (insn->mode == MODE_64BIT) {
557 insn->rexPrefix = 0x40
558 | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
561 switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
569 dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx",
570 insn->vectorExtensionPrefix[0],
571 insn->vectorExtensionPrefix[1]);
573 } else if (byte == 0x8f) {
576 if (lookAtByte(insn, &byte1)) {
577 dbgprintf(insn, "Couldn't read second byte of XOP");
581 if ((byte1 & 0x38) != 0x0) { /* 0 in these 3 bits is a POP instruction. */
582 insn->vectorExtensionType = TYPE_XOP;
583 insn->necessaryPrefixLocation = insn->readerCursor - 1;
586 insn->necessaryPrefixLocation = insn->readerCursor - 1;
589 if (insn->vectorExtensionType == TYPE_XOP) {
590 insn->vectorExtensionPrefix[0] = byte;
591 consumeByte(insn, &insn->vectorExtensionPrefix[1]);
592 consumeByte(insn, &insn->vectorExtensionPrefix[2]);
594 /* We simulate the REX prefix for simplicity's sake */
596 if (insn->mode == MODE_64BIT) {
597 insn->rexPrefix = 0x40
598 | (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3)
599 | (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2)
600 | (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1)
601 | (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
604 switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
612 dbgprintf(insn, "Found XOP prefix 0x%hhx 0x%hhx 0x%hhx",
613 insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
614 insn->vectorExtensionPrefix[2]);
617 if (insn->mode == MODE_64BIT) {
618 if ((byte & 0xf0) == 0x40) {
621 if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
622 dbgprintf(insn, "Redundant REX prefix");
626 insn->rexPrefix = byte;
627 insn->necessaryPrefixLocation = insn->readerCursor - 2;
629 dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
632 insn->necessaryPrefixLocation = insn->readerCursor - 1;
636 insn->necessaryPrefixLocation = insn->readerCursor - 1;
640 if (insn->mode == MODE_16BIT) {
641 insn->registerSize = (hasOpSize ? 4 : 2);
642 insn->addressSize = (hasAdSize ? 4 : 2);
643 insn->displacementSize = (hasAdSize ? 4 : 2);
644 insn->immediateSize = (hasOpSize ? 4 : 2);
645 } else if (insn->mode == MODE_32BIT) {
646 insn->registerSize = (hasOpSize ? 2 : 4);
647 insn->addressSize = (hasAdSize ? 2 : 4);
648 insn->displacementSize = (hasAdSize ? 2 : 4);
649 insn->immediateSize = (hasOpSize ? 2 : 4);
650 } else if (insn->mode == MODE_64BIT) {
651 if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
652 insn->registerSize = 8;
653 insn->addressSize = (hasAdSize ? 4 : 8);
654 insn->displacementSize = 4;
655 insn->immediateSize = 4;
656 } else if (insn->rexPrefix) {
657 insn->registerSize = (hasOpSize ? 2 : 4);
658 insn->addressSize = (hasAdSize ? 4 : 8);
659 insn->displacementSize = (hasOpSize ? 2 : 4);
660 insn->immediateSize = (hasOpSize ? 2 : 4);
662 insn->registerSize = (hasOpSize ? 2 : 4);
663 insn->addressSize = (hasAdSize ? 4 : 8);
664 insn->displacementSize = (hasOpSize ? 2 : 4);
665 insn->immediateSize = (hasOpSize ? 2 : 4);
673 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
674 * extended or escape opcodes).
676 * @param insn - The instruction whose opcode is to be read.
677 * @return - 0 if the opcode could be read successfully; nonzero otherwise.
679 static int readOpcode(struct InternalInstruction* insn) {
680 /* Determine the length of the primary opcode */
684 dbgprintf(insn, "readOpcode()");
686 insn->opcodeType = ONEBYTE;
688 if (insn->vectorExtensionType == TYPE_EVEX) {
689 switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
691 dbgprintf(insn, "Unhandled mm field for instruction (0x%hhx)",
692 mmFromEVEX2of4(insn->vectorExtensionPrefix[1]));
695 insn->opcodeType = TWOBYTE;
696 return consumeByte(insn, &insn->opcode);
698 insn->opcodeType = THREEBYTE_38;
699 return consumeByte(insn, &insn->opcode);
701 insn->opcodeType = THREEBYTE_3A;
702 return consumeByte(insn, &insn->opcode);
704 } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
705 switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
707 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
708 mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
711 insn->opcodeType = TWOBYTE;
712 return consumeByte(insn, &insn->opcode);
714 insn->opcodeType = THREEBYTE_38;
715 return consumeByte(insn, &insn->opcode);
717 insn->opcodeType = THREEBYTE_3A;
718 return consumeByte(insn, &insn->opcode);
720 } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
721 insn->opcodeType = TWOBYTE;
722 return consumeByte(insn, &insn->opcode);
723 } else if (insn->vectorExtensionType == TYPE_XOP) {
724 switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
726 dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
727 mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
729 case XOP_MAP_SELECT_8:
730 insn->opcodeType = XOP8_MAP;
731 return consumeByte(insn, &insn->opcode);
732 case XOP_MAP_SELECT_9:
733 insn->opcodeType = XOP9_MAP;
734 return consumeByte(insn, &insn->opcode);
735 case XOP_MAP_SELECT_A:
736 insn->opcodeType = XOPA_MAP;
737 return consumeByte(insn, &insn->opcode);
741 if (consumeByte(insn, ¤t))
744 if (current == 0x0f) {
745 dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
747 if (consumeByte(insn, ¤t))
750 if (current == 0x38) {
751 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
753 if (consumeByte(insn, ¤t))
756 insn->opcodeType = THREEBYTE_38;
757 } else if (current == 0x3a) {
758 dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
760 if (consumeByte(insn, ¤t))
763 insn->opcodeType = THREEBYTE_3A;
765 dbgprintf(insn, "Didn't find a three-byte escape prefix");
767 insn->opcodeType = TWOBYTE;
772 * At this point we have consumed the full opcode.
773 * Anything we consume from here on must be unconsumed.
776 insn->opcode = current;
781 static int readModRM(struct InternalInstruction* insn);
784 * getIDWithAttrMask - Determines the ID of an instruction, consuming
785 * the ModR/M byte as appropriate for extended and escape opcodes,
786 * and using a supplied attribute mask.
788 * @param instructionID - A pointer whose target is filled in with the ID of the
790 * @param insn - The instruction whose ID is to be determined.
791 * @param attrMask - The attribute mask to search.
792 * @return - 0 if the ModR/M could be read when needed or was not
793 * needed; nonzero otherwise.
795 static int getIDWithAttrMask(uint16_t* instructionID,
796 struct InternalInstruction* insn,
798 bool hasModRMExtension;
800 InstructionContext instructionClass = contextForAttrs(attrMask);
802 hasModRMExtension = modRMRequired(insn->opcodeType,
806 if (hasModRMExtension) {
810 *instructionID = decode(insn->opcodeType,
815 *instructionID = decode(insn->opcodeType,
825 * is16BitEquivalent - Determines whether two instruction names refer to
826 * equivalent instructions but one is 16-bit whereas the other is not.
828 * @param orig - The instruction that is not 16-bit
829 * @param equiv - The instruction that is 16-bit
831 static bool is16BitEquivalent(const char* orig, const char* equiv) {
835 if (orig[i] == '\0' && equiv[i] == '\0')
837 if (orig[i] == '\0' || equiv[i] == '\0')
839 if (orig[i] != equiv[i]) {
840 if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
842 if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
844 if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
852 * is64Bit - Determines whether this instruction is a 64-bit instruction.
854 * @param name - The instruction that is not 16-bit
856 static bool is64Bit(const char* name) {
862 if (name[i] == '6' && name[i+1] == '4')
868 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
869 * appropriate for extended and escape opcodes. Determines the attributes and
870 * context for the instruction before doing so.
872 * @param insn - The instruction whose ID is to be determined.
873 * @return - 0 if the ModR/M could be read when needed or was not needed;
876 static int getID(struct InternalInstruction* insn, const void *miiArg) {
878 uint16_t instructionID;
880 dbgprintf(insn, "getID()");
882 attrMask = ATTR_NONE;
884 if (insn->mode == MODE_64BIT)
885 attrMask |= ATTR_64BIT;
887 if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
888 attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
890 if (insn->vectorExtensionType == TYPE_EVEX) {
891 switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
893 attrMask |= ATTR_OPSIZE;
903 if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
904 attrMask |= ATTR_EVEXKZ;
905 if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
906 attrMask |= ATTR_EVEXB;
907 if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
908 attrMask |= ATTR_EVEXK;
909 if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
910 attrMask |= ATTR_EVEXL;
911 if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
912 attrMask |= ATTR_EVEXL2;
913 } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
914 switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
916 attrMask |= ATTR_OPSIZE;
926 if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
927 attrMask |= ATTR_VEXL;
928 } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
929 switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
931 attrMask |= ATTR_OPSIZE;
941 if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
942 attrMask |= ATTR_VEXL;
943 } else if (insn->vectorExtensionType == TYPE_XOP) {
944 switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
946 attrMask |= ATTR_OPSIZE;
956 if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
957 attrMask |= ATTR_VEXL;
962 if (insn->mode != MODE_16BIT && isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
963 attrMask |= ATTR_OPSIZE;
964 else if (isPrefixAtLocation(insn, 0x67, insn->necessaryPrefixLocation))
965 attrMask |= ATTR_ADSIZE;
966 else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
968 else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
972 if (insn->rexPrefix & 0x08)
973 attrMask |= ATTR_REXW;
976 * JCXZ/JECXZ need special handling for 16-bit mode because the meaning
977 * of the AdSize prefix is inverted w.r.t. 32-bit mode.
979 if (insn->mode == MODE_16BIT && insn->opcodeType == ONEBYTE &&
980 insn->opcode == 0xE3)
981 attrMask ^= ATTR_ADSIZE;
984 * In 64-bit mode all f64 superscripted opcodes ignore opcode size prefix
985 * CALL/JMP/JCC instructions need to ignore 0x66 and consume 4 bytes
988 if (insn->mode == MODE_64BIT &&
989 isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation)) {
990 switch (insn->opcode) {
993 // Take care of psubsb and other mmx instructions.
994 if (insn->opcodeType == ONEBYTE) {
995 attrMask ^= ATTR_OPSIZE;
996 insn->immediateSize = 4;
997 insn->displacementSize = 4;
1014 // Take care of lea and three byte ops.
1015 if (insn->opcodeType == TWOBYTE) {
1016 attrMask ^= ATTR_OPSIZE;
1017 insn->immediateSize = 4;
1018 insn->displacementSize = 4;
1024 if (getIDWithAttrMask(&instructionID, insn, attrMask))
1027 /* The following clauses compensate for limitations of the tables. */
1029 if (insn->mode != MODE_64BIT &&
1030 insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
1032 * The tables can't distinquish between cases where the W-bit is used to
1033 * select register size and cases where its a required part of the opcode.
1035 if ((insn->vectorExtensionType == TYPE_EVEX &&
1036 wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
1037 (insn->vectorExtensionType == TYPE_VEX_3B &&
1038 wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
1039 (insn->vectorExtensionType == TYPE_XOP &&
1040 wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1042 uint16_t instructionIDWithREXW;
1043 if (getIDWithAttrMask(&instructionIDWithREXW,
1044 insn, attrMask | ATTR_REXW)) {
1045 insn->instructionID = instructionID;
1046 insn->spec = specifierForUID(instructionID);
1050 const char *SpecName = GetInstrName(instructionIDWithREXW, miiArg);
1051 // If not a 64-bit instruction. Switch the opcode.
1052 if (!is64Bit(SpecName)) {
1053 insn->instructionID = instructionIDWithREXW;
1054 insn->spec = specifierForUID(instructionIDWithREXW);
1061 * Absolute moves need special handling.
1062 * -For 16-bit mode because the meaning of the AdSize and OpSize prefixes are
1064 * -For 32-bit mode we need to ensure the ADSIZE prefix is observed in
1067 if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) {
1068 /* Make sure we observed the prefixes in any position. */
1069 if (insn->prefixPresent[0x67])
1070 attrMask |= ATTR_ADSIZE;
1071 if (insn->prefixPresent[0x66])
1072 attrMask |= ATTR_OPSIZE;
1074 /* In 16-bit, invert the attributes. */
1075 if (insn->mode == MODE_16BIT)
1076 attrMask ^= ATTR_ADSIZE | ATTR_OPSIZE;
1078 if (getIDWithAttrMask(&instructionID, insn, attrMask))
1081 insn->instructionID = instructionID;
1082 insn->spec = specifierForUID(instructionID);
1086 if ((insn->mode == MODE_16BIT || insn->prefixPresent[0x66]) &&
1087 !(attrMask & ATTR_OPSIZE)) {
1089 * The instruction tables make no distinction between instructions that
1090 * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
1091 * particular spot (i.e., many MMX operations). In general we're
1092 * conservative, but in the specific case where OpSize is present but not
1093 * in the right place we check if there's a 16-bit operation.
1096 const struct InstructionSpecifier *spec;
1097 uint16_t instructionIDWithOpsize;
1098 const char *specName, *specWithOpSizeName;
1100 spec = specifierForUID(instructionID);
1102 if (getIDWithAttrMask(&instructionIDWithOpsize,
1104 attrMask | ATTR_OPSIZE)) {
1106 * ModRM required with OpSize but not present; give up and return version
1107 * without OpSize set
1110 insn->instructionID = instructionID;
1115 specName = GetInstrName(instructionID, miiArg);
1116 specWithOpSizeName = GetInstrName(instructionIDWithOpsize, miiArg);
1118 if (is16BitEquivalent(specName, specWithOpSizeName) &&
1119 (insn->mode == MODE_16BIT) ^ insn->prefixPresent[0x66]) {
1120 insn->instructionID = instructionIDWithOpsize;
1121 insn->spec = specifierForUID(instructionIDWithOpsize);
1123 insn->instructionID = instructionID;
1129 if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1130 insn->rexPrefix & 0x01) {
1132 * NOOP shouldn't decode as NOOP if REX.b is set. Instead
1133 * it should decode as XCHG %r8, %eax.
1136 const struct InstructionSpecifier *spec;
1137 uint16_t instructionIDWithNewOpcode;
1138 const struct InstructionSpecifier *specWithNewOpcode;
1140 spec = specifierForUID(instructionID);
1142 /* Borrow opcode from one of the other XCHGar opcodes */
1143 insn->opcode = 0x91;
1145 if (getIDWithAttrMask(&instructionIDWithNewOpcode,
1148 insn->opcode = 0x90;
1150 insn->instructionID = instructionID;
1155 specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
1158 insn->opcode = 0x90;
1160 insn->instructionID = instructionIDWithNewOpcode;
1161 insn->spec = specWithNewOpcode;
1166 insn->instructionID = instructionID;
1167 insn->spec = specifierForUID(insn->instructionID);
1173 * readSIB - Consumes the SIB byte to determine addressing information for an
1176 * @param insn - The instruction whose SIB byte is to be read.
1177 * @return - 0 if the SIB byte was successfully read; nonzero otherwise.
1179 static int readSIB(struct InternalInstruction* insn) {
1180 SIBIndex sibIndexBase = SIB_INDEX_NONE;
1181 SIBBase sibBaseBase = SIB_BASE_NONE;
1182 uint8_t index, base;
1184 dbgprintf(insn, "readSIB()");
1186 if (insn->consumedSIB)
1189 insn->consumedSIB = true;
1191 switch (insn->addressSize) {
1193 dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
1196 sibIndexBase = SIB_INDEX_EAX;
1197 sibBaseBase = SIB_BASE_EAX;
1200 sibIndexBase = SIB_INDEX_RAX;
1201 sibBaseBase = SIB_BASE_RAX;
1205 if (consumeByte(insn, &insn->sib))
1208 index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1210 // FIXME: The fifth bit (bit index 4) is only to be used for instructions
1211 // that understand VSIB indexing. ORing the bit in here is mildy dangerous
1212 // because performing math on an 'enum SIBIndex' can produce garbage.
1213 // Excluding the "none" value, it should cover 6 spaces of register names:
1214 // - 16 possibilities for 16-bit GPR starting at SIB_INDEX_BX_SI
1215 // - 16 possibilities for 32-bit GPR starting at SIB_INDEX_EAX
1216 // - 16 possibilities for 64-bit GPR starting at SIB_INDEX_RAX
1217 // - 32 possibilities for each of XMM, YMM, ZMM registers
1218 // When sibIndexBase gets assigned SIB_INDEX_RAX as it does in 64-bit mode,
1219 // summing in a fully decoded index between 0 and 31 can end up with a value
1220 // that looks like something in the low half of the XMM range.
1221 // translateRMMemory() tries to reverse the damage, with only partial success,
1222 // as evidenced by known bugs in "test/MC/Disassembler/X86/x86-64.txt"
1223 if (insn->vectorExtensionType == TYPE_EVEX)
1224 index |= v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4;
1227 insn->sibIndex = SIB_INDEX_NONE;
1229 insn->sibIndex = (SIBIndex)(sibIndexBase + index);
1232 insn->sibScale = 1 << scaleFromSIB(insn->sib);
1234 base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1239 switch (modFromModRM(insn->modRM)) {
1241 insn->eaDisplacement = EA_DISP_32;
1242 insn->sibBase = SIB_BASE_NONE;
1245 insn->eaDisplacement = EA_DISP_8;
1246 insn->sibBase = (SIBBase)(sibBaseBase + base);
1249 insn->eaDisplacement = EA_DISP_32;
1250 insn->sibBase = (SIBBase)(sibBaseBase + base);
1253 debug("Cannot have Mod = 0b11 and a SIB byte");
1258 insn->sibBase = (SIBBase)(sibBaseBase + base);
1266 * readDisplacement - Consumes the displacement of an instruction.
1268 * @param insn - The instruction whose displacement is to be read.
1269 * @return - 0 if the displacement byte was successfully read; nonzero
1272 static int readDisplacement(struct InternalInstruction* insn) {
1277 dbgprintf(insn, "readDisplacement()");
1279 if (insn->consumedDisplacement)
1282 insn->consumedDisplacement = true;
1283 insn->displacementOffset = insn->readerCursor - insn->startLocation;
1285 switch (insn->eaDisplacement) {
1287 insn->consumedDisplacement = false;
1290 if (consumeInt8(insn, &d8))
1292 insn->displacement = d8;
1295 if (consumeInt16(insn, &d16))
1297 insn->displacement = d16;
1300 if (consumeInt32(insn, &d32))
1302 insn->displacement = d32;
1306 insn->consumedDisplacement = true;
1311 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1312 * displacement) for an instruction and interprets it.
1314 * @param insn - The instruction whose addressing information is to be read.
1315 * @return - 0 if the information was successfully read; nonzero otherwise.
1317 static int readModRM(struct InternalInstruction* insn) {
1318 uint8_t mod, rm, reg;
1320 dbgprintf(insn, "readModRM()");
1322 if (insn->consumedModRM)
1325 if (consumeByte(insn, &insn->modRM))
1327 insn->consumedModRM = true;
1329 mod = modFromModRM(insn->modRM);
1330 rm = rmFromModRM(insn->modRM);
1331 reg = regFromModRM(insn->modRM);
1334 * This goes by insn->registerSize to pick the correct register, which messes
1335 * up if we're using (say) XMM or 8-bit register operands. That gets fixed in
1338 switch (insn->registerSize) {
1340 insn->regBase = MODRM_REG_AX;
1341 insn->eaRegBase = EA_REG_AX;
1344 insn->regBase = MODRM_REG_EAX;
1345 insn->eaRegBase = EA_REG_EAX;
1348 insn->regBase = MODRM_REG_RAX;
1349 insn->eaRegBase = EA_REG_RAX;
1353 reg |= rFromREX(insn->rexPrefix) << 3;
1354 rm |= bFromREX(insn->rexPrefix) << 3;
1355 if (insn->vectorExtensionType == TYPE_EVEX) {
1356 reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1357 rm |= xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1360 insn->reg = (Reg)(insn->regBase + reg);
1362 switch (insn->addressSize) {
1364 insn->eaBaseBase = EA_BASE_BX_SI;
1369 insn->eaBase = EA_BASE_NONE;
1370 insn->eaDisplacement = EA_DISP_16;
1371 if (readDisplacement(insn))
1374 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1375 insn->eaDisplacement = EA_DISP_NONE;
1379 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1380 insn->eaDisplacement = EA_DISP_8;
1381 insn->displacementSize = 1;
1382 if (readDisplacement(insn))
1386 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1387 insn->eaDisplacement = EA_DISP_16;
1388 if (readDisplacement(insn))
1392 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1393 if (readDisplacement(insn))
1400 insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1404 insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1405 // In determining whether RIP-relative mode is used (rm=5),
1406 // or whether a SIB byte is present (rm=4),
1407 // the extension bits (REX.b and EVEX.x) are ignored.
1409 case 0x4: // SIB byte is present
1410 insn->eaBase = (insn->addressSize == 4 ?
1411 EA_BASE_sib : EA_BASE_sib64);
1412 if (readSIB(insn) || readDisplacement(insn))
1415 case 0x5: // RIP-relative
1416 insn->eaBase = EA_BASE_NONE;
1417 insn->eaDisplacement = EA_DISP_32;
1418 if (readDisplacement(insn))
1422 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1427 insn->displacementSize = 1;
1430 insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1432 case 0x4: // SIB byte is present
1433 insn->eaBase = EA_BASE_sib;
1434 if (readSIB(insn) || readDisplacement(insn))
1438 insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1439 if (readDisplacement(insn))
1445 insn->eaDisplacement = EA_DISP_NONE;
1446 insn->eaBase = (EABase)(insn->eaRegBase + rm);
1450 } /* switch (insn->addressSize) */
1455 #define GENERIC_FIXUP_FUNC(name, base, prefix) \
1456 static uint8_t name(struct InternalInstruction *insn, \
1463 debug("Unhandled register type"); \
1467 return base + index; \
1469 if (insn->rexPrefix && \
1470 index >= 4 && index <= 7) { \
1471 return prefix##_SPL + (index - 4); \
1473 return prefix##_AL + index; \
1476 return prefix##_AX + index; \
1478 return prefix##_EAX + index; \
1480 return prefix##_RAX + index; \
1482 return prefix##_ZMM0 + index; \
1484 return prefix##_YMM0 + index; \
1489 return prefix##_XMM0 + index; \
1495 return prefix##_K0 + index; \
1497 return prefix##_MM0 + (index & 0x7); \
1498 case TYPE_SEGMENTREG: \
1501 return prefix##_ES + index; \
1502 case TYPE_DEBUGREG: \
1503 return prefix##_DR0 + index; \
1504 case TYPE_CONTROLREG: \
1505 return prefix##_CR0 + index; \
1510 * fixup*Value - Consults an operand type to determine the meaning of the
1511 * reg or R/M field. If the operand is an XMM operand, for example, an
1512 * operand would be XMM0 instead of AX, which readModRM() would otherwise
1513 * misinterpret it as.
1515 * @param insn - The instruction containing the operand.
1516 * @param type - The operand type.
1517 * @param index - The existing value of the field as reported by readModRM().
1518 * @param valid - The address of a uint8_t. The target is set to 1 if the
1519 * field is valid for the register class; 0 if not.
1520 * @return - The proper value.
1522 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase, MODRM_REG)
1523 GENERIC_FIXUP_FUNC(fixupRMValue, insn->eaRegBase, EA_REG)
1526 * fixupReg - Consults an operand specifier to determine which of the
1527 * fixup*Value functions to use in correcting readModRM()'ss interpretation.
1529 * @param insn - See fixup*Value().
1530 * @param op - The operand specifier.
1531 * @return - 0 if fixup was successful; -1 if the register returned was
1532 * invalid for its class.
1534 static int fixupReg(struct InternalInstruction *insn,
1535 const struct OperandSpecifier *op) {
1538 dbgprintf(insn, "fixupReg()");
1540 switch ((OperandEncoding)op->encoding) {
1542 debug("Expected a REG or R/M encoding in fixupReg");
1545 insn->vvvv = (Reg)fixupRegValue(insn,
1546 (OperandType)op->type,
1553 insn->reg = (Reg)fixupRegValue(insn,
1554 (OperandType)op->type,
1555 insn->reg - insn->regBase,
1561 if (insn->eaBase >= insn->eaRegBase) {
1562 insn->eaBase = (EABase)fixupRMValue(insn,
1563 (OperandType)op->type,
1564 insn->eaBase - insn->eaRegBase,
1576 * readOpcodeRegister - Reads an operand from the opcode field of an
1577 * instruction and interprets it appropriately given the operand width.
1578 * Handles AddRegFrm instructions.
1580 * @param insn - the instruction whose opcode field is to be read.
1581 * @param size - The width (in bytes) of the register being specified.
1582 * 1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1584 * @return - 0 on success; nonzero otherwise.
1586 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1587 dbgprintf(insn, "readOpcodeRegister()");
1590 size = insn->registerSize;
1594 insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1595 | (insn->opcode & 7)));
1596 if (insn->rexPrefix &&
1597 insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1598 insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1599 insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1600 + (insn->opcodeRegister - MODRM_REG_AL - 4));
1605 insn->opcodeRegister = (Reg)(MODRM_REG_AX
1606 + ((bFromREX(insn->rexPrefix) << 3)
1607 | (insn->opcode & 7)));
1610 insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1611 + ((bFromREX(insn->rexPrefix) << 3)
1612 | (insn->opcode & 7)));
1615 insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1616 + ((bFromREX(insn->rexPrefix) << 3)
1617 | (insn->opcode & 7)));
1625 * readImmediate - Consumes an immediate operand from an instruction, given the
1626 * desired operand size.
1628 * @param insn - The instruction whose operand is to be read.
1629 * @param size - The width (in bytes) of the operand.
1630 * @return - 0 if the immediate was successfully consumed; nonzero
1633 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1639 dbgprintf(insn, "readImmediate()");
1641 if (insn->numImmediatesConsumed == 2) {
1642 debug("Already consumed two immediates");
1647 size = insn->immediateSize;
1649 insn->immediateSize = size;
1650 insn->immediateOffset = insn->readerCursor - insn->startLocation;
1654 if (consumeByte(insn, &imm8))
1656 insn->immediates[insn->numImmediatesConsumed] = imm8;
1659 if (consumeUInt16(insn, &imm16))
1661 insn->immediates[insn->numImmediatesConsumed] = imm16;
1664 if (consumeUInt32(insn, &imm32))
1666 insn->immediates[insn->numImmediatesConsumed] = imm32;
1669 if (consumeUInt64(insn, &imm64))
1671 insn->immediates[insn->numImmediatesConsumed] = imm64;
1675 insn->numImmediatesConsumed++;
1681 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1683 * @param insn - The instruction whose operand is to be read.
1684 * @return - 0 if the vvvv was successfully consumed; nonzero
1687 static int readVVVV(struct InternalInstruction* insn) {
1688 dbgprintf(insn, "readVVVV()");
1691 if (insn->vectorExtensionType == TYPE_EVEX)
1692 vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1693 vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1694 else if (insn->vectorExtensionType == TYPE_VEX_3B)
1695 vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1696 else if (insn->vectorExtensionType == TYPE_VEX_2B)
1697 vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1698 else if (insn->vectorExtensionType == TYPE_XOP)
1699 vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1703 if (insn->mode != MODE_64BIT)
1706 insn->vvvv = static_cast<Reg>(vvvv);
1711 * readMaskRegister - Reads an mask register from the opcode field of an
1714 * @param insn - The instruction whose opcode field is to be read.
1715 * @return - 0 on success; nonzero otherwise.
1717 static int readMaskRegister(struct InternalInstruction* insn) {
1718 dbgprintf(insn, "readMaskRegister()");
1720 if (insn->vectorExtensionType != TYPE_EVEX)
1724 static_cast<Reg>(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1729 * readOperands - Consults the specifier for an instruction and consumes all
1730 * operands for that instruction, interpreting them as it goes.
1732 * @param insn - The instruction whose operands are to be read and interpreted.
1733 * @return - 0 if all operands could be read; nonzero otherwise.
1735 static int readOperands(struct InternalInstruction* insn) {
1736 int hasVVVV, needVVVV;
1739 dbgprintf(insn, "readOperands()");
1741 /* If non-zero vvvv specified, need to make sure one of the operands
1743 hasVVVV = !readVVVV(insn);
1744 needVVVV = hasVVVV && (insn->vvvv != 0);
1746 for (const auto &Op : x86OperandSets[insn->spec->operands]) {
1747 switch (Op.encoding) {
1754 if (readModRM(insn))
1756 if (fixupReg(insn, &Op))
1758 // Apply the AVX512 compressed displacement scaling factor.
1759 if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1760 insn->displacement *= 1 << (Op.encoding - ENCODING_RM);
1768 dbgprintf(insn, "We currently don't hande code-offset encodings");
1772 /* Saw a register immediate so don't read again and instead split the
1773 previous immediate. FIXME: This is a hack. */
1774 insn->immediates[insn->numImmediatesConsumed] =
1775 insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1776 ++insn->numImmediatesConsumed;
1779 if (readImmediate(insn, 1))
1781 if (Op.type == TYPE_XMM128 ||
1782 Op.type == TYPE_XMM256)
1786 if (readImmediate(insn, 2))
1790 if (readImmediate(insn, 4))
1794 if (readImmediate(insn, 8))
1798 if (readImmediate(insn, insn->immediateSize))
1802 if (readImmediate(insn, insn->addressSize))
1806 if (readOpcodeRegister(insn, 1))
1810 if (readOpcodeRegister(insn, 2))
1814 if (readOpcodeRegister(insn, 4))
1818 if (readOpcodeRegister(insn, 8))
1822 if (readOpcodeRegister(insn, 0))
1828 needVVVV = 0; /* Mark that we have found a VVVV operand. */
1831 if (fixupReg(insn, &Op))
1834 case ENCODING_WRITEMASK:
1835 if (readMaskRegister(insn))
1841 dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1846 /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1847 if (needVVVV) return -1;
1853 * decodeInstruction - Reads and interprets a full instruction provided by the
1856 * @param insn - A pointer to the instruction to be populated. Must be
1858 * @param reader - The function to be used to read the instruction's bytes.
1859 * @param readerArg - A generic argument to be passed to the reader to store
1860 * any internal state.
1861 * @param logger - If non-NULL, the function to be used to write log messages
1863 * @param loggerArg - A generic argument to be passed to the logger to store
1864 * any internal state.
1865 * @param startLoc - The address (in the reader's address space) of the first
1866 * byte in the instruction.
1867 * @param mode - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1868 * decode the instruction in.
1869 * @return - 0 if the instruction's memory could be read; nonzero if
1872 int llvm::X86Disassembler::decodeInstruction(
1873 struct InternalInstruction *insn, byteReader_t reader,
1874 const void *readerArg, dlog_t logger, void *loggerArg, const void *miiArg,
1875 uint64_t startLoc, DisassemblerMode mode) {
1876 memset(insn, 0, sizeof(struct InternalInstruction));
1878 insn->reader = reader;
1879 insn->readerArg = readerArg;
1880 insn->dlog = logger;
1881 insn->dlogArg = loggerArg;
1882 insn->startLocation = startLoc;
1883 insn->readerCursor = startLoc;
1885 insn->numImmediatesConsumed = 0;
1887 if (readPrefixes(insn) ||
1889 getID(insn, miiArg) ||
1890 insn->instructionID == 0 ||
1894 insn->operands = x86OperandSets[insn->spec->operands];
1896 insn->length = insn->readerCursor - insn->startLocation;
1898 dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1899 startLoc, insn->readerCursor, insn->length);
1901 if (insn->length > 15)
1902 dbgprintf(insn, "Instruction exceeds 15-byte limit");