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