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