X86DisassemblerDecoder.cpp revision dce4a407a24b04eebc6a376f8e62b41aaa7b071f
1//===-- X86DisassemblerDecoder.c - Disassembler decoder -------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
14//===----------------------------------------------------------------------===//
15
16#include <stdarg.h>   /* for va_*()       */
17#include <stdio.h>    /* for vsnprintf()  */
18#include <stdlib.h>   /* for exit()       */
19#include <string.h>   /* for memset()     */
20
21#include "X86DisassemblerDecoder.h"
22
23using namespace llvm::X86Disassembler;
24
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.
28struct ModRMDecision {
29  uint8_t modrm_type;
30  uint16_t instructionIDs;
31};
32
33/// Specifies which set of ModR/M->instruction tables to look at
34/// given a particular opcode.
35struct OpcodeDecision {
36  ModRMDecision modRMDecisions[256];
37};
38
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).
44struct ContextDecision {
45  OpcodeDecision opcodeDecisions[IC_max];
46};
47
48#include "X86GenDisassemblerTables.inc"
49
50#ifndef NDEBUG
51#define debug(s) do { Debug(__FILE__, __LINE__, s); } while (0)
52#else
53#define debug(s) do { } while (0)
54#endif
55
56
57/*
58 * contextForAttrs - Client for the instruction context table.  Takes a set of
59 *   attributes and returns the appropriate decode context.
60 *
61 * @param attrMask  - Attributes, from the enumeration attributeBits.
62 * @return          - The InstructionContext to use when looking up an
63 *                    an instruction with these attributes.
64 */
65static InstructionContext contextForAttrs(uint16_t attrMask) {
66  return static_cast<InstructionContext>(CONTEXTS_SYM[attrMask]);
67}
68
69/*
70 * modRMRequired - Reads the appropriate instruction table to determine whether
71 *   the ModR/M byte is required to decode a particular instruction.
72 *
73 * @param type        - The opcode type (i.e., how many bytes it has).
74 * @param insnContext - The context for the instruction, as returned by
75 *                      contextForAttrs.
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.
79 */
80static int modRMRequired(OpcodeType type,
81                         InstructionContext insnContext,
82                         uint16_t opcode) {
83  const struct ContextDecision* decision = nullptr;
84
85  switch (type) {
86  case ONEBYTE:
87    decision = &ONEBYTE_SYM;
88    break;
89  case TWOBYTE:
90    decision = &TWOBYTE_SYM;
91    break;
92  case THREEBYTE_38:
93    decision = &THREEBYTE38_SYM;
94    break;
95  case THREEBYTE_3A:
96    decision = &THREEBYTE3A_SYM;
97    break;
98  case XOP8_MAP:
99    decision = &XOP8_MAP_SYM;
100    break;
101  case XOP9_MAP:
102    decision = &XOP9_MAP_SYM;
103    break;
104  case XOPA_MAP:
105    decision = &XOPA_MAP_SYM;
106    break;
107  }
108
109  return decision->opcodeDecisions[insnContext].modRMDecisions[opcode].
110    modrm_type != MODRM_ONEENTRY;
111}
112
113/*
114 * decode - Reads the appropriate instruction table to obtain the unique ID of
115 *   an instruction.
116 *
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.
122 */
123static InstrUID decode(OpcodeType type,
124                       InstructionContext insnContext,
125                       uint8_t opcode,
126                       uint8_t modRM) {
127  const struct ModRMDecision* dec = nullptr;
128
129  switch (type) {
130  case ONEBYTE:
131    dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
132    break;
133  case TWOBYTE:
134    dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
135    break;
136  case THREEBYTE_38:
137    dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
138    break;
139  case THREEBYTE_3A:
140    dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
141    break;
142  case XOP8_MAP:
143    dec = &XOP8_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
144    break;
145  case XOP9_MAP:
146    dec = &XOP9_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
147    break;
148  case XOPA_MAP:
149    dec = &XOPA_MAP_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
150    break;
151  }
152
153  switch (dec->modrm_type) {
154  default:
155    debug("Corrupt table!  Unknown modrm_type");
156    return 0;
157  case MODRM_ONEENTRY:
158    return modRMTable[dec->instructionIDs];
159  case MODRM_SPLITRM:
160    if (modFromModRM(modRM) == 0x3)
161      return modRMTable[dec->instructionIDs+1];
162    return modRMTable[dec->instructionIDs];
163  case MODRM_SPLITREG:
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)];
171  case MODRM_FULL:
172    return modRMTable[dec->instructionIDs+modRM];
173  }
174}
175
176/*
177 * specifierForUID - Given a UID, returns the name and operand specification for
178 *   that instruction.
179 *
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.
183 */
184static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
185  return &INSTRUCTIONS_SYM[uid];
186}
187
188/*
189 * consumeByte - Uses the reader function provided by the user to consume one
190 *   byte from the instruction's memory and advance the cursor.
191 *
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.
197 */
198static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
199  int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
200
201  if (!ret)
202    ++(insn->readerCursor);
203
204  return ret;
205}
206
207/*
208 * lookAtByte - Like consumeByte, but does not advance the cursor.
209 *
210 * @param insn  - See consumeByte().
211 * @param byte  - See consumeByte().
212 * @return      - See consumeByte().
213 */
214static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
215  return insn->reader(insn->readerArg, byte, insn->readerCursor);
216}
217
218static void unconsumeByte(struct InternalInstruction* insn) {
219  insn->readerCursor--;
220}
221
222#define CONSUME_FUNC(name, type)                                  \
223  static int name(struct InternalInstruction* insn, type* ptr) {  \
224    type combined = 0;                                            \
225    unsigned offset;                                              \
226    for (offset = 0; offset < sizeof(type); ++offset) {           \
227      uint8_t byte;                                               \
228      int ret = insn->reader(insn->readerArg,                     \
229                             &byte,                               \
230                             insn->readerCursor + offset);        \
231      if (ret)                                                    \
232        return ret;                                               \
233      combined = combined | ((uint64_t)byte << (offset * 8));     \
234    }                                                             \
235    *ptr = combined;                                              \
236    insn->readerCursor += sizeof(type);                           \
237    return 0;                                                     \
238  }
239
240/*
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.
244 *
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().
249 */
250CONSUME_FUNC(consumeInt8, int8_t)
251CONSUME_FUNC(consumeInt16, int16_t)
252CONSUME_FUNC(consumeInt32, int32_t)
253CONSUME_FUNC(consumeUInt16, uint16_t)
254CONSUME_FUNC(consumeUInt32, uint32_t)
255CONSUME_FUNC(consumeUInt64, uint64_t)
256
257/*
258 * dbgprintf - Uses the logging function provided by the user to log a single
259 *   message, typically without a carriage-return.
260 *
261 * @param insn    - The instruction containing the logging function.
262 * @param format  - See printf().
263 * @param ...     - See printf().
264 */
265static void dbgprintf(struct InternalInstruction* insn,
266                      const char* format,
267                      ...) {
268  char buffer[256];
269  va_list ap;
270
271  if (!insn->dlog)
272    return;
273
274  va_start(ap, format);
275  (void)vsnprintf(buffer, sizeof(buffer), format, ap);
276  va_end(ap);
277
278  insn->dlog(insn->dlogArg, buffer);
279
280  return;
281}
282
283/*
284 * setPrefixPresent - Marks that a particular prefix is present at a particular
285 *   location.
286 *
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).
291 */
292static void setPrefixPresent(struct InternalInstruction* insn,
293                                    uint8_t prefix,
294                                    uint64_t location)
295{
296  insn->prefixPresent[prefix] = 1;
297  insn->prefixLocations[prefix] = location;
298}
299
300/*
301 * isPrefixAtLocation - Queries an instruction to determine whether a prefix is
302 *   present at a given location.
303 *
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.
308 */
309static bool isPrefixAtLocation(struct InternalInstruction* insn,
310                               uint8_t prefix,
311                               uint64_t location)
312{
313  if (insn->prefixPresent[prefix] == 1 &&
314     insn->prefixLocations[prefix] == location)
315    return true;
316  else
317    return false;
318}
319
320/*
321 * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
322 *   instruction as having them.  Also sets the instruction's default operand,
323 *   address, and other relevant data sizes to report operands correctly.
324 *
325 * @param insn  - The instruction whose prefixes are to be read.
326 * @return      - 0 if the instruction could be read until the end of the prefix
327 *                bytes, and no prefixes conflicted; nonzero otherwise.
328 */
329static int readPrefixes(struct InternalInstruction* insn) {
330  bool isPrefix = true;
331  bool prefixGroups[4] = { false };
332  uint64_t prefixLocation;
333  uint8_t byte = 0;
334  uint8_t nextByte;
335
336  bool hasAdSize = false;
337  bool hasOpSize = false;
338
339  dbgprintf(insn, "readPrefixes()");
340
341  while (isPrefix) {
342    prefixLocation = insn->readerCursor;
343
344    /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
345    if (consumeByte(insn, &byte))
346      break;
347
348    /*
349     * If the byte is a LOCK/REP/REPNE prefix and not a part of the opcode, then
350     * break and let it be disassembled as a normal "instruction".
351     */
352    if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0)
353      break;
354
355    if (insn->readerCursor - 1 == insn->startLocation
356        && (byte == 0xf2 || byte == 0xf3)
357        && !lookAtByte(insn, &nextByte))
358    {
359      /*
360       * If the byte is 0xf2 or 0xf3, and any of the following conditions are
361       * met:
362       * - it is followed by a LOCK (0xf0) prefix
363       * - it is followed by an xchg instruction
364       * then it should be disassembled as a xacquire/xrelease not repne/rep.
365       */
366      if ((byte == 0xf2 || byte == 0xf3) &&
367          ((nextByte == 0xf0) |
368          ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90)))
369        insn->xAcquireRelease = true;
370      /*
371       * Also if the byte is 0xf3, and the following condition is met:
372       * - it is followed by a "mov mem, reg" (opcode 0x88/0x89) or
373       *                       "mov mem, imm" (opcode 0xc6/0xc7) instructions.
374       * then it should be disassembled as an xrelease not rep.
375       */
376      if (byte == 0xf3 &&
377          (nextByte == 0x88 || nextByte == 0x89 ||
378           nextByte == 0xc6 || nextByte == 0xc7))
379        insn->xAcquireRelease = true;
380      if (insn->mode == MODE_64BIT && (nextByte & 0xf0) == 0x40) {
381        if (consumeByte(insn, &nextByte))
382          return -1;
383        if (lookAtByte(insn, &nextByte))
384          return -1;
385        unconsumeByte(insn);
386      }
387      if (nextByte != 0x0f && nextByte != 0x90)
388        break;
389    }
390
391    switch (byte) {
392    case 0xf0:  /* LOCK */
393    case 0xf2:  /* REPNE/REPNZ */
394    case 0xf3:  /* REP or REPE/REPZ */
395      if (prefixGroups[0])
396        dbgprintf(insn, "Redundant Group 1 prefix");
397      prefixGroups[0] = true;
398      setPrefixPresent(insn, byte, prefixLocation);
399      break;
400    case 0x2e:  /* CS segment override -OR- Branch not taken */
401    case 0x36:  /* SS segment override -OR- Branch taken */
402    case 0x3e:  /* DS segment override */
403    case 0x26:  /* ES segment override */
404    case 0x64:  /* FS segment override */
405    case 0x65:  /* GS segment override */
406      switch (byte) {
407      case 0x2e:
408        insn->segmentOverride = SEG_OVERRIDE_CS;
409        break;
410      case 0x36:
411        insn->segmentOverride = SEG_OVERRIDE_SS;
412        break;
413      case 0x3e:
414        insn->segmentOverride = SEG_OVERRIDE_DS;
415        break;
416      case 0x26:
417        insn->segmentOverride = SEG_OVERRIDE_ES;
418        break;
419      case 0x64:
420        insn->segmentOverride = SEG_OVERRIDE_FS;
421        break;
422      case 0x65:
423        insn->segmentOverride = SEG_OVERRIDE_GS;
424        break;
425      default:
426        debug("Unhandled override");
427        return -1;
428      }
429      if (prefixGroups[1])
430        dbgprintf(insn, "Redundant Group 2 prefix");
431      prefixGroups[1] = true;
432      setPrefixPresent(insn, byte, prefixLocation);
433      break;
434    case 0x66:  /* Operand-size override */
435      if (prefixGroups[2])
436        dbgprintf(insn, "Redundant Group 3 prefix");
437      prefixGroups[2] = true;
438      hasOpSize = true;
439      setPrefixPresent(insn, byte, prefixLocation);
440      break;
441    case 0x67:  /* Address-size override */
442      if (prefixGroups[3])
443        dbgprintf(insn, "Redundant Group 4 prefix");
444      prefixGroups[3] = true;
445      hasAdSize = true;
446      setPrefixPresent(insn, byte, prefixLocation);
447      break;
448    default:    /* Not a prefix byte */
449      isPrefix = false;
450      break;
451    }
452
453    if (isPrefix)
454      dbgprintf(insn, "Found prefix 0x%hhx", byte);
455  }
456
457  insn->vectorExtensionType = TYPE_NO_VEX_XOP;
458
459  if (byte == 0x62) {
460    uint8_t byte1, byte2;
461
462    if (consumeByte(insn, &byte1)) {
463      dbgprintf(insn, "Couldn't read second byte of EVEX prefix");
464      return -1;
465    }
466
467    if (lookAtByte(insn, &byte2)) {
468      dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
469      return -1;
470    }
471
472    if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
473       ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
474      insn->vectorExtensionType = TYPE_EVEX;
475    }
476    else {
477      unconsumeByte(insn); /* unconsume byte1 */
478      unconsumeByte(insn); /* unconsume byte  */
479      insn->necessaryPrefixLocation = insn->readerCursor - 2;
480    }
481
482    if (insn->vectorExtensionType == TYPE_EVEX) {
483      insn->vectorExtensionPrefix[0] = byte;
484      insn->vectorExtensionPrefix[1] = byte1;
485      if (consumeByte(insn, &insn->vectorExtensionPrefix[2])) {
486        dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
487        return -1;
488      }
489      if (consumeByte(insn, &insn->vectorExtensionPrefix[3])) {
490        dbgprintf(insn, "Couldn't read fourth byte of EVEX prefix");
491        return -1;
492      }
493
494      /* We simulate the REX prefix for simplicity's sake */
495      if (insn->mode == MODE_64BIT) {
496        insn->rexPrefix = 0x40
497                        | (wFromEVEX3of4(insn->vectorExtensionPrefix[2]) << 3)
498                        | (rFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 2)
499                        | (xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 1)
500                        | (bFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 0);
501      }
502
503      dbgprintf(insn, "Found EVEX prefix 0x%hhx 0x%hhx 0x%hhx 0x%hhx",
504              insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
505              insn->vectorExtensionPrefix[2], insn->vectorExtensionPrefix[3]);
506    }
507  }
508  else if (byte == 0xc4) {
509    uint8_t byte1;
510
511    if (lookAtByte(insn, &byte1)) {
512      dbgprintf(insn, "Couldn't read second byte of VEX");
513      return -1;
514    }
515
516    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
517      insn->vectorExtensionType = TYPE_VEX_3B;
518      insn->necessaryPrefixLocation = insn->readerCursor - 1;
519    }
520    else {
521      unconsumeByte(insn);
522      insn->necessaryPrefixLocation = insn->readerCursor - 1;
523    }
524
525    if (insn->vectorExtensionType == TYPE_VEX_3B) {
526      insn->vectorExtensionPrefix[0] = byte;
527      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
528      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
529
530      /* We simulate the REX prefix for simplicity's sake */
531
532      if (insn->mode == MODE_64BIT) {
533        insn->rexPrefix = 0x40
534                        | (wFromVEX3of3(insn->vectorExtensionPrefix[2]) << 3)
535                        | (rFromVEX2of3(insn->vectorExtensionPrefix[1]) << 2)
536                        | (xFromVEX2of3(insn->vectorExtensionPrefix[1]) << 1)
537                        | (bFromVEX2of3(insn->vectorExtensionPrefix[1]) << 0);
538      }
539
540      dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx",
541                insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
542                insn->vectorExtensionPrefix[2]);
543    }
544  }
545  else if (byte == 0xc5) {
546    uint8_t byte1;
547
548    if (lookAtByte(insn, &byte1)) {
549      dbgprintf(insn, "Couldn't read second byte of VEX");
550      return -1;
551    }
552
553    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
554      insn->vectorExtensionType = TYPE_VEX_2B;
555    }
556    else {
557      unconsumeByte(insn);
558    }
559
560    if (insn->vectorExtensionType == TYPE_VEX_2B) {
561      insn->vectorExtensionPrefix[0] = byte;
562      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
563
564      if (insn->mode == MODE_64BIT) {
565        insn->rexPrefix = 0x40
566                        | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
567      }
568
569      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1]))
570      {
571      default:
572        break;
573      case VEX_PREFIX_66:
574        hasOpSize = true;
575        break;
576      }
577
578      dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx",
579                insn->vectorExtensionPrefix[0],
580                insn->vectorExtensionPrefix[1]);
581    }
582  }
583  else if (byte == 0x8f) {
584    uint8_t byte1;
585
586    if (lookAtByte(insn, &byte1)) {
587      dbgprintf(insn, "Couldn't read second byte of XOP");
588      return -1;
589    }
590
591    if ((byte1 & 0x38) != 0x0) { /* 0 in these 3 bits is a POP instruction. */
592      insn->vectorExtensionType = TYPE_XOP;
593      insn->necessaryPrefixLocation = insn->readerCursor - 1;
594    }
595    else {
596      unconsumeByte(insn);
597      insn->necessaryPrefixLocation = insn->readerCursor - 1;
598    }
599
600    if (insn->vectorExtensionType == TYPE_XOP) {
601      insn->vectorExtensionPrefix[0] = byte;
602      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
603      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
604
605      /* We simulate the REX prefix for simplicity's sake */
606
607      if (insn->mode == MODE_64BIT) {
608        insn->rexPrefix = 0x40
609                        | (wFromXOP3of3(insn->vectorExtensionPrefix[2]) << 3)
610                        | (rFromXOP2of3(insn->vectorExtensionPrefix[1]) << 2)
611                        | (xFromXOP2of3(insn->vectorExtensionPrefix[1]) << 1)
612                        | (bFromXOP2of3(insn->vectorExtensionPrefix[1]) << 0);
613      }
614
615      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2]))
616      {
617      default:
618        break;
619      case VEX_PREFIX_66:
620        hasOpSize = true;
621        break;
622      }
623
624      dbgprintf(insn, "Found XOP prefix 0x%hhx 0x%hhx 0x%hhx",
625                insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
626                insn->vectorExtensionPrefix[2]);
627    }
628  }
629  else {
630    if (insn->mode == MODE_64BIT) {
631      if ((byte & 0xf0) == 0x40) {
632        uint8_t opcodeByte;
633
634        if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
635          dbgprintf(insn, "Redundant REX prefix");
636          return -1;
637        }
638
639        insn->rexPrefix = byte;
640        insn->necessaryPrefixLocation = insn->readerCursor - 2;
641
642        dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
643      } else {
644        unconsumeByte(insn);
645        insn->necessaryPrefixLocation = insn->readerCursor - 1;
646      }
647    } else {
648      unconsumeByte(insn);
649      insn->necessaryPrefixLocation = insn->readerCursor - 1;
650    }
651  }
652
653  if (insn->mode == MODE_16BIT) {
654    insn->registerSize       = (hasOpSize ? 4 : 2);
655    insn->addressSize        = (hasAdSize ? 4 : 2);
656    insn->displacementSize   = (hasAdSize ? 4 : 2);
657    insn->immediateSize      = (hasOpSize ? 4 : 2);
658  } else if (insn->mode == MODE_32BIT) {
659    insn->registerSize       = (hasOpSize ? 2 : 4);
660    insn->addressSize        = (hasAdSize ? 2 : 4);
661    insn->displacementSize   = (hasAdSize ? 2 : 4);
662    insn->immediateSize      = (hasOpSize ? 2 : 4);
663  } else if (insn->mode == MODE_64BIT) {
664    if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
665      insn->registerSize       = 8;
666      insn->addressSize        = (hasAdSize ? 4 : 8);
667      insn->displacementSize   = 4;
668      insn->immediateSize      = 4;
669    } else if (insn->rexPrefix) {
670      insn->registerSize       = (hasOpSize ? 2 : 4);
671      insn->addressSize        = (hasAdSize ? 4 : 8);
672      insn->displacementSize   = (hasOpSize ? 2 : 4);
673      insn->immediateSize      = (hasOpSize ? 2 : 4);
674    } else {
675      insn->registerSize       = (hasOpSize ? 2 : 4);
676      insn->addressSize        = (hasAdSize ? 4 : 8);
677      insn->displacementSize   = (hasOpSize ? 2 : 4);
678      insn->immediateSize      = (hasOpSize ? 2 : 4);
679    }
680  }
681
682  return 0;
683}
684
685/*
686 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
687 *   extended or escape opcodes).
688 *
689 * @param insn  - The instruction whose opcode is to be read.
690 * @return      - 0 if the opcode could be read successfully; nonzero otherwise.
691 */
692static int readOpcode(struct InternalInstruction* insn) {
693  /* Determine the length of the primary opcode */
694
695  uint8_t current;
696
697  dbgprintf(insn, "readOpcode()");
698
699  insn->opcodeType = ONEBYTE;
700
701  if (insn->vectorExtensionType == TYPE_EVEX)
702  {
703    switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
704    default:
705      dbgprintf(insn, "Unhandled mm field for instruction (0x%hhx)",
706                mmFromEVEX2of4(insn->vectorExtensionPrefix[1]));
707      return -1;
708    case VEX_LOB_0F:
709      insn->opcodeType = TWOBYTE;
710      return consumeByte(insn, &insn->opcode);
711    case VEX_LOB_0F38:
712      insn->opcodeType = THREEBYTE_38;
713      return consumeByte(insn, &insn->opcode);
714    case VEX_LOB_0F3A:
715      insn->opcodeType = THREEBYTE_3A;
716      return consumeByte(insn, &insn->opcode);
717    }
718  }
719  else if (insn->vectorExtensionType == TYPE_VEX_3B) {
720    switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
721    default:
722      dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
723                mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
724      return -1;
725    case VEX_LOB_0F:
726      insn->opcodeType = TWOBYTE;
727      return consumeByte(insn, &insn->opcode);
728    case VEX_LOB_0F38:
729      insn->opcodeType = THREEBYTE_38;
730      return consumeByte(insn, &insn->opcode);
731    case VEX_LOB_0F3A:
732      insn->opcodeType = THREEBYTE_3A;
733      return consumeByte(insn, &insn->opcode);
734    }
735  }
736  else if (insn->vectorExtensionType == TYPE_VEX_2B) {
737    insn->opcodeType = TWOBYTE;
738    return consumeByte(insn, &insn->opcode);
739  }
740  else if (insn->vectorExtensionType == TYPE_XOP) {
741    switch (mmmmmFromXOP2of3(insn->vectorExtensionPrefix[1])) {
742    default:
743      dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
744                mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
745      return -1;
746    case XOP_MAP_SELECT_8:
747      insn->opcodeType = XOP8_MAP;
748      return consumeByte(insn, &insn->opcode);
749    case XOP_MAP_SELECT_9:
750      insn->opcodeType = XOP9_MAP;
751      return consumeByte(insn, &insn->opcode);
752    case XOP_MAP_SELECT_A:
753      insn->opcodeType = XOPA_MAP;
754      return consumeByte(insn, &insn->opcode);
755    }
756  }
757
758  if (consumeByte(insn, &current))
759    return -1;
760
761  if (current == 0x0f) {
762    dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
763
764    if (consumeByte(insn, &current))
765      return -1;
766
767    if (current == 0x38) {
768      dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
769
770      if (consumeByte(insn, &current))
771        return -1;
772
773      insn->opcodeType = THREEBYTE_38;
774    } else if (current == 0x3a) {
775      dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
776
777      if (consumeByte(insn, &current))
778        return -1;
779
780      insn->opcodeType = THREEBYTE_3A;
781    } else {
782      dbgprintf(insn, "Didn't find a three-byte escape prefix");
783
784      insn->opcodeType = TWOBYTE;
785    }
786  }
787
788  /*
789   * At this point we have consumed the full opcode.
790   * Anything we consume from here on must be unconsumed.
791   */
792
793  insn->opcode = current;
794
795  return 0;
796}
797
798static int readModRM(struct InternalInstruction* insn);
799
800/*
801 * getIDWithAttrMask - Determines the ID of an instruction, consuming
802 *   the ModR/M byte as appropriate for extended and escape opcodes,
803 *   and using a supplied attribute mask.
804 *
805 * @param instructionID - A pointer whose target is filled in with the ID of the
806 *                        instruction.
807 * @param insn          - The instruction whose ID is to be determined.
808 * @param attrMask      - The attribute mask to search.
809 * @return              - 0 if the ModR/M could be read when needed or was not
810 *                        needed; nonzero otherwise.
811 */
812static int getIDWithAttrMask(uint16_t* instructionID,
813                             struct InternalInstruction* insn,
814                             uint16_t attrMask) {
815  bool hasModRMExtension;
816
817  InstructionContext instructionClass = contextForAttrs(attrMask);
818
819  hasModRMExtension = modRMRequired(insn->opcodeType,
820                                    instructionClass,
821                                    insn->opcode);
822
823  if (hasModRMExtension) {
824    if (readModRM(insn))
825      return -1;
826
827    *instructionID = decode(insn->opcodeType,
828                            instructionClass,
829                            insn->opcode,
830                            insn->modRM);
831  } else {
832    *instructionID = decode(insn->opcodeType,
833                            instructionClass,
834                            insn->opcode,
835                            0);
836  }
837
838  return 0;
839}
840
841/*
842 * is16BitEquivalent - Determines whether two instruction names refer to
843 * equivalent instructions but one is 16-bit whereas the other is not.
844 *
845 * @param orig  - The instruction that is not 16-bit
846 * @param equiv - The instruction that is 16-bit
847 */
848static bool is16BitEquivalent(const char* orig, const char* equiv) {
849  off_t i;
850
851  for (i = 0;; i++) {
852    if (orig[i] == '\0' && equiv[i] == '\0')
853      return true;
854    if (orig[i] == '\0' || equiv[i] == '\0')
855      return false;
856    if (orig[i] != equiv[i]) {
857      if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
858        continue;
859      if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
860        continue;
861      if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
862        continue;
863      return false;
864    }
865  }
866}
867
868/*
869 * getID - Determines the ID of an instruction, consuming the ModR/M byte as
870 *   appropriate for extended and escape opcodes.  Determines the attributes and
871 *   context for the instruction before doing so.
872 *
873 * @param insn  - The instruction whose ID is to be determined.
874 * @return      - 0 if the ModR/M could be read when needed or was not needed;
875 *                nonzero otherwise.
876 */
877static int getID(struct InternalInstruction* insn, const void *miiArg) {
878  uint16_t attrMask;
879  uint16_t instructionID;
880
881  dbgprintf(insn, "getID()");
882
883  attrMask = ATTR_NONE;
884
885  if (insn->mode == MODE_64BIT)
886    attrMask |= ATTR_64BIT;
887
888  if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
889    attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
890
891    if (insn->vectorExtensionType == TYPE_EVEX) {
892      switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
893      case VEX_PREFIX_66:
894        attrMask |= ATTR_OPSIZE;
895        break;
896      case VEX_PREFIX_F3:
897        attrMask |= ATTR_XS;
898        break;
899      case VEX_PREFIX_F2:
900        attrMask |= ATTR_XD;
901        break;
902      }
903
904      if (zFromEVEX4of4(insn->vectorExtensionPrefix[3]))
905        attrMask |= ATTR_EVEXKZ;
906      if (bFromEVEX4of4(insn->vectorExtensionPrefix[3]))
907        attrMask |= ATTR_EVEXB;
908      if (aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]))
909        attrMask |= ATTR_EVEXK;
910      if (lFromEVEX4of4(insn->vectorExtensionPrefix[3]))
911        attrMask |= ATTR_EVEXL;
912      if (l2FromEVEX4of4(insn->vectorExtensionPrefix[3]))
913        attrMask |= ATTR_EVEXL2;
914    }
915    else if (insn->vectorExtensionType == TYPE_VEX_3B) {
916      switch (ppFromVEX3of3(insn->vectorExtensionPrefix[2])) {
917      case VEX_PREFIX_66:
918        attrMask |= ATTR_OPSIZE;
919        break;
920      case VEX_PREFIX_F3:
921        attrMask |= ATTR_XS;
922        break;
923      case VEX_PREFIX_F2:
924        attrMask |= ATTR_XD;
925        break;
926      }
927
928      if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
929        attrMask |= ATTR_VEXL;
930    }
931    else if (insn->vectorExtensionType == TYPE_VEX_2B) {
932      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
933      case VEX_PREFIX_66:
934        attrMask |= ATTR_OPSIZE;
935        break;
936      case VEX_PREFIX_F3:
937        attrMask |= ATTR_XS;
938        break;
939      case VEX_PREFIX_F2:
940        attrMask |= ATTR_XD;
941        break;
942      }
943
944      if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
945        attrMask |= ATTR_VEXL;
946    }
947    else if (insn->vectorExtensionType == TYPE_XOP) {
948      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
949      case VEX_PREFIX_66:
950        attrMask |= ATTR_OPSIZE;
951        break;
952      case VEX_PREFIX_F3:
953        attrMask |= ATTR_XS;
954        break;
955      case VEX_PREFIX_F2:
956        attrMask |= ATTR_XD;
957        break;
958      }
959
960      if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
961        attrMask |= ATTR_VEXL;
962    }
963    else {
964      return -1;
965    }
966  }
967  else {
968    if (insn->mode != MODE_16BIT && isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
969      attrMask |= ATTR_OPSIZE;
970    else if (isPrefixAtLocation(insn, 0x67, insn->necessaryPrefixLocation))
971      attrMask |= ATTR_ADSIZE;
972    else if (isPrefixAtLocation(insn, 0xf3, insn->necessaryPrefixLocation))
973      attrMask |= ATTR_XS;
974    else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
975      attrMask |= ATTR_XD;
976  }
977
978  if (insn->rexPrefix & 0x08)
979    attrMask |= ATTR_REXW;
980
981  if (getIDWithAttrMask(&instructionID, insn, attrMask))
982    return -1;
983
984  /*
985   * JCXZ/JECXZ need special handling for 16-bit mode because the meaning
986   * of the AdSize prefix is inverted w.r.t. 32-bit mode.
987   */
988  if (insn->mode == MODE_16BIT && insn->opcode == 0xE3) {
989    const struct InstructionSpecifier *spec;
990    spec = specifierForUID(instructionID);
991
992    /*
993     * Check for Ii8PCRel instructions. We could alternatively do a
994     * string-compare on the names, but this is probably cheaper.
995     */
996    if (x86OperandSets[spec->operands][0].type == TYPE_REL8) {
997      attrMask ^= ATTR_ADSIZE;
998      if (getIDWithAttrMask(&instructionID, insn, attrMask))
999        return -1;
1000    }
1001  }
1002
1003  /* The following clauses compensate for limitations of the tables. */
1004
1005  if ((insn->mode == MODE_16BIT || insn->prefixPresent[0x66]) &&
1006      !(attrMask & ATTR_OPSIZE)) {
1007    /*
1008     * The instruction tables make no distinction between instructions that
1009     * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
1010     * particular spot (i.e., many MMX operations).  In general we're
1011     * conservative, but in the specific case where OpSize is present but not
1012     * in the right place we check if there's a 16-bit operation.
1013     */
1014
1015    const struct InstructionSpecifier *spec;
1016    uint16_t instructionIDWithOpsize;
1017    const char *specName, *specWithOpSizeName;
1018
1019    spec = specifierForUID(instructionID);
1020
1021    if (getIDWithAttrMask(&instructionIDWithOpsize,
1022                          insn,
1023                          attrMask | ATTR_OPSIZE)) {
1024      /*
1025       * ModRM required with OpSize but not present; give up and return version
1026       * without OpSize set
1027       */
1028
1029      insn->instructionID = instructionID;
1030      insn->spec = spec;
1031      return 0;
1032    }
1033
1034    specName = GetInstrName(instructionID, miiArg);
1035    specWithOpSizeName = GetInstrName(instructionIDWithOpsize, miiArg);
1036
1037    if (is16BitEquivalent(specName, specWithOpSizeName) &&
1038        (insn->mode == MODE_16BIT) ^ insn->prefixPresent[0x66]) {
1039      insn->instructionID = instructionIDWithOpsize;
1040      insn->spec = specifierForUID(instructionIDWithOpsize);
1041    } else {
1042      insn->instructionID = instructionID;
1043      insn->spec = spec;
1044    }
1045    return 0;
1046  }
1047
1048  if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1049      insn->rexPrefix & 0x01) {
1050    /*
1051     * NOOP shouldn't decode as NOOP if REX.b is set. Instead
1052     * it should decode as XCHG %r8, %eax.
1053     */
1054
1055    const struct InstructionSpecifier *spec;
1056    uint16_t instructionIDWithNewOpcode;
1057    const struct InstructionSpecifier *specWithNewOpcode;
1058
1059    spec = specifierForUID(instructionID);
1060
1061    /* Borrow opcode from one of the other XCHGar opcodes */
1062    insn->opcode = 0x91;
1063
1064    if (getIDWithAttrMask(&instructionIDWithNewOpcode,
1065                          insn,
1066                          attrMask)) {
1067      insn->opcode = 0x90;
1068
1069      insn->instructionID = instructionID;
1070      insn->spec = spec;
1071      return 0;
1072    }
1073
1074    specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
1075
1076    /* Change back */
1077    insn->opcode = 0x90;
1078
1079    insn->instructionID = instructionIDWithNewOpcode;
1080    insn->spec = specWithNewOpcode;
1081
1082    return 0;
1083  }
1084
1085  insn->instructionID = instructionID;
1086  insn->spec = specifierForUID(insn->instructionID);
1087
1088  return 0;
1089}
1090
1091/*
1092 * readSIB - Consumes the SIB byte to determine addressing information for an
1093 *   instruction.
1094 *
1095 * @param insn  - The instruction whose SIB byte is to be read.
1096 * @return      - 0 if the SIB byte was successfully read; nonzero otherwise.
1097 */
1098static int readSIB(struct InternalInstruction* insn) {
1099  SIBIndex sibIndexBase = SIB_INDEX_NONE;
1100  SIBBase sibBaseBase = SIB_BASE_NONE;
1101  uint8_t index, base;
1102
1103  dbgprintf(insn, "readSIB()");
1104
1105  if (insn->consumedSIB)
1106    return 0;
1107
1108  insn->consumedSIB = true;
1109
1110  switch (insn->addressSize) {
1111  case 2:
1112    dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
1113    return -1;
1114  case 4:
1115    sibIndexBase = SIB_INDEX_EAX;
1116    sibBaseBase = SIB_BASE_EAX;
1117    break;
1118  case 8:
1119    sibIndexBase = SIB_INDEX_RAX;
1120    sibBaseBase = SIB_BASE_RAX;
1121    break;
1122  }
1123
1124  if (consumeByte(insn, &insn->sib))
1125    return -1;
1126
1127  index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1128  if (insn->vectorExtensionType == TYPE_EVEX)
1129    index |= v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4;
1130
1131  switch (index) {
1132  case 0x4:
1133    insn->sibIndex = SIB_INDEX_NONE;
1134    break;
1135  default:
1136    insn->sibIndex = (SIBIndex)(sibIndexBase + index);
1137    if (insn->sibIndex == SIB_INDEX_sib ||
1138        insn->sibIndex == SIB_INDEX_sib64)
1139      insn->sibIndex = SIB_INDEX_NONE;
1140    break;
1141  }
1142
1143  switch (scaleFromSIB(insn->sib)) {
1144  case 0:
1145    insn->sibScale = 1;
1146    break;
1147  case 1:
1148    insn->sibScale = 2;
1149    break;
1150  case 2:
1151    insn->sibScale = 4;
1152    break;
1153  case 3:
1154    insn->sibScale = 8;
1155    break;
1156  }
1157
1158  base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1159
1160  switch (base) {
1161  case 0x5:
1162  case 0xd:
1163    switch (modFromModRM(insn->modRM)) {
1164    case 0x0:
1165      insn->eaDisplacement = EA_DISP_32;
1166      insn->sibBase = SIB_BASE_NONE;
1167      break;
1168    case 0x1:
1169      insn->eaDisplacement = EA_DISP_8;
1170      insn->sibBase = (SIBBase)(sibBaseBase + base);
1171      break;
1172    case 0x2:
1173      insn->eaDisplacement = EA_DISP_32;
1174      insn->sibBase = (SIBBase)(sibBaseBase + base);
1175      break;
1176    case 0x3:
1177      debug("Cannot have Mod = 0b11 and a SIB byte");
1178      return -1;
1179    }
1180    break;
1181  default:
1182    insn->sibBase = (SIBBase)(sibBaseBase + base);
1183    break;
1184  }
1185
1186  return 0;
1187}
1188
1189/*
1190 * readDisplacement - Consumes the displacement of an instruction.
1191 *
1192 * @param insn  - The instruction whose displacement is to be read.
1193 * @return      - 0 if the displacement byte was successfully read; nonzero
1194 *                otherwise.
1195 */
1196static int readDisplacement(struct InternalInstruction* insn) {
1197  int8_t d8;
1198  int16_t d16;
1199  int32_t d32;
1200
1201  dbgprintf(insn, "readDisplacement()");
1202
1203  if (insn->consumedDisplacement)
1204    return 0;
1205
1206  insn->consumedDisplacement = true;
1207  insn->displacementOffset = insn->readerCursor - insn->startLocation;
1208
1209  switch (insn->eaDisplacement) {
1210  case EA_DISP_NONE:
1211    insn->consumedDisplacement = false;
1212    break;
1213  case EA_DISP_8:
1214    if (consumeInt8(insn, &d8))
1215      return -1;
1216    insn->displacement = d8;
1217    break;
1218  case EA_DISP_16:
1219    if (consumeInt16(insn, &d16))
1220      return -1;
1221    insn->displacement = d16;
1222    break;
1223  case EA_DISP_32:
1224    if (consumeInt32(insn, &d32))
1225      return -1;
1226    insn->displacement = d32;
1227    break;
1228  }
1229
1230  insn->consumedDisplacement = true;
1231  return 0;
1232}
1233
1234/*
1235 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1236 *   displacement) for an instruction and interprets it.
1237 *
1238 * @param insn  - The instruction whose addressing information is to be read.
1239 * @return      - 0 if the information was successfully read; nonzero otherwise.
1240 */
1241static int readModRM(struct InternalInstruction* insn) {
1242  uint8_t mod, rm, reg;
1243
1244  dbgprintf(insn, "readModRM()");
1245
1246  if (insn->consumedModRM)
1247    return 0;
1248
1249  if (consumeByte(insn, &insn->modRM))
1250    return -1;
1251  insn->consumedModRM = true;
1252
1253  mod     = modFromModRM(insn->modRM);
1254  rm      = rmFromModRM(insn->modRM);
1255  reg     = regFromModRM(insn->modRM);
1256
1257  /*
1258   * This goes by insn->registerSize to pick the correct register, which messes
1259   * up if we're using (say) XMM or 8-bit register operands.  That gets fixed in
1260   * fixupReg().
1261   */
1262  switch (insn->registerSize) {
1263  case 2:
1264    insn->regBase = MODRM_REG_AX;
1265    insn->eaRegBase = EA_REG_AX;
1266    break;
1267  case 4:
1268    insn->regBase = MODRM_REG_EAX;
1269    insn->eaRegBase = EA_REG_EAX;
1270    break;
1271  case 8:
1272    insn->regBase = MODRM_REG_RAX;
1273    insn->eaRegBase = EA_REG_RAX;
1274    break;
1275  }
1276
1277  reg |= rFromREX(insn->rexPrefix) << 3;
1278  rm  |= bFromREX(insn->rexPrefix) << 3;
1279  if (insn->vectorExtensionType == TYPE_EVEX) {
1280    reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1281    rm  |=  xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1282  }
1283
1284  insn->reg = (Reg)(insn->regBase + reg);
1285
1286  switch (insn->addressSize) {
1287  case 2:
1288    insn->eaBaseBase = EA_BASE_BX_SI;
1289
1290    switch (mod) {
1291    case 0x0:
1292      if (rm == 0x6) {
1293        insn->eaBase = EA_BASE_NONE;
1294        insn->eaDisplacement = EA_DISP_16;
1295        if (readDisplacement(insn))
1296          return -1;
1297      } else {
1298        insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1299        insn->eaDisplacement = EA_DISP_NONE;
1300      }
1301      break;
1302    case 0x1:
1303      insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1304      insn->eaDisplacement = EA_DISP_8;
1305      insn->displacementSize = 1;
1306      if (readDisplacement(insn))
1307        return -1;
1308      break;
1309    case 0x2:
1310      insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1311      insn->eaDisplacement = EA_DISP_16;
1312      if (readDisplacement(insn))
1313        return -1;
1314      break;
1315    case 0x3:
1316      insn->eaBase = (EABase)(insn->eaRegBase + rm);
1317      if (readDisplacement(insn))
1318        return -1;
1319      break;
1320    }
1321    break;
1322  case 4:
1323  case 8:
1324    insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1325
1326    switch (mod) {
1327    case 0x0:
1328      insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1329      switch (rm) {
1330      case 0x14:
1331      case 0x4:
1332      case 0xc:   /* in case REXW.b is set */
1333        insn->eaBase = (insn->addressSize == 4 ?
1334                        EA_BASE_sib : EA_BASE_sib64);
1335        if (readSIB(insn) || readDisplacement(insn))
1336          return -1;
1337        break;
1338      case 0x5:
1339        insn->eaBase = EA_BASE_NONE;
1340        insn->eaDisplacement = EA_DISP_32;
1341        if (readDisplacement(insn))
1342          return -1;
1343        break;
1344      default:
1345        insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1346        break;
1347      }
1348      break;
1349    case 0x1:
1350      insn->displacementSize = 1;
1351      /* FALLTHROUGH */
1352    case 0x2:
1353      insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1354      switch (rm) {
1355      case 0x14:
1356      case 0x4:
1357      case 0xc:   /* in case REXW.b is set */
1358        insn->eaBase = EA_BASE_sib;
1359        if (readSIB(insn) || readDisplacement(insn))
1360          return -1;
1361        break;
1362      default:
1363        insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1364        if (readDisplacement(insn))
1365          return -1;
1366        break;
1367      }
1368      break;
1369    case 0x3:
1370      insn->eaDisplacement = EA_DISP_NONE;
1371      insn->eaBase = (EABase)(insn->eaRegBase + rm);
1372      break;
1373    }
1374    break;
1375  } /* switch (insn->addressSize) */
1376
1377  return 0;
1378}
1379
1380#define GENERIC_FIXUP_FUNC(name, base, prefix)            \
1381  static uint8_t name(struct InternalInstruction *insn,   \
1382                      OperandType type,                   \
1383                      uint8_t index,                      \
1384                      uint8_t *valid) {                   \
1385    *valid = 1;                                           \
1386    switch (type) {                                       \
1387    default:                                              \
1388      debug("Unhandled register type");                   \
1389      *valid = 0;                                         \
1390      return 0;                                           \
1391    case TYPE_Rv:                                         \
1392      return base + index;                                \
1393    case TYPE_R8:                                         \
1394      if (insn->rexPrefix &&                              \
1395         index >= 4 && index <= 7) {                      \
1396        return prefix##_SPL + (index - 4);                \
1397      } else {                                            \
1398        return prefix##_AL + index;                       \
1399      }                                                   \
1400    case TYPE_R16:                                        \
1401      return prefix##_AX + index;                         \
1402    case TYPE_R32:                                        \
1403      return prefix##_EAX + index;                        \
1404    case TYPE_R64:                                        \
1405      return prefix##_RAX + index;                        \
1406    case TYPE_XMM512:                                     \
1407      return prefix##_ZMM0 + index;                       \
1408    case TYPE_XMM256:                                     \
1409      return prefix##_YMM0 + index;                       \
1410    case TYPE_XMM128:                                     \
1411    case TYPE_XMM64:                                      \
1412    case TYPE_XMM32:                                      \
1413    case TYPE_XMM:                                        \
1414      return prefix##_XMM0 + index;                       \
1415    case TYPE_VK1:                                        \
1416    case TYPE_VK8:                                        \
1417    case TYPE_VK16:                                       \
1418      return prefix##_K0 + index;                         \
1419    case TYPE_MM64:                                       \
1420    case TYPE_MM32:                                       \
1421    case TYPE_MM:                                         \
1422      if (index > 7)                                      \
1423        *valid = 0;                                       \
1424      return prefix##_MM0 + index;                        \
1425    case TYPE_SEGMENTREG:                                 \
1426      if (index > 5)                                      \
1427        *valid = 0;                                       \
1428      return prefix##_ES + index;                         \
1429    case TYPE_DEBUGREG:                                   \
1430      if (index > 7)                                      \
1431        *valid = 0;                                       \
1432      return prefix##_DR0 + index;                        \
1433    case TYPE_CONTROLREG:                                 \
1434      if (index > 8)                                      \
1435        *valid = 0;                                       \
1436      return prefix##_CR0 + index;                        \
1437    }                                                     \
1438  }
1439
1440/*
1441 * fixup*Value - Consults an operand type to determine the meaning of the
1442 *   reg or R/M field.  If the operand is an XMM operand, for example, an
1443 *   operand would be XMM0 instead of AX, which readModRM() would otherwise
1444 *   misinterpret it as.
1445 *
1446 * @param insn  - The instruction containing the operand.
1447 * @param type  - The operand type.
1448 * @param index - The existing value of the field as reported by readModRM().
1449 * @param valid - The address of a uint8_t.  The target is set to 1 if the
1450 *                field is valid for the register class; 0 if not.
1451 * @return      - The proper value.
1452 */
1453GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase,    MODRM_REG)
1454GENERIC_FIXUP_FUNC(fixupRMValue,  insn->eaRegBase,  EA_REG)
1455
1456/*
1457 * fixupReg - Consults an operand specifier to determine which of the
1458 *   fixup*Value functions to use in correcting readModRM()'ss interpretation.
1459 *
1460 * @param insn  - See fixup*Value().
1461 * @param op    - The operand specifier.
1462 * @return      - 0 if fixup was successful; -1 if the register returned was
1463 *                invalid for its class.
1464 */
1465static int fixupReg(struct InternalInstruction *insn,
1466                    const struct OperandSpecifier *op) {
1467  uint8_t valid;
1468
1469  dbgprintf(insn, "fixupReg()");
1470
1471  switch ((OperandEncoding)op->encoding) {
1472  default:
1473    debug("Expected a REG or R/M encoding in fixupReg");
1474    return -1;
1475  case ENCODING_VVVV:
1476    insn->vvvv = (Reg)fixupRegValue(insn,
1477                                    (OperandType)op->type,
1478                                    insn->vvvv,
1479                                    &valid);
1480    if (!valid)
1481      return -1;
1482    break;
1483  case ENCODING_REG:
1484    insn->reg = (Reg)fixupRegValue(insn,
1485                                   (OperandType)op->type,
1486                                   insn->reg - insn->regBase,
1487                                   &valid);
1488    if (!valid)
1489      return -1;
1490    break;
1491  case ENCODING_RM:
1492    if (insn->eaBase >= insn->eaRegBase) {
1493      insn->eaBase = (EABase)fixupRMValue(insn,
1494                                          (OperandType)op->type,
1495                                          insn->eaBase - insn->eaRegBase,
1496                                          &valid);
1497      if (!valid)
1498        return -1;
1499    }
1500    break;
1501  }
1502
1503  return 0;
1504}
1505
1506/*
1507 * readOpcodeRegister - Reads an operand from the opcode field of an
1508 *   instruction and interprets it appropriately given the operand width.
1509 *   Handles AddRegFrm instructions.
1510 *
1511 * @param insn  - the instruction whose opcode field is to be read.
1512 * @param size  - The width (in bytes) of the register being specified.
1513 *                1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1514 *                RAX.
1515 * @return      - 0 on success; nonzero otherwise.
1516 */
1517static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1518  dbgprintf(insn, "readOpcodeRegister()");
1519
1520  if (size == 0)
1521    size = insn->registerSize;
1522
1523  switch (size) {
1524  case 1:
1525    insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1526                                                  | (insn->opcode & 7)));
1527    if (insn->rexPrefix &&
1528        insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1529        insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1530      insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1531                                   + (insn->opcodeRegister - MODRM_REG_AL - 4));
1532    }
1533
1534    break;
1535  case 2:
1536    insn->opcodeRegister = (Reg)(MODRM_REG_AX
1537                                 + ((bFromREX(insn->rexPrefix) << 3)
1538                                    | (insn->opcode & 7)));
1539    break;
1540  case 4:
1541    insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1542                                 + ((bFromREX(insn->rexPrefix) << 3)
1543                                    | (insn->opcode & 7)));
1544    break;
1545  case 8:
1546    insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1547                                 + ((bFromREX(insn->rexPrefix) << 3)
1548                                    | (insn->opcode & 7)));
1549    break;
1550  }
1551
1552  return 0;
1553}
1554
1555/*
1556 * readImmediate - Consumes an immediate operand from an instruction, given the
1557 *   desired operand size.
1558 *
1559 * @param insn  - The instruction whose operand is to be read.
1560 * @param size  - The width (in bytes) of the operand.
1561 * @return      - 0 if the immediate was successfully consumed; nonzero
1562 *                otherwise.
1563 */
1564static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1565  uint8_t imm8;
1566  uint16_t imm16;
1567  uint32_t imm32;
1568  uint64_t imm64;
1569
1570  dbgprintf(insn, "readImmediate()");
1571
1572  if (insn->numImmediatesConsumed == 2) {
1573    debug("Already consumed two immediates");
1574    return -1;
1575  }
1576
1577  if (size == 0)
1578    size = insn->immediateSize;
1579  else
1580    insn->immediateSize = size;
1581  insn->immediateOffset = insn->readerCursor - insn->startLocation;
1582
1583  switch (size) {
1584  case 1:
1585    if (consumeByte(insn, &imm8))
1586      return -1;
1587    insn->immediates[insn->numImmediatesConsumed] = imm8;
1588    break;
1589  case 2:
1590    if (consumeUInt16(insn, &imm16))
1591      return -1;
1592    insn->immediates[insn->numImmediatesConsumed] = imm16;
1593    break;
1594  case 4:
1595    if (consumeUInt32(insn, &imm32))
1596      return -1;
1597    insn->immediates[insn->numImmediatesConsumed] = imm32;
1598    break;
1599  case 8:
1600    if (consumeUInt64(insn, &imm64))
1601      return -1;
1602    insn->immediates[insn->numImmediatesConsumed] = imm64;
1603    break;
1604  }
1605
1606  insn->numImmediatesConsumed++;
1607
1608  return 0;
1609}
1610
1611/*
1612 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1613 *
1614 * @param insn  - The instruction whose operand is to be read.
1615 * @return      - 0 if the vvvv was successfully consumed; nonzero
1616 *                otherwise.
1617 */
1618static int readVVVV(struct InternalInstruction* insn) {
1619  dbgprintf(insn, "readVVVV()");
1620
1621  int vvvv;
1622  if (insn->vectorExtensionType == TYPE_EVEX)
1623    vvvv = vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]);
1624  else if (insn->vectorExtensionType == TYPE_VEX_3B)
1625    vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1626  else if (insn->vectorExtensionType == TYPE_VEX_2B)
1627    vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1628  else if (insn->vectorExtensionType == TYPE_XOP)
1629    vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1630  else
1631    return -1;
1632
1633  if (insn->mode != MODE_64BIT)
1634    vvvv &= 0x7;
1635
1636  insn->vvvv = static_cast<Reg>(vvvv);
1637  return 0;
1638}
1639
1640/*
1641 * readMaskRegister - Reads an mask register from the opcode field of an
1642 *   instruction.
1643 *
1644 * @param insn    - The instruction whose opcode field is to be read.
1645 * @return        - 0 on success; nonzero otherwise.
1646 */
1647static int readMaskRegister(struct InternalInstruction* insn) {
1648  dbgprintf(insn, "readMaskRegister()");
1649
1650  if (insn->vectorExtensionType != TYPE_EVEX)
1651    return -1;
1652
1653  insn->writemask =
1654      static_cast<Reg>(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1655  return 0;
1656}
1657
1658/*
1659 * readOperands - Consults the specifier for an instruction and consumes all
1660 *   operands for that instruction, interpreting them as it goes.
1661 *
1662 * @param insn  - The instruction whose operands are to be read and interpreted.
1663 * @return      - 0 if all operands could be read; nonzero otherwise.
1664 */
1665static int readOperands(struct InternalInstruction* insn) {
1666  int hasVVVV, needVVVV;
1667  int sawRegImm = 0;
1668
1669  dbgprintf(insn, "readOperands()");
1670
1671  /* If non-zero vvvv specified, need to make sure one of the operands
1672     uses it. */
1673  hasVVVV = !readVVVV(insn);
1674  needVVVV = hasVVVV && (insn->vvvv != 0);
1675
1676  for (const auto &Op : x86OperandSets[insn->spec->operands]) {
1677    switch (Op.encoding) {
1678    case ENCODING_NONE:
1679    case ENCODING_SI:
1680    case ENCODING_DI:
1681      break;
1682    case ENCODING_REG:
1683    case ENCODING_RM:
1684      if (readModRM(insn))
1685        return -1;
1686      if (fixupReg(insn, &Op))
1687        return -1;
1688      break;
1689    case ENCODING_CB:
1690    case ENCODING_CW:
1691    case ENCODING_CD:
1692    case ENCODING_CP:
1693    case ENCODING_CO:
1694    case ENCODING_CT:
1695      dbgprintf(insn, "We currently don't hande code-offset encodings");
1696      return -1;
1697    case ENCODING_IB:
1698      if (sawRegImm) {
1699        /* Saw a register immediate so don't read again and instead split the
1700           previous immediate.  FIXME: This is a hack. */
1701        insn->immediates[insn->numImmediatesConsumed] =
1702          insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1703        ++insn->numImmediatesConsumed;
1704        break;
1705      }
1706      if (readImmediate(insn, 1))
1707        return -1;
1708      if (Op.type == TYPE_IMM3 &&
1709          insn->immediates[insn->numImmediatesConsumed - 1] > 7)
1710        return -1;
1711      if (Op.type == TYPE_IMM5 &&
1712          insn->immediates[insn->numImmediatesConsumed - 1] > 31)
1713        return -1;
1714      if (Op.type == TYPE_XMM128 ||
1715          Op.type == TYPE_XMM256)
1716        sawRegImm = 1;
1717      break;
1718    case ENCODING_IW:
1719      if (readImmediate(insn, 2))
1720        return -1;
1721      break;
1722    case ENCODING_ID:
1723      if (readImmediate(insn, 4))
1724        return -1;
1725      break;
1726    case ENCODING_IO:
1727      if (readImmediate(insn, 8))
1728        return -1;
1729      break;
1730    case ENCODING_Iv:
1731      if (readImmediate(insn, insn->immediateSize))
1732        return -1;
1733      break;
1734    case ENCODING_Ia:
1735      if (readImmediate(insn, insn->addressSize))
1736        return -1;
1737      break;
1738    case ENCODING_RB:
1739      if (readOpcodeRegister(insn, 1))
1740        return -1;
1741      break;
1742    case ENCODING_RW:
1743      if (readOpcodeRegister(insn, 2))
1744        return -1;
1745      break;
1746    case ENCODING_RD:
1747      if (readOpcodeRegister(insn, 4))
1748        return -1;
1749      break;
1750    case ENCODING_RO:
1751      if (readOpcodeRegister(insn, 8))
1752        return -1;
1753      break;
1754    case ENCODING_Rv:
1755      if (readOpcodeRegister(insn, 0))
1756        return -1;
1757      break;
1758    case ENCODING_FP:
1759      break;
1760    case ENCODING_VVVV:
1761      needVVVV = 0; /* Mark that we have found a VVVV operand. */
1762      if (!hasVVVV)
1763        return -1;
1764      if (fixupReg(insn, &Op))
1765        return -1;
1766      break;
1767    case ENCODING_WRITEMASK:
1768      if (readMaskRegister(insn))
1769        return -1;
1770      break;
1771    case ENCODING_DUP:
1772      break;
1773    default:
1774      dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1775      return -1;
1776    }
1777  }
1778
1779  /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1780  if (needVVVV) return -1;
1781
1782  return 0;
1783}
1784
1785/*
1786 * decodeInstruction - Reads and interprets a full instruction provided by the
1787 *   user.
1788 *
1789 * @param insn      - A pointer to the instruction to be populated.  Must be
1790 *                    pre-allocated.
1791 * @param reader    - The function to be used to read the instruction's bytes.
1792 * @param readerArg - A generic argument to be passed to the reader to store
1793 *                    any internal state.
1794 * @param logger    - If non-NULL, the function to be used to write log messages
1795 *                    and warnings.
1796 * @param loggerArg - A generic argument to be passed to the logger to store
1797 *                    any internal state.
1798 * @param startLoc  - The address (in the reader's address space) of the first
1799 *                    byte in the instruction.
1800 * @param mode      - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1801 *                    decode the instruction in.
1802 * @return          - 0 if the instruction's memory could be read; nonzero if
1803 *                    not.
1804 */
1805int llvm::X86Disassembler::decodeInstruction(
1806    struct InternalInstruction *insn, byteReader_t reader,
1807    const void *readerArg, dlog_t logger, void *loggerArg, const void *miiArg,
1808    uint64_t startLoc, DisassemblerMode mode) {
1809  memset(insn, 0, sizeof(struct InternalInstruction));
1810
1811  insn->reader = reader;
1812  insn->readerArg = readerArg;
1813  insn->dlog = logger;
1814  insn->dlogArg = loggerArg;
1815  insn->startLocation = startLoc;
1816  insn->readerCursor = startLoc;
1817  insn->mode = mode;
1818  insn->numImmediatesConsumed = 0;
1819
1820  if (readPrefixes(insn)       ||
1821      readOpcode(insn)         ||
1822      getID(insn, miiArg)      ||
1823      insn->instructionID == 0 ||
1824      readOperands(insn))
1825    return -1;
1826
1827  insn->operands = x86OperandSets[insn->spec->operands];
1828
1829  insn->length = insn->readerCursor - insn->startLocation;
1830
1831  dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1832            startLoc, insn->readerCursor, insn->length);
1833
1834  if (insn->length > 15)
1835    dbgprintf(insn, "Instruction exceeds 15-byte limit");
1836
1837  return 0;
1838}
1839