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