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