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