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