1//===-- X86DisassemblerDecoder.cpp - 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 <cstdarg>   /* for va_*()       */
17#include <cstdio>    /* for vsnprintf()  */
18#include <cstdlib>   /* for exit()       */
19#include <cstring>   /* 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  return insn->prefixPresent[prefix] == 1 &&
314     insn->prefixLocations[prefix] == location;
315}
316
317/*
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.
321 *
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.
325 */
326static int readPrefixes(struct InternalInstruction* insn) {
327  bool isPrefix = true;
328  bool prefixGroups[4] = { false };
329  uint64_t prefixLocation;
330  uint8_t byte = 0;
331  uint8_t nextByte;
332
333  bool hasAdSize = false;
334  bool hasOpSize = false;
335
336  dbgprintf(insn, "readPrefixes()");
337
338  while (isPrefix) {
339    prefixLocation = insn->readerCursor;
340
341    /* If we fail reading prefixes, just stop here and let the opcode reader deal with it */
342    if (consumeByte(insn, &byte))
343      break;
344
345    /*
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".
348     */
349    if (insn->readerCursor - 1 == insn->startLocation && byte == 0xf0)
350      break;
351
352    if (insn->readerCursor - 1 == insn->startLocation
353        && (byte == 0xf2 || byte == 0xf3)
354        && !lookAtByte(insn, &nextByte))
355    {
356      /*
357       * If the byte is 0xf2 or 0xf3, and any of the following conditions are
358       * met:
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.
362       */
363      if ((byte == 0xf2 || byte == 0xf3) &&
364          ((nextByte == 0xf0) |
365          ((nextByte & 0xfe) == 0x86 || (nextByte & 0xf8) == 0x90)))
366        insn->xAcquireRelease = true;
367      /*
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.
372       */
373      if (byte == 0xf3 &&
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))
379          return -1;
380        if (lookAtByte(insn, &nextByte))
381          return -1;
382        unconsumeByte(insn);
383      }
384      if (nextByte != 0x0f && nextByte != 0x90)
385        break;
386    }
387
388    switch (byte) {
389    case 0xf0:  /* LOCK */
390    case 0xf2:  /* REPNE/REPNZ */
391    case 0xf3:  /* REP or REPE/REPZ */
392      if (prefixGroups[0])
393        dbgprintf(insn, "Redundant Group 1 prefix");
394      prefixGroups[0] = true;
395      setPrefixPresent(insn, byte, prefixLocation);
396      break;
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 */
403      switch (byte) {
404      case 0x2e:
405        insn->segmentOverride = SEG_OVERRIDE_CS;
406        break;
407      case 0x36:
408        insn->segmentOverride = SEG_OVERRIDE_SS;
409        break;
410      case 0x3e:
411        insn->segmentOverride = SEG_OVERRIDE_DS;
412        break;
413      case 0x26:
414        insn->segmentOverride = SEG_OVERRIDE_ES;
415        break;
416      case 0x64:
417        insn->segmentOverride = SEG_OVERRIDE_FS;
418        break;
419      case 0x65:
420        insn->segmentOverride = SEG_OVERRIDE_GS;
421        break;
422      default:
423        debug("Unhandled override");
424        return -1;
425      }
426      if (prefixGroups[1])
427        dbgprintf(insn, "Redundant Group 2 prefix");
428      prefixGroups[1] = true;
429      setPrefixPresent(insn, byte, prefixLocation);
430      break;
431    case 0x66:  /* Operand-size override */
432      if (prefixGroups[2])
433        dbgprintf(insn, "Redundant Group 3 prefix");
434      prefixGroups[2] = true;
435      hasOpSize = true;
436      setPrefixPresent(insn, byte, prefixLocation);
437      break;
438    case 0x67:  /* Address-size override */
439      if (prefixGroups[3])
440        dbgprintf(insn, "Redundant Group 4 prefix");
441      prefixGroups[3] = true;
442      hasAdSize = true;
443      setPrefixPresent(insn, byte, prefixLocation);
444      break;
445    default:    /* Not a prefix byte */
446      isPrefix = false;
447      break;
448    }
449
450    if (isPrefix)
451      dbgprintf(insn, "Found prefix 0x%hhx", byte);
452  }
453
454  insn->vectorExtensionType = TYPE_NO_VEX_XOP;
455
456  if (byte == 0x62) {
457    uint8_t byte1, byte2;
458
459    if (consumeByte(insn, &byte1)) {
460      dbgprintf(insn, "Couldn't read second byte of EVEX prefix");
461      return -1;
462    }
463
464    if (lookAtByte(insn, &byte2)) {
465      dbgprintf(insn, "Couldn't read third byte of EVEX prefix");
466      return -1;
467    }
468
469    if ((insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) &&
470       ((~byte1 & 0xc) == 0xc) && ((byte2 & 0x4) == 0x4)) {
471      insn->vectorExtensionType = TYPE_EVEX;
472    } else {
473      unconsumeByte(insn); /* unconsume byte1 */
474      unconsumeByte(insn); /* unconsume byte  */
475      insn->necessaryPrefixLocation = insn->readerCursor - 2;
476    }
477
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");
483        return -1;
484      }
485      if (consumeByte(insn, &insn->vectorExtensionPrefix[3])) {
486        dbgprintf(insn, "Couldn't read fourth byte of EVEX prefix");
487        return -1;
488      }
489
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);
497      }
498
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]);
502    }
503  } else if (byte == 0xc4) {
504    uint8_t byte1;
505
506    if (lookAtByte(insn, &byte1)) {
507      dbgprintf(insn, "Couldn't read second byte of VEX");
508      return -1;
509    }
510
511    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
512      insn->vectorExtensionType = TYPE_VEX_3B;
513      insn->necessaryPrefixLocation = insn->readerCursor - 1;
514    } else {
515      unconsumeByte(insn);
516      insn->necessaryPrefixLocation = insn->readerCursor - 1;
517    }
518
519    if (insn->vectorExtensionType == TYPE_VEX_3B) {
520      insn->vectorExtensionPrefix[0] = byte;
521      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
522      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
523
524      /* We simulate the REX prefix for simplicity's sake */
525
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);
532      }
533
534      dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx",
535                insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
536                insn->vectorExtensionPrefix[2]);
537    }
538  } else if (byte == 0xc5) {
539    uint8_t byte1;
540
541    if (lookAtByte(insn, &byte1)) {
542      dbgprintf(insn, "Couldn't read second byte of VEX");
543      return -1;
544    }
545
546    if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
547      insn->vectorExtensionType = TYPE_VEX_2B;
548    } else {
549      unconsumeByte(insn);
550    }
551
552    if (insn->vectorExtensionType == TYPE_VEX_2B) {
553      insn->vectorExtensionPrefix[0] = byte;
554      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
555
556      if (insn->mode == MODE_64BIT) {
557        insn->rexPrefix = 0x40
558                        | (rFromVEX2of2(insn->vectorExtensionPrefix[1]) << 2);
559      }
560
561      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
562      default:
563        break;
564      case VEX_PREFIX_66:
565        hasOpSize = true;
566        break;
567      }
568
569      dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx",
570                insn->vectorExtensionPrefix[0],
571                insn->vectorExtensionPrefix[1]);
572    }
573  } else if (byte == 0x8f) {
574    uint8_t byte1;
575
576    if (lookAtByte(insn, &byte1)) {
577      dbgprintf(insn, "Couldn't read second byte of XOP");
578      return -1;
579    }
580
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;
584    } else {
585      unconsumeByte(insn);
586      insn->necessaryPrefixLocation = insn->readerCursor - 1;
587    }
588
589    if (insn->vectorExtensionType == TYPE_XOP) {
590      insn->vectorExtensionPrefix[0] = byte;
591      consumeByte(insn, &insn->vectorExtensionPrefix[1]);
592      consumeByte(insn, &insn->vectorExtensionPrefix[2]);
593
594      /* We simulate the REX prefix for simplicity's sake */
595
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);
602      }
603
604      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
605      default:
606        break;
607      case VEX_PREFIX_66:
608        hasOpSize = true;
609        break;
610      }
611
612      dbgprintf(insn, "Found XOP prefix 0x%hhx 0x%hhx 0x%hhx",
613                insn->vectorExtensionPrefix[0], insn->vectorExtensionPrefix[1],
614                insn->vectorExtensionPrefix[2]);
615    }
616  } else {
617    if (insn->mode == MODE_64BIT) {
618      if ((byte & 0xf0) == 0x40) {
619        uint8_t opcodeByte;
620
621        if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
622          dbgprintf(insn, "Redundant REX prefix");
623          return -1;
624        }
625
626        insn->rexPrefix = byte;
627        insn->necessaryPrefixLocation = insn->readerCursor - 2;
628
629        dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
630      } else {
631        unconsumeByte(insn);
632        insn->necessaryPrefixLocation = insn->readerCursor - 1;
633      }
634    } else {
635      unconsumeByte(insn);
636      insn->necessaryPrefixLocation = insn->readerCursor - 1;
637    }
638  }
639
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);
661    } else {
662      insn->registerSize       = (hasOpSize ? 2 : 4);
663      insn->addressSize        = (hasAdSize ? 4 : 8);
664      insn->displacementSize   = (hasOpSize ? 2 : 4);
665      insn->immediateSize      = (hasOpSize ? 2 : 4);
666    }
667  }
668
669  return 0;
670}
671
672/*
673 * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
674 *   extended or escape opcodes).
675 *
676 * @param insn  - The instruction whose opcode is to be read.
677 * @return      - 0 if the opcode could be read successfully; nonzero otherwise.
678 */
679static int readOpcode(struct InternalInstruction* insn) {
680  /* Determine the length of the primary opcode */
681
682  uint8_t current;
683
684  dbgprintf(insn, "readOpcode()");
685
686  insn->opcodeType = ONEBYTE;
687
688  if (insn->vectorExtensionType == TYPE_EVEX) {
689    switch (mmFromEVEX2of4(insn->vectorExtensionPrefix[1])) {
690    default:
691      dbgprintf(insn, "Unhandled mm field for instruction (0x%hhx)",
692                mmFromEVEX2of4(insn->vectorExtensionPrefix[1]));
693      return -1;
694    case VEX_LOB_0F:
695      insn->opcodeType = TWOBYTE;
696      return consumeByte(insn, &insn->opcode);
697    case VEX_LOB_0F38:
698      insn->opcodeType = THREEBYTE_38;
699      return consumeByte(insn, &insn->opcode);
700    case VEX_LOB_0F3A:
701      insn->opcodeType = THREEBYTE_3A;
702      return consumeByte(insn, &insn->opcode);
703    }
704  } else if (insn->vectorExtensionType == TYPE_VEX_3B) {
705    switch (mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1])) {
706    default:
707      dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
708                mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
709      return -1;
710    case VEX_LOB_0F:
711      insn->opcodeType = TWOBYTE;
712      return consumeByte(insn, &insn->opcode);
713    case VEX_LOB_0F38:
714      insn->opcodeType = THREEBYTE_38;
715      return consumeByte(insn, &insn->opcode);
716    case VEX_LOB_0F3A:
717      insn->opcodeType = THREEBYTE_3A;
718      return consumeByte(insn, &insn->opcode);
719    }
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])) {
725    default:
726      dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)",
727                mmmmmFromVEX2of3(insn->vectorExtensionPrefix[1]));
728      return -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);
738    }
739  }
740
741  if (consumeByte(insn, &current))
742    return -1;
743
744  if (current == 0x0f) {
745    dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
746
747    if (consumeByte(insn, &current))
748      return -1;
749
750    if (current == 0x38) {
751      dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
752
753      if (consumeByte(insn, &current))
754        return -1;
755
756      insn->opcodeType = THREEBYTE_38;
757    } else if (current == 0x3a) {
758      dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
759
760      if (consumeByte(insn, &current))
761        return -1;
762
763      insn->opcodeType = THREEBYTE_3A;
764    } else {
765      dbgprintf(insn, "Didn't find a three-byte escape prefix");
766
767      insn->opcodeType = TWOBYTE;
768    }
769  }
770
771  /*
772   * At this point we have consumed the full opcode.
773   * Anything we consume from here on must be unconsumed.
774   */
775
776  insn->opcode = current;
777
778  return 0;
779}
780
781static int readModRM(struct InternalInstruction* insn);
782
783/*
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.
787 *
788 * @param instructionID - A pointer whose target is filled in with the ID of the
789 *                        instruction.
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.
794 */
795static int getIDWithAttrMask(uint16_t* instructionID,
796                             struct InternalInstruction* insn,
797                             uint16_t attrMask) {
798  bool hasModRMExtension;
799
800  InstructionContext instructionClass = contextForAttrs(attrMask);
801
802  hasModRMExtension = modRMRequired(insn->opcodeType,
803                                    instructionClass,
804                                    insn->opcode);
805
806  if (hasModRMExtension) {
807    if (readModRM(insn))
808      return -1;
809
810    *instructionID = decode(insn->opcodeType,
811                            instructionClass,
812                            insn->opcode,
813                            insn->modRM);
814  } else {
815    *instructionID = decode(insn->opcodeType,
816                            instructionClass,
817                            insn->opcode,
818                            0);
819  }
820
821  return 0;
822}
823
824/*
825 * is16BitEquivalent - Determines whether two instruction names refer to
826 * equivalent instructions but one is 16-bit whereas the other is not.
827 *
828 * @param orig  - The instruction that is not 16-bit
829 * @param equiv - The instruction that is 16-bit
830 */
831static bool is16BitEquivalent(const char* orig, const char* equiv) {
832  off_t i;
833
834  for (i = 0;; i++) {
835    if (orig[i] == '\0' && equiv[i] == '\0')
836      return true;
837    if (orig[i] == '\0' || equiv[i] == '\0')
838      return false;
839    if (orig[i] != equiv[i]) {
840      if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
841        continue;
842      if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
843        continue;
844      if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
845        continue;
846      return false;
847    }
848  }
849}
850
851/*
852 * is64Bit - Determines whether this instruction is a 64-bit instruction.
853 *
854 * @param name - The instruction that is not 16-bit
855 */
856static bool is64Bit(const char* name) {
857  off_t i;
858
859  for (i = 0;; ++i) {
860    if (name[i] == '\0')
861      return false;
862    if (name[i] == '6' && name[i+1] == '4')
863      return true;
864  }
865}
866
867/*
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.
871 *
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;
874 *                nonzero otherwise.
875 */
876static int getID(struct InternalInstruction* insn, const void *miiArg) {
877  uint16_t attrMask;
878  uint16_t instructionID;
879
880  dbgprintf(insn, "getID()");
881
882  attrMask = ATTR_NONE;
883
884  if (insn->mode == MODE_64BIT)
885    attrMask |= ATTR_64BIT;
886
887  if (insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
888    attrMask |= (insn->vectorExtensionType == TYPE_EVEX) ? ATTR_EVEX : ATTR_VEX;
889
890    if (insn->vectorExtensionType == TYPE_EVEX) {
891      switch (ppFromEVEX3of4(insn->vectorExtensionPrefix[2])) {
892      case VEX_PREFIX_66:
893        attrMask |= ATTR_OPSIZE;
894        break;
895      case VEX_PREFIX_F3:
896        attrMask |= ATTR_XS;
897        break;
898      case VEX_PREFIX_F2:
899        attrMask |= ATTR_XD;
900        break;
901      }
902
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])) {
915      case VEX_PREFIX_66:
916        attrMask |= ATTR_OPSIZE;
917        break;
918      case VEX_PREFIX_F3:
919        attrMask |= ATTR_XS;
920        break;
921      case VEX_PREFIX_F2:
922        attrMask |= ATTR_XD;
923        break;
924      }
925
926      if (lFromVEX3of3(insn->vectorExtensionPrefix[2]))
927        attrMask |= ATTR_VEXL;
928    } else if (insn->vectorExtensionType == TYPE_VEX_2B) {
929      switch (ppFromVEX2of2(insn->vectorExtensionPrefix[1])) {
930      case VEX_PREFIX_66:
931        attrMask |= ATTR_OPSIZE;
932        break;
933      case VEX_PREFIX_F3:
934        attrMask |= ATTR_XS;
935        break;
936      case VEX_PREFIX_F2:
937        attrMask |= ATTR_XD;
938        break;
939      }
940
941      if (lFromVEX2of2(insn->vectorExtensionPrefix[1]))
942        attrMask |= ATTR_VEXL;
943    } else if (insn->vectorExtensionType == TYPE_XOP) {
944      switch (ppFromXOP3of3(insn->vectorExtensionPrefix[2])) {
945      case VEX_PREFIX_66:
946        attrMask |= ATTR_OPSIZE;
947        break;
948      case VEX_PREFIX_F3:
949        attrMask |= ATTR_XS;
950        break;
951      case VEX_PREFIX_F2:
952        attrMask |= ATTR_XD;
953        break;
954      }
955
956      if (lFromXOP3of3(insn->vectorExtensionPrefix[2]))
957        attrMask |= ATTR_VEXL;
958    } else {
959      return -1;
960    }
961  } else {
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))
967      attrMask |= ATTR_XS;
968    else if (isPrefixAtLocation(insn, 0xf2, insn->necessaryPrefixLocation))
969      attrMask |= ATTR_XD;
970  }
971
972  if (insn->rexPrefix & 0x08)
973    attrMask |= ATTR_REXW;
974
975  /*
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.
978   */
979  if (insn->mode == MODE_16BIT && insn->opcodeType == ONEBYTE &&
980      insn->opcode == 0xE3)
981    attrMask ^= ATTR_ADSIZE;
982
983  if (getIDWithAttrMask(&instructionID, insn, attrMask))
984    return -1;
985
986  /* The following clauses compensate for limitations of the tables. */
987
988  if (insn->mode != MODE_64BIT &&
989      insn->vectorExtensionType != TYPE_NO_VEX_XOP) {
990    /*
991     * The tables can't distinquish between cases where the W-bit is used to
992     * select register size and cases where its a required part of the opcode.
993     */
994    if ((insn->vectorExtensionType == TYPE_EVEX &&
995         wFromEVEX3of4(insn->vectorExtensionPrefix[2])) ||
996        (insn->vectorExtensionType == TYPE_VEX_3B &&
997         wFromVEX3of3(insn->vectorExtensionPrefix[2])) ||
998        (insn->vectorExtensionType == TYPE_XOP &&
999         wFromXOP3of3(insn->vectorExtensionPrefix[2]))) {
1000
1001      uint16_t instructionIDWithREXW;
1002      if (getIDWithAttrMask(&instructionIDWithREXW,
1003                            insn, attrMask | ATTR_REXW)) {
1004        insn->instructionID = instructionID;
1005        insn->spec = specifierForUID(instructionID);
1006        return 0;
1007      }
1008
1009      const char *SpecName = GetInstrName(instructionIDWithREXW, miiArg);
1010      // If not a 64-bit instruction. Switch the opcode.
1011      if (!is64Bit(SpecName)) {
1012        insn->instructionID = instructionIDWithREXW;
1013        insn->spec = specifierForUID(instructionIDWithREXW);
1014        return 0;
1015      }
1016    }
1017  }
1018
1019  /*
1020   * Absolute moves need special handling.
1021   * -For 16-bit mode because the meaning of the AdSize and OpSize prefixes are
1022   *  inverted w.r.t.
1023   * -For 32-bit mode we need to ensure the ADSIZE prefix is observed in
1024   *  any position.
1025   */
1026  if (insn->opcodeType == ONEBYTE && ((insn->opcode & 0xFC) == 0xA0)) {
1027    /* Make sure we observed the prefixes in any position. */
1028    if (insn->prefixPresent[0x67])
1029      attrMask |= ATTR_ADSIZE;
1030    if (insn->prefixPresent[0x66])
1031      attrMask |= ATTR_OPSIZE;
1032
1033    /* In 16-bit, invert the attributes. */
1034    if (insn->mode == MODE_16BIT)
1035      attrMask ^= ATTR_ADSIZE | ATTR_OPSIZE;
1036
1037    if (getIDWithAttrMask(&instructionID, insn, attrMask))
1038      return -1;
1039
1040    insn->instructionID = instructionID;
1041    insn->spec = specifierForUID(instructionID);
1042    return 0;
1043  }
1044
1045  if ((insn->mode == MODE_16BIT || insn->prefixPresent[0x66]) &&
1046      !(attrMask & ATTR_OPSIZE)) {
1047    /*
1048     * The instruction tables make no distinction between instructions that
1049     * allow OpSize anywhere (i.e., 16-bit operations) and that need it in a
1050     * particular spot (i.e., many MMX operations).  In general we're
1051     * conservative, but in the specific case where OpSize is present but not
1052     * in the right place we check if there's a 16-bit operation.
1053     */
1054
1055    const struct InstructionSpecifier *spec;
1056    uint16_t instructionIDWithOpsize;
1057    const char *specName, *specWithOpSizeName;
1058
1059    spec = specifierForUID(instructionID);
1060
1061    if (getIDWithAttrMask(&instructionIDWithOpsize,
1062                          insn,
1063                          attrMask | ATTR_OPSIZE)) {
1064      /*
1065       * ModRM required with OpSize but not present; give up and return version
1066       * without OpSize set
1067       */
1068
1069      insn->instructionID = instructionID;
1070      insn->spec = spec;
1071      return 0;
1072    }
1073
1074    specName = GetInstrName(instructionID, miiArg);
1075    specWithOpSizeName = GetInstrName(instructionIDWithOpsize, miiArg);
1076
1077    if (is16BitEquivalent(specName, specWithOpSizeName) &&
1078        (insn->mode == MODE_16BIT) ^ insn->prefixPresent[0x66]) {
1079      insn->instructionID = instructionIDWithOpsize;
1080      insn->spec = specifierForUID(instructionIDWithOpsize);
1081    } else {
1082      insn->instructionID = instructionID;
1083      insn->spec = spec;
1084    }
1085    return 0;
1086  }
1087
1088  if (insn->opcodeType == ONEBYTE && insn->opcode == 0x90 &&
1089      insn->rexPrefix & 0x01) {
1090    /*
1091     * NOOP shouldn't decode as NOOP if REX.b is set. Instead
1092     * it should decode as XCHG %r8, %eax.
1093     */
1094
1095    const struct InstructionSpecifier *spec;
1096    uint16_t instructionIDWithNewOpcode;
1097    const struct InstructionSpecifier *specWithNewOpcode;
1098
1099    spec = specifierForUID(instructionID);
1100
1101    /* Borrow opcode from one of the other XCHGar opcodes */
1102    insn->opcode = 0x91;
1103
1104    if (getIDWithAttrMask(&instructionIDWithNewOpcode,
1105                          insn,
1106                          attrMask)) {
1107      insn->opcode = 0x90;
1108
1109      insn->instructionID = instructionID;
1110      insn->spec = spec;
1111      return 0;
1112    }
1113
1114    specWithNewOpcode = specifierForUID(instructionIDWithNewOpcode);
1115
1116    /* Change back */
1117    insn->opcode = 0x90;
1118
1119    insn->instructionID = instructionIDWithNewOpcode;
1120    insn->spec = specWithNewOpcode;
1121
1122    return 0;
1123  }
1124
1125  insn->instructionID = instructionID;
1126  insn->spec = specifierForUID(insn->instructionID);
1127
1128  return 0;
1129}
1130
1131/*
1132 * readSIB - Consumes the SIB byte to determine addressing information for an
1133 *   instruction.
1134 *
1135 * @param insn  - The instruction whose SIB byte is to be read.
1136 * @return      - 0 if the SIB byte was successfully read; nonzero otherwise.
1137 */
1138static int readSIB(struct InternalInstruction* insn) {
1139  SIBIndex sibIndexBase = SIB_INDEX_NONE;
1140  SIBBase sibBaseBase = SIB_BASE_NONE;
1141  uint8_t index, base;
1142
1143  dbgprintf(insn, "readSIB()");
1144
1145  if (insn->consumedSIB)
1146    return 0;
1147
1148  insn->consumedSIB = true;
1149
1150  switch (insn->addressSize) {
1151  case 2:
1152    dbgprintf(insn, "SIB-based addressing doesn't work in 16-bit mode");
1153    return -1;
1154  case 4:
1155    sibIndexBase = SIB_INDEX_EAX;
1156    sibBaseBase = SIB_BASE_EAX;
1157    break;
1158  case 8:
1159    sibIndexBase = SIB_INDEX_RAX;
1160    sibBaseBase = SIB_BASE_RAX;
1161    break;
1162  }
1163
1164  if (consumeByte(insn, &insn->sib))
1165    return -1;
1166
1167  index = indexFromSIB(insn->sib) | (xFromREX(insn->rexPrefix) << 3);
1168  if (insn->vectorExtensionType == TYPE_EVEX)
1169    index |= v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4;
1170
1171  switch (index) {
1172  case 0x4:
1173    insn->sibIndex = SIB_INDEX_NONE;
1174    break;
1175  default:
1176    insn->sibIndex = (SIBIndex)(sibIndexBase + index);
1177    if (insn->sibIndex == SIB_INDEX_sib ||
1178        insn->sibIndex == SIB_INDEX_sib64)
1179      insn->sibIndex = SIB_INDEX_NONE;
1180    break;
1181  }
1182
1183  switch (scaleFromSIB(insn->sib)) {
1184  case 0:
1185    insn->sibScale = 1;
1186    break;
1187  case 1:
1188    insn->sibScale = 2;
1189    break;
1190  case 2:
1191    insn->sibScale = 4;
1192    break;
1193  case 3:
1194    insn->sibScale = 8;
1195    break;
1196  }
1197
1198  base = baseFromSIB(insn->sib) | (bFromREX(insn->rexPrefix) << 3);
1199
1200  switch (base) {
1201  case 0x5:
1202  case 0xd:
1203    switch (modFromModRM(insn->modRM)) {
1204    case 0x0:
1205      insn->eaDisplacement = EA_DISP_32;
1206      insn->sibBase = SIB_BASE_NONE;
1207      break;
1208    case 0x1:
1209      insn->eaDisplacement = EA_DISP_8;
1210      insn->sibBase = (SIBBase)(sibBaseBase + base);
1211      break;
1212    case 0x2:
1213      insn->eaDisplacement = EA_DISP_32;
1214      insn->sibBase = (SIBBase)(sibBaseBase + base);
1215      break;
1216    case 0x3:
1217      debug("Cannot have Mod = 0b11 and a SIB byte");
1218      return -1;
1219    }
1220    break;
1221  default:
1222    insn->sibBase = (SIBBase)(sibBaseBase + base);
1223    break;
1224  }
1225
1226  return 0;
1227}
1228
1229/*
1230 * readDisplacement - Consumes the displacement of an instruction.
1231 *
1232 * @param insn  - The instruction whose displacement is to be read.
1233 * @return      - 0 if the displacement byte was successfully read; nonzero
1234 *                otherwise.
1235 */
1236static int readDisplacement(struct InternalInstruction* insn) {
1237  int8_t d8;
1238  int16_t d16;
1239  int32_t d32;
1240
1241  dbgprintf(insn, "readDisplacement()");
1242
1243  if (insn->consumedDisplacement)
1244    return 0;
1245
1246  insn->consumedDisplacement = true;
1247  insn->displacementOffset = insn->readerCursor - insn->startLocation;
1248
1249  switch (insn->eaDisplacement) {
1250  case EA_DISP_NONE:
1251    insn->consumedDisplacement = false;
1252    break;
1253  case EA_DISP_8:
1254    if (consumeInt8(insn, &d8))
1255      return -1;
1256    insn->displacement = d8;
1257    break;
1258  case EA_DISP_16:
1259    if (consumeInt16(insn, &d16))
1260      return -1;
1261    insn->displacement = d16;
1262    break;
1263  case EA_DISP_32:
1264    if (consumeInt32(insn, &d32))
1265      return -1;
1266    insn->displacement = d32;
1267    break;
1268  }
1269
1270  insn->consumedDisplacement = true;
1271  return 0;
1272}
1273
1274/*
1275 * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1276 *   displacement) for an instruction and interprets it.
1277 *
1278 * @param insn  - The instruction whose addressing information is to be read.
1279 * @return      - 0 if the information was successfully read; nonzero otherwise.
1280 */
1281static int readModRM(struct InternalInstruction* insn) {
1282  uint8_t mod, rm, reg;
1283
1284  dbgprintf(insn, "readModRM()");
1285
1286  if (insn->consumedModRM)
1287    return 0;
1288
1289  if (consumeByte(insn, &insn->modRM))
1290    return -1;
1291  insn->consumedModRM = true;
1292
1293  mod     = modFromModRM(insn->modRM);
1294  rm      = rmFromModRM(insn->modRM);
1295  reg     = regFromModRM(insn->modRM);
1296
1297  /*
1298   * This goes by insn->registerSize to pick the correct register, which messes
1299   * up if we're using (say) XMM or 8-bit register operands.  That gets fixed in
1300   * fixupReg().
1301   */
1302  switch (insn->registerSize) {
1303  case 2:
1304    insn->regBase = MODRM_REG_AX;
1305    insn->eaRegBase = EA_REG_AX;
1306    break;
1307  case 4:
1308    insn->regBase = MODRM_REG_EAX;
1309    insn->eaRegBase = EA_REG_EAX;
1310    break;
1311  case 8:
1312    insn->regBase = MODRM_REG_RAX;
1313    insn->eaRegBase = EA_REG_RAX;
1314    break;
1315  }
1316
1317  reg |= rFromREX(insn->rexPrefix) << 3;
1318  rm  |= bFromREX(insn->rexPrefix) << 3;
1319  if (insn->vectorExtensionType == TYPE_EVEX) {
1320    reg |= r2FromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1321    rm  |=  xFromEVEX2of4(insn->vectorExtensionPrefix[1]) << 4;
1322  }
1323
1324  insn->reg = (Reg)(insn->regBase + reg);
1325
1326  switch (insn->addressSize) {
1327  case 2:
1328    insn->eaBaseBase = EA_BASE_BX_SI;
1329
1330    switch (mod) {
1331    case 0x0:
1332      if (rm == 0x6) {
1333        insn->eaBase = EA_BASE_NONE;
1334        insn->eaDisplacement = EA_DISP_16;
1335        if (readDisplacement(insn))
1336          return -1;
1337      } else {
1338        insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1339        insn->eaDisplacement = EA_DISP_NONE;
1340      }
1341      break;
1342    case 0x1:
1343      insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1344      insn->eaDisplacement = EA_DISP_8;
1345      insn->displacementSize = 1;
1346      if (readDisplacement(insn))
1347        return -1;
1348      break;
1349    case 0x2:
1350      insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1351      insn->eaDisplacement = EA_DISP_16;
1352      if (readDisplacement(insn))
1353        return -1;
1354      break;
1355    case 0x3:
1356      insn->eaBase = (EABase)(insn->eaRegBase + rm);
1357      if (readDisplacement(insn))
1358        return -1;
1359      break;
1360    }
1361    break;
1362  case 4:
1363  case 8:
1364    insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1365
1366    switch (mod) {
1367    case 0x0:
1368      insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1369      switch (rm) {
1370      case 0x14:
1371      case 0x4:
1372      case 0xc:   /* in case REXW.b is set */
1373        insn->eaBase = (insn->addressSize == 4 ?
1374                        EA_BASE_sib : EA_BASE_sib64);
1375        if (readSIB(insn) || readDisplacement(insn))
1376          return -1;
1377        break;
1378      case 0x5:
1379        insn->eaBase = EA_BASE_NONE;
1380        insn->eaDisplacement = EA_DISP_32;
1381        if (readDisplacement(insn))
1382          return -1;
1383        break;
1384      default:
1385        insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1386        break;
1387      }
1388      break;
1389    case 0x1:
1390      insn->displacementSize = 1;
1391      /* FALLTHROUGH */
1392    case 0x2:
1393      insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1394      switch (rm) {
1395      case 0x14:
1396      case 0x4:
1397      case 0xc:   /* in case REXW.b is set */
1398        insn->eaBase = EA_BASE_sib;
1399        if (readSIB(insn) || readDisplacement(insn))
1400          return -1;
1401        break;
1402      default:
1403        insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1404        if (readDisplacement(insn))
1405          return -1;
1406        break;
1407      }
1408      break;
1409    case 0x3:
1410      insn->eaDisplacement = EA_DISP_NONE;
1411      insn->eaBase = (EABase)(insn->eaRegBase + rm);
1412      break;
1413    }
1414    break;
1415  } /* switch (insn->addressSize) */
1416
1417  return 0;
1418}
1419
1420#define GENERIC_FIXUP_FUNC(name, base, prefix)            \
1421  static uint8_t name(struct InternalInstruction *insn,   \
1422                      OperandType type,                   \
1423                      uint8_t index,                      \
1424                      uint8_t *valid) {                   \
1425    *valid = 1;                                           \
1426    switch (type) {                                       \
1427    default:                                              \
1428      debug("Unhandled register type");                   \
1429      *valid = 0;                                         \
1430      return 0;                                           \
1431    case TYPE_Rv:                                         \
1432      return base + index;                                \
1433    case TYPE_R8:                                         \
1434      if (insn->rexPrefix &&                              \
1435         index >= 4 && index <= 7) {                      \
1436        return prefix##_SPL + (index - 4);                \
1437      } else {                                            \
1438        return prefix##_AL + index;                       \
1439      }                                                   \
1440    case TYPE_R16:                                        \
1441      return prefix##_AX + index;                         \
1442    case TYPE_R32:                                        \
1443      return prefix##_EAX + index;                        \
1444    case TYPE_R64:                                        \
1445      return prefix##_RAX + index;                        \
1446    case TYPE_XMM512:                                     \
1447      return prefix##_ZMM0 + index;                       \
1448    case TYPE_XMM256:                                     \
1449      return prefix##_YMM0 + index;                       \
1450    case TYPE_XMM128:                                     \
1451    case TYPE_XMM64:                                      \
1452    case TYPE_XMM32:                                      \
1453    case TYPE_XMM:                                        \
1454      return prefix##_XMM0 + index;                       \
1455    case TYPE_VK1:                                        \
1456    case TYPE_VK8:                                        \
1457    case TYPE_VK16:                                       \
1458      if (index > 7)                                      \
1459        *valid = 0;                                       \
1460      return prefix##_K0 + index;                         \
1461    case TYPE_MM64:                                       \
1462      return prefix##_MM0 + (index & 0x7);                \
1463    case TYPE_SEGMENTREG:                                 \
1464      if (index > 5)                                      \
1465        *valid = 0;                                       \
1466      return prefix##_ES + index;                         \
1467    case TYPE_DEBUGREG:                                   \
1468      return prefix##_DR0 + index;                        \
1469    case TYPE_CONTROLREG:                                 \
1470      return prefix##_CR0 + index;                        \
1471    }                                                     \
1472  }
1473
1474/*
1475 * fixup*Value - Consults an operand type to determine the meaning of the
1476 *   reg or R/M field.  If the operand is an XMM operand, for example, an
1477 *   operand would be XMM0 instead of AX, which readModRM() would otherwise
1478 *   misinterpret it as.
1479 *
1480 * @param insn  - The instruction containing the operand.
1481 * @param type  - The operand type.
1482 * @param index - The existing value of the field as reported by readModRM().
1483 * @param valid - The address of a uint8_t.  The target is set to 1 if the
1484 *                field is valid for the register class; 0 if not.
1485 * @return      - The proper value.
1486 */
1487GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase,    MODRM_REG)
1488GENERIC_FIXUP_FUNC(fixupRMValue,  insn->eaRegBase,  EA_REG)
1489
1490/*
1491 * fixupReg - Consults an operand specifier to determine which of the
1492 *   fixup*Value functions to use in correcting readModRM()'ss interpretation.
1493 *
1494 * @param insn  - See fixup*Value().
1495 * @param op    - The operand specifier.
1496 * @return      - 0 if fixup was successful; -1 if the register returned was
1497 *                invalid for its class.
1498 */
1499static int fixupReg(struct InternalInstruction *insn,
1500                    const struct OperandSpecifier *op) {
1501  uint8_t valid;
1502
1503  dbgprintf(insn, "fixupReg()");
1504
1505  switch ((OperandEncoding)op->encoding) {
1506  default:
1507    debug("Expected a REG or R/M encoding in fixupReg");
1508    return -1;
1509  case ENCODING_VVVV:
1510    insn->vvvv = (Reg)fixupRegValue(insn,
1511                                    (OperandType)op->type,
1512                                    insn->vvvv,
1513                                    &valid);
1514    if (!valid)
1515      return -1;
1516    break;
1517  case ENCODING_REG:
1518    insn->reg = (Reg)fixupRegValue(insn,
1519                                   (OperandType)op->type,
1520                                   insn->reg - insn->regBase,
1521                                   &valid);
1522    if (!valid)
1523      return -1;
1524    break;
1525  CASE_ENCODING_RM:
1526    if (insn->eaBase >= insn->eaRegBase) {
1527      insn->eaBase = (EABase)fixupRMValue(insn,
1528                                          (OperandType)op->type,
1529                                          insn->eaBase - insn->eaRegBase,
1530                                          &valid);
1531      if (!valid)
1532        return -1;
1533    }
1534    break;
1535  }
1536
1537  return 0;
1538}
1539
1540/*
1541 * readOpcodeRegister - Reads an operand from the opcode field of an
1542 *   instruction and interprets it appropriately given the operand width.
1543 *   Handles AddRegFrm instructions.
1544 *
1545 * @param insn  - the instruction whose opcode field is to be read.
1546 * @param size  - The width (in bytes) of the register being specified.
1547 *                1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1548 *                RAX.
1549 * @return      - 0 on success; nonzero otherwise.
1550 */
1551static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1552  dbgprintf(insn, "readOpcodeRegister()");
1553
1554  if (size == 0)
1555    size = insn->registerSize;
1556
1557  switch (size) {
1558  case 1:
1559    insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3)
1560                                                  | (insn->opcode & 7)));
1561    if (insn->rexPrefix &&
1562        insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1563        insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1564      insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1565                                   + (insn->opcodeRegister - MODRM_REG_AL - 4));
1566    }
1567
1568    break;
1569  case 2:
1570    insn->opcodeRegister = (Reg)(MODRM_REG_AX
1571                                 + ((bFromREX(insn->rexPrefix) << 3)
1572                                    | (insn->opcode & 7)));
1573    break;
1574  case 4:
1575    insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1576                                 + ((bFromREX(insn->rexPrefix) << 3)
1577                                    | (insn->opcode & 7)));
1578    break;
1579  case 8:
1580    insn->opcodeRegister = (Reg)(MODRM_REG_RAX
1581                                 + ((bFromREX(insn->rexPrefix) << 3)
1582                                    | (insn->opcode & 7)));
1583    break;
1584  }
1585
1586  return 0;
1587}
1588
1589/*
1590 * readImmediate - Consumes an immediate operand from an instruction, given the
1591 *   desired operand size.
1592 *
1593 * @param insn  - The instruction whose operand is to be read.
1594 * @param size  - The width (in bytes) of the operand.
1595 * @return      - 0 if the immediate was successfully consumed; nonzero
1596 *                otherwise.
1597 */
1598static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1599  uint8_t imm8;
1600  uint16_t imm16;
1601  uint32_t imm32;
1602  uint64_t imm64;
1603
1604  dbgprintf(insn, "readImmediate()");
1605
1606  if (insn->numImmediatesConsumed == 2) {
1607    debug("Already consumed two immediates");
1608    return -1;
1609  }
1610
1611  if (size == 0)
1612    size = insn->immediateSize;
1613  else
1614    insn->immediateSize = size;
1615  insn->immediateOffset = insn->readerCursor - insn->startLocation;
1616
1617  switch (size) {
1618  case 1:
1619    if (consumeByte(insn, &imm8))
1620      return -1;
1621    insn->immediates[insn->numImmediatesConsumed] = imm8;
1622    break;
1623  case 2:
1624    if (consumeUInt16(insn, &imm16))
1625      return -1;
1626    insn->immediates[insn->numImmediatesConsumed] = imm16;
1627    break;
1628  case 4:
1629    if (consumeUInt32(insn, &imm32))
1630      return -1;
1631    insn->immediates[insn->numImmediatesConsumed] = imm32;
1632    break;
1633  case 8:
1634    if (consumeUInt64(insn, &imm64))
1635      return -1;
1636    insn->immediates[insn->numImmediatesConsumed] = imm64;
1637    break;
1638  }
1639
1640  insn->numImmediatesConsumed++;
1641
1642  return 0;
1643}
1644
1645/*
1646 * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1647 *
1648 * @param insn  - The instruction whose operand is to be read.
1649 * @return      - 0 if the vvvv was successfully consumed; nonzero
1650 *                otherwise.
1651 */
1652static int readVVVV(struct InternalInstruction* insn) {
1653  dbgprintf(insn, "readVVVV()");
1654
1655  int vvvv;
1656  if (insn->vectorExtensionType == TYPE_EVEX)
1657    vvvv = (v2FromEVEX4of4(insn->vectorExtensionPrefix[3]) << 4 |
1658            vvvvFromEVEX3of4(insn->vectorExtensionPrefix[2]));
1659  else if (insn->vectorExtensionType == TYPE_VEX_3B)
1660    vvvv = vvvvFromVEX3of3(insn->vectorExtensionPrefix[2]);
1661  else if (insn->vectorExtensionType == TYPE_VEX_2B)
1662    vvvv = vvvvFromVEX2of2(insn->vectorExtensionPrefix[1]);
1663  else if (insn->vectorExtensionType == TYPE_XOP)
1664    vvvv = vvvvFromXOP3of3(insn->vectorExtensionPrefix[2]);
1665  else
1666    return -1;
1667
1668  if (insn->mode != MODE_64BIT)
1669    vvvv &= 0x7;
1670
1671  insn->vvvv = static_cast<Reg>(vvvv);
1672  return 0;
1673}
1674
1675/*
1676 * readMaskRegister - Reads an mask register from the opcode field of an
1677 *   instruction.
1678 *
1679 * @param insn    - The instruction whose opcode field is to be read.
1680 * @return        - 0 on success; nonzero otherwise.
1681 */
1682static int readMaskRegister(struct InternalInstruction* insn) {
1683  dbgprintf(insn, "readMaskRegister()");
1684
1685  if (insn->vectorExtensionType != TYPE_EVEX)
1686    return -1;
1687
1688  insn->writemask =
1689      static_cast<Reg>(aaaFromEVEX4of4(insn->vectorExtensionPrefix[3]));
1690  return 0;
1691}
1692
1693/*
1694 * readOperands - Consults the specifier for an instruction and consumes all
1695 *   operands for that instruction, interpreting them as it goes.
1696 *
1697 * @param insn  - The instruction whose operands are to be read and interpreted.
1698 * @return      - 0 if all operands could be read; nonzero otherwise.
1699 */
1700static int readOperands(struct InternalInstruction* insn) {
1701  int hasVVVV, needVVVV;
1702  int sawRegImm = 0;
1703
1704  dbgprintf(insn, "readOperands()");
1705
1706  /* If non-zero vvvv specified, need to make sure one of the operands
1707     uses it. */
1708  hasVVVV = !readVVVV(insn);
1709  needVVVV = hasVVVV && (insn->vvvv != 0);
1710
1711  for (const auto &Op : x86OperandSets[insn->spec->operands]) {
1712    switch (Op.encoding) {
1713    case ENCODING_NONE:
1714    case ENCODING_SI:
1715    case ENCODING_DI:
1716      break;
1717    case ENCODING_REG:
1718    CASE_ENCODING_RM:
1719      if (readModRM(insn))
1720        return -1;
1721      if (fixupReg(insn, &Op))
1722        return -1;
1723      // Apply the AVX512 compressed displacement scaling factor.
1724      if (Op.encoding != ENCODING_REG && insn->eaDisplacement == EA_DISP_8)
1725        insn->displacement *= 1 << (Op.encoding - ENCODING_RM);
1726      break;
1727    case ENCODING_CB:
1728    case ENCODING_CW:
1729    case ENCODING_CD:
1730    case ENCODING_CP:
1731    case ENCODING_CO:
1732    case ENCODING_CT:
1733      dbgprintf(insn, "We currently don't hande code-offset encodings");
1734      return -1;
1735    case ENCODING_IB:
1736      if (sawRegImm) {
1737        /* Saw a register immediate so don't read again and instead split the
1738           previous immediate.  FIXME: This is a hack. */
1739        insn->immediates[insn->numImmediatesConsumed] =
1740          insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1741        ++insn->numImmediatesConsumed;
1742        break;
1743      }
1744      if (readImmediate(insn, 1))
1745        return -1;
1746      if (Op.type == TYPE_XMM128 ||
1747          Op.type == TYPE_XMM256)
1748        sawRegImm = 1;
1749      break;
1750    case ENCODING_IW:
1751      if (readImmediate(insn, 2))
1752        return -1;
1753      break;
1754    case ENCODING_ID:
1755      if (readImmediate(insn, 4))
1756        return -1;
1757      break;
1758    case ENCODING_IO:
1759      if (readImmediate(insn, 8))
1760        return -1;
1761      break;
1762    case ENCODING_Iv:
1763      if (readImmediate(insn, insn->immediateSize))
1764        return -1;
1765      break;
1766    case ENCODING_Ia:
1767      if (readImmediate(insn, insn->addressSize))
1768        return -1;
1769      break;
1770    case ENCODING_RB:
1771      if (readOpcodeRegister(insn, 1))
1772        return -1;
1773      break;
1774    case ENCODING_RW:
1775      if (readOpcodeRegister(insn, 2))
1776        return -1;
1777      break;
1778    case ENCODING_RD:
1779      if (readOpcodeRegister(insn, 4))
1780        return -1;
1781      break;
1782    case ENCODING_RO:
1783      if (readOpcodeRegister(insn, 8))
1784        return -1;
1785      break;
1786    case ENCODING_Rv:
1787      if (readOpcodeRegister(insn, 0))
1788        return -1;
1789      break;
1790    case ENCODING_FP:
1791      break;
1792    case ENCODING_VVVV:
1793      needVVVV = 0; /* Mark that we have found a VVVV operand. */
1794      if (!hasVVVV)
1795        return -1;
1796      if (fixupReg(insn, &Op))
1797        return -1;
1798      break;
1799    case ENCODING_WRITEMASK:
1800      if (readMaskRegister(insn))
1801        return -1;
1802      break;
1803    case ENCODING_DUP:
1804      break;
1805    default:
1806      dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1807      return -1;
1808    }
1809  }
1810
1811  /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1812  if (needVVVV) return -1;
1813
1814  return 0;
1815}
1816
1817/*
1818 * decodeInstruction - Reads and interprets a full instruction provided by the
1819 *   user.
1820 *
1821 * @param insn      - A pointer to the instruction to be populated.  Must be
1822 *                    pre-allocated.
1823 * @param reader    - The function to be used to read the instruction's bytes.
1824 * @param readerArg - A generic argument to be passed to the reader to store
1825 *                    any internal state.
1826 * @param logger    - If non-NULL, the function to be used to write log messages
1827 *                    and warnings.
1828 * @param loggerArg - A generic argument to be passed to the logger to store
1829 *                    any internal state.
1830 * @param startLoc  - The address (in the reader's address space) of the first
1831 *                    byte in the instruction.
1832 * @param mode      - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1833 *                    decode the instruction in.
1834 * @return          - 0 if the instruction's memory could be read; nonzero if
1835 *                    not.
1836 */
1837int llvm::X86Disassembler::decodeInstruction(
1838    struct InternalInstruction *insn, byteReader_t reader,
1839    const void *readerArg, dlog_t logger, void *loggerArg, const void *miiArg,
1840    uint64_t startLoc, DisassemblerMode mode) {
1841  memset(insn, 0, sizeof(struct InternalInstruction));
1842
1843  insn->reader = reader;
1844  insn->readerArg = readerArg;
1845  insn->dlog = logger;
1846  insn->dlogArg = loggerArg;
1847  insn->startLocation = startLoc;
1848  insn->readerCursor = startLoc;
1849  insn->mode = mode;
1850  insn->numImmediatesConsumed = 0;
1851
1852  if (readPrefixes(insn)       ||
1853      readOpcode(insn)         ||
1854      getID(insn, miiArg)      ||
1855      insn->instructionID == 0 ||
1856      readOperands(insn))
1857    return -1;
1858
1859  insn->operands = x86OperandSets[insn->spec->operands];
1860
1861  insn->length = insn->readerCursor - insn->startLocation;
1862
1863  dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1864            startLoc, insn->readerCursor, insn->length);
1865
1866  if (insn->length > 15)
1867    dbgprintf(insn, "Instruction exceeds 15-byte limit");
1868
1869  return 0;
1870}
1871