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