Emacs-tag and some comment fix for all ARM, CellSPU, Hexagon, MBlaze, MSP430, PPC...
[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   return 0;
90 }
91
92 /*
93  * decode - Reads the appropriate instruction table to obtain the unique ID of
94  *   an instruction.
95  *
96  * @param type        - See modRMRequired().
97  * @param insnContext - See modRMRequired().
98  * @param opcode      - See modRMRequired().
99  * @param modRM       - The ModR/M byte if required, or any value if not.
100  * @return            - The UID of the instruction, or 0 on failure.
101  */
102 static InstrUID decode(OpcodeType type,
103                        InstructionContext insnContext,
104                        uint8_t opcode,
105                        uint8_t modRM) {
106   const struct ModRMDecision* dec = 0;
107   
108   switch (type) {
109   case ONEBYTE:
110     dec = &ONEBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
111     break;
112   case TWOBYTE:
113     dec = &TWOBYTE_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
114     break;
115   case THREEBYTE_38:
116     dec = &THREEBYTE38_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
117     break;
118   case THREEBYTE_3A:
119     dec = &THREEBYTE3A_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
120     break;
121   case THREEBYTE_A6:
122     dec = &THREEBYTEA6_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
123     break;
124   case THREEBYTE_A7:
125     dec = &THREEBYTEA7_SYM.opcodeDecisions[insnContext].modRMDecisions[opcode];
126     break;
127   }
128   
129   switch (dec->modrm_type) {
130   default:
131     debug("Corrupt table!  Unknown modrm_type");
132     return 0;
133   case MODRM_ONEENTRY:
134     return modRMTable[dec->instructionIDs];
135   case MODRM_SPLITRM:
136     if (modFromModRM(modRM) == 0x3)
137       return modRMTable[dec->instructionIDs+1];
138     return modRMTable[dec->instructionIDs];
139   case MODRM_SPLITREG:
140     if (modFromModRM(modRM) == 0x3)
141       return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)+8];
142     return modRMTable[dec->instructionIDs+((modRM & 0x38) >> 3)];
143   case MODRM_FULL:
144     return modRMTable[dec->instructionIDs+modRM];
145   }
146 }
147
148 /*
149  * specifierForUID - Given a UID, returns the name and operand specification for
150  *   that instruction.
151  *
152  * @param uid - The unique ID for the instruction.  This should be returned by
153  *              decode(); specifierForUID will not check bounds.
154  * @return    - A pointer to the specification for that instruction.
155  */
156 static const struct InstructionSpecifier *specifierForUID(InstrUID uid) {
157   return &INSTRUCTIONS_SYM[uid];
158 }
159
160 /*
161  * consumeByte - Uses the reader function provided by the user to consume one
162  *   byte from the instruction's memory and advance the cursor.
163  *
164  * @param insn  - The instruction with the reader function to use.  The cursor
165  *                for this instruction is advanced.
166  * @param byte  - A pointer to a pre-allocated memory buffer to be populated
167  *                with the data read.
168  * @return      - 0 if the read was successful; nonzero otherwise.
169  */
170 static int consumeByte(struct InternalInstruction* insn, uint8_t* byte) {
171   int ret = insn->reader(insn->readerArg, byte, insn->readerCursor);
172   
173   if (!ret)
174     ++(insn->readerCursor);
175   
176   return ret;
177 }
178
179 /*
180  * lookAtByte - Like consumeByte, but does not advance the cursor.
181  *
182  * @param insn  - See consumeByte().
183  * @param byte  - See consumeByte().
184  * @return      - See consumeByte().
185  */
186 static int lookAtByte(struct InternalInstruction* insn, uint8_t* byte) {
187   return insn->reader(insn->readerArg, byte, insn->readerCursor);
188 }
189
190 static void unconsumeByte(struct InternalInstruction* insn) {
191   insn->readerCursor--;
192 }
193
194 #define CONSUME_FUNC(name, type)                                  \
195   static int name(struct InternalInstruction* insn, type* ptr) {  \
196     type combined = 0;                                            \
197     unsigned offset;                                              \
198     for (offset = 0; offset < sizeof(type); ++offset) {           \
199       uint8_t byte;                                               \
200       int ret = insn->reader(insn->readerArg,                     \
201                              &byte,                               \
202                              insn->readerCursor + offset);        \
203       if (ret)                                                    \
204         return ret;                                               \
205       combined = combined | ((type)byte << ((type)offset * 8));   \
206     }                                                             \
207     *ptr = combined;                                              \
208     insn->readerCursor += sizeof(type);                           \
209     return 0;                                                     \
210   }
211
212 /*
213  * consume* - Use the reader function provided by the user to consume data
214  *   values of various sizes from the instruction's memory and advance the
215  *   cursor appropriately.  These readers perform endian conversion.
216  *
217  * @param insn    - See consumeByte().
218  * @param ptr     - A pointer to a pre-allocated memory of appropriate size to
219  *                  be populated with the data read.
220  * @return        - See consumeByte().
221  */
222 CONSUME_FUNC(consumeInt8, int8_t)
223 CONSUME_FUNC(consumeInt16, int16_t)
224 CONSUME_FUNC(consumeInt32, int32_t)
225 CONSUME_FUNC(consumeUInt16, uint16_t)
226 CONSUME_FUNC(consumeUInt32, uint32_t)
227 CONSUME_FUNC(consumeUInt64, uint64_t)
228
229 /*
230  * dbgprintf - Uses the logging function provided by the user to log a single
231  *   message, typically without a carriage-return.
232  *
233  * @param insn    - The instruction containing the logging function.
234  * @param format  - See printf().
235  * @param ...     - See printf().
236  */
237 static void dbgprintf(struct InternalInstruction* insn,
238                       const char* format,
239                       ...) {  
240   char buffer[256];
241   va_list ap;
242   
243   if (!insn->dlog)
244     return;
245     
246   va_start(ap, format);
247   (void)vsnprintf(buffer, sizeof(buffer), format, ap);
248   va_end(ap);
249   
250   insn->dlog(insn->dlogArg, buffer);
251   
252   return;
253 }
254
255 /*
256  * setPrefixPresent - Marks that a particular prefix is present at a particular
257  *   location.
258  *
259  * @param insn      - The instruction to be marked as having the prefix.
260  * @param prefix    - The prefix that is present.
261  * @param location  - The location where the prefix is located (in the address
262  *                    space of the instruction's reader).
263  */
264 static void setPrefixPresent(struct InternalInstruction* insn,
265                                     uint8_t prefix,
266                                     uint64_t location)
267 {
268   insn->prefixPresent[prefix] = 1;
269   insn->prefixLocations[prefix] = location;
270 }
271
272 /*
273  * isPrefixAtLocation - Queries an instruction to determine whether a prefix is
274  *   present at a given location.
275  *
276  * @param insn      - The instruction to be queried.
277  * @param prefix    - The prefix.
278  * @param location  - The location to query.
279  * @return          - Whether the prefix is at that location.
280  */
281 static BOOL isPrefixAtLocation(struct InternalInstruction* insn,
282                                uint8_t prefix,
283                                uint64_t location)
284 {
285   if (insn->prefixPresent[prefix] == 1 &&
286      insn->prefixLocations[prefix] == location)
287     return TRUE;
288   else
289     return FALSE;
290 }
291
292 /*
293  * readPrefixes - Consumes all of an instruction's prefix bytes, and marks the
294  *   instruction as having them.  Also sets the instruction's default operand,
295  *   address, and other relevant data sizes to report operands correctly.
296  *
297  * @param insn  - The instruction whose prefixes are to be read.
298  * @return      - 0 if the instruction could be read until the end of the prefix
299  *                bytes, and no prefixes conflicted; nonzero otherwise.
300  */
301 static int readPrefixes(struct InternalInstruction* insn) {
302   BOOL isPrefix = TRUE;
303   BOOL prefixGroups[4] = { FALSE };
304   uint64_t prefixLocation;
305   uint8_t byte = 0;
306   
307   BOOL hasAdSize = FALSE;
308   BOOL hasOpSize = FALSE;
309   
310   dbgprintf(insn, "readPrefixes()");
311     
312   while (isPrefix) {
313     prefixLocation = insn->readerCursor;
314     
315     if (consumeByte(insn, &byte))
316       return -1;
317     
318     switch (byte) {
319     case 0xf0:  /* LOCK */
320     case 0xf2:  /* REPNE/REPNZ */
321     case 0xf3:  /* REP or REPE/REPZ */
322       if (prefixGroups[0])
323         dbgprintf(insn, "Redundant Group 1 prefix");
324       prefixGroups[0] = TRUE;
325       setPrefixPresent(insn, byte, prefixLocation);
326       break;
327     case 0x2e:  /* CS segment override -OR- Branch not taken */
328     case 0x36:  /* SS segment override -OR- Branch taken */
329     case 0x3e:  /* DS segment override */
330     case 0x26:  /* ES segment override */
331     case 0x64:  /* FS segment override */
332     case 0x65:  /* GS segment override */
333       switch (byte) {
334       case 0x2e:
335         insn->segmentOverride = SEG_OVERRIDE_CS;
336         break;
337       case 0x36:
338         insn->segmentOverride = SEG_OVERRIDE_SS;
339         break;
340       case 0x3e:
341         insn->segmentOverride = SEG_OVERRIDE_DS;
342         break;
343       case 0x26:
344         insn->segmentOverride = SEG_OVERRIDE_ES;
345         break;
346       case 0x64:
347         insn->segmentOverride = SEG_OVERRIDE_FS;
348         break;
349       case 0x65:
350         insn->segmentOverride = SEG_OVERRIDE_GS;
351         break;
352       default:
353         debug("Unhandled override");
354         return -1;
355       }
356       if (prefixGroups[1])
357         dbgprintf(insn, "Redundant Group 2 prefix");
358       prefixGroups[1] = TRUE;
359       setPrefixPresent(insn, byte, prefixLocation);
360       break;
361     case 0x66:  /* Operand-size override */
362       if (prefixGroups[2])
363         dbgprintf(insn, "Redundant Group 3 prefix");
364       prefixGroups[2] = TRUE;
365       hasOpSize = TRUE;
366       setPrefixPresent(insn, byte, prefixLocation);
367       break;
368     case 0x67:  /* Address-size override */
369       if (prefixGroups[3])
370         dbgprintf(insn, "Redundant Group 4 prefix");
371       prefixGroups[3] = TRUE;
372       hasAdSize = TRUE;
373       setPrefixPresent(insn, byte, prefixLocation);
374       break;
375     default:    /* Not a prefix byte */
376       isPrefix = FALSE;
377       break;
378     }
379     
380     if (isPrefix)
381       dbgprintf(insn, "Found prefix 0x%hhx", byte);
382   }
383     
384   insn->vexSize = 0;
385   
386   if (byte == 0xc4) {
387     uint8_t byte1;
388       
389     if (lookAtByte(insn, &byte1)) {
390       dbgprintf(insn, "Couldn't read second byte of VEX");
391       return -1;
392     }
393     
394     if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
395       insn->vexSize = 3;
396       insn->necessaryPrefixLocation = insn->readerCursor - 1;
397     }
398     else {
399       unconsumeByte(insn);
400       insn->necessaryPrefixLocation = insn->readerCursor - 1;
401     }
402     
403     if (insn->vexSize == 3) {
404       insn->vexPrefix[0] = byte;
405       consumeByte(insn, &insn->vexPrefix[1]);
406       consumeByte(insn, &insn->vexPrefix[2]);
407
408       /* We simulate the REX prefix for simplicity's sake */
409    
410       if (insn->mode == MODE_64BIT) {
411         insn->rexPrefix = 0x40 
412                         | (wFromVEX3of3(insn->vexPrefix[2]) << 3)
413                         | (rFromVEX2of3(insn->vexPrefix[1]) << 2)
414                         | (xFromVEX2of3(insn->vexPrefix[1]) << 1)
415                         | (bFromVEX2of3(insn->vexPrefix[1]) << 0);
416       }
417     
418       switch (ppFromVEX3of3(insn->vexPrefix[2]))
419       {
420       default:
421         break;
422       case VEX_PREFIX_66:
423         hasOpSize = TRUE;      
424         break;
425       }
426     
427       dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1], insn->vexPrefix[2]);
428     }
429   }
430   else if (byte == 0xc5) {
431     uint8_t byte1;
432     
433     if (lookAtByte(insn, &byte1)) {
434       dbgprintf(insn, "Couldn't read second byte of VEX");
435       return -1;
436     }
437       
438     if (insn->mode == MODE_64BIT || (byte1 & 0xc0) == 0xc0) {
439       insn->vexSize = 2;
440     }
441     else {
442       unconsumeByte(insn);
443     }
444     
445     if (insn->vexSize == 2) {
446       insn->vexPrefix[0] = byte;
447       consumeByte(insn, &insn->vexPrefix[1]);
448         
449       if (insn->mode == MODE_64BIT) {
450         insn->rexPrefix = 0x40 
451                         | (rFromVEX2of2(insn->vexPrefix[1]) << 2);
452       }
453         
454       switch (ppFromVEX2of2(insn->vexPrefix[1]))
455       {
456       default:
457         break;
458       case VEX_PREFIX_66:
459         hasOpSize = TRUE;      
460         break;
461       }
462          
463       dbgprintf(insn, "Found VEX prefix 0x%hhx 0x%hhx", insn->vexPrefix[0], insn->vexPrefix[1]);
464     }
465   }
466   else {
467     if (insn->mode == MODE_64BIT) {
468       if ((byte & 0xf0) == 0x40) {
469         uint8_t opcodeByte;
470           
471         if (lookAtByte(insn, &opcodeByte) || ((opcodeByte & 0xf0) == 0x40)) {
472           dbgprintf(insn, "Redundant REX prefix");
473           return -1;
474         }
475           
476         insn->rexPrefix = byte;
477         insn->necessaryPrefixLocation = insn->readerCursor - 2;
478           
479         dbgprintf(insn, "Found REX prefix 0x%hhx", byte);
480       } else {                
481         unconsumeByte(insn);
482         insn->necessaryPrefixLocation = insn->readerCursor - 1;
483       }
484     } else {
485       unconsumeByte(insn);
486       insn->necessaryPrefixLocation = insn->readerCursor - 1;
487     }
488   }
489
490   if (insn->mode == MODE_16BIT) {
491     insn->registerSize       = (hasOpSize ? 4 : 2);
492     insn->addressSize        = (hasAdSize ? 4 : 2);
493     insn->displacementSize   = (hasAdSize ? 4 : 2);
494     insn->immediateSize      = (hasOpSize ? 4 : 2);
495   } else if (insn->mode == MODE_32BIT) {
496     insn->registerSize       = (hasOpSize ? 2 : 4);
497     insn->addressSize        = (hasAdSize ? 2 : 4);
498     insn->displacementSize   = (hasAdSize ? 2 : 4);
499     insn->immediateSize      = (hasOpSize ? 2 : 4);
500   } else if (insn->mode == MODE_64BIT) {
501     if (insn->rexPrefix && wFromREX(insn->rexPrefix)) {
502       insn->registerSize       = 8;
503       insn->addressSize        = (hasAdSize ? 4 : 8);
504       insn->displacementSize   = 4;
505       insn->immediateSize      = 4;
506     } else if (insn->rexPrefix) {
507       insn->registerSize       = (hasOpSize ? 2 : 4);
508       insn->addressSize        = (hasAdSize ? 4 : 8);
509       insn->displacementSize   = (hasOpSize ? 2 : 4);
510       insn->immediateSize      = (hasOpSize ? 2 : 4);
511     } else {
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     }
517   }
518   
519   return 0;
520 }
521
522 /*
523  * readOpcode - Reads the opcode (excepting the ModR/M byte in the case of
524  *   extended or escape opcodes).
525  *
526  * @param insn  - The instruction whose opcode is to be read.
527  * @return      - 0 if the opcode could be read successfully; nonzero otherwise.
528  */
529 static int readOpcode(struct InternalInstruction* insn) {  
530   /* Determine the length of the primary opcode */
531   
532   uint8_t current;
533   
534   dbgprintf(insn, "readOpcode()");
535   
536   insn->opcodeType = ONEBYTE;
537     
538   if (insn->vexSize == 3)
539   {
540     switch (mmmmmFromVEX2of3(insn->vexPrefix[1]))
541     {
542     default:
543       dbgprintf(insn, "Unhandled m-mmmm field for instruction (0x%hhx)", mmmmmFromVEX2of3(insn->vexPrefix[1]));
544       return -1;      
545     case 0:
546       break;
547     case VEX_LOB_0F:
548       insn->twoByteEscape = 0x0f;
549       insn->opcodeType = TWOBYTE;
550       return consumeByte(insn, &insn->opcode);
551     case VEX_LOB_0F38:
552       insn->twoByteEscape = 0x0f;
553       insn->threeByteEscape = 0x38;
554       insn->opcodeType = THREEBYTE_38;
555       return consumeByte(insn, &insn->opcode);
556     case VEX_LOB_0F3A:    
557       insn->twoByteEscape = 0x0f;
558       insn->threeByteEscape = 0x3a;
559       insn->opcodeType = THREEBYTE_3A;
560       return consumeByte(insn, &insn->opcode);
561     }
562   }
563   else if (insn->vexSize == 2)
564   {
565     insn->twoByteEscape = 0x0f;
566     insn->opcodeType = TWOBYTE;
567     return consumeByte(insn, &insn->opcode);
568   }
569     
570   if (consumeByte(insn, &current))
571     return -1;
572   
573   if (current == 0x0f) {
574     dbgprintf(insn, "Found a two-byte escape prefix (0x%hhx)", current);
575     
576     insn->twoByteEscape = current;
577     
578     if (consumeByte(insn, &current))
579       return -1;
580     
581     if (current == 0x38) {
582       dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
583       
584       insn->threeByteEscape = current;
585       
586       if (consumeByte(insn, &current))
587         return -1;
588       
589       insn->opcodeType = THREEBYTE_38;
590     } else if (current == 0x3a) {
591       dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
592       
593       insn->threeByteEscape = current;
594       
595       if (consumeByte(insn, &current))
596         return -1;
597       
598       insn->opcodeType = THREEBYTE_3A;
599     } else if (current == 0xa6) {
600       dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
601       
602       insn->threeByteEscape = current;
603       
604       if (consumeByte(insn, &current))
605         return -1;
606       
607       insn->opcodeType = THREEBYTE_A6;
608     } else if (current == 0xa7) {
609       dbgprintf(insn, "Found a three-byte escape prefix (0x%hhx)", current);
610       
611       insn->threeByteEscape = current;
612       
613       if (consumeByte(insn, &current))
614         return -1;
615       
616       insn->opcodeType = THREEBYTE_A7;
617     } else {
618       dbgprintf(insn, "Didn't find a three-byte escape prefix");
619       
620       insn->opcodeType = TWOBYTE;
621     }
622   }
623   
624   /*
625    * At this point we have consumed the full opcode.
626    * Anything we consume from here on must be unconsumed.
627    */
628   
629   insn->opcode = current;
630   
631   return 0;
632 }
633
634 static int readModRM(struct InternalInstruction* insn);
635
636 /*
637  * getIDWithAttrMask - Determines the ID of an instruction, consuming
638  *   the ModR/M byte as appropriate for extended and escape opcodes,
639  *   and using a supplied attribute mask.
640  *
641  * @param instructionID - A pointer whose target is filled in with the ID of the
642  *                        instruction.
643  * @param insn          - The instruction whose ID is to be determined.
644  * @param attrMask      - The attribute mask to search.
645  * @return              - 0 if the ModR/M could be read when needed or was not
646  *                        needed; nonzero otherwise.
647  */
648 static int getIDWithAttrMask(uint16_t* instructionID,
649                              struct InternalInstruction* insn,
650                              uint8_t attrMask) {
651   BOOL hasModRMExtension;
652   
653   uint8_t instructionClass;
654
655   instructionClass = contextForAttrs(attrMask);
656   
657   hasModRMExtension = modRMRequired(insn->opcodeType,
658                                     instructionClass,
659                                     insn->opcode);
660   
661   if (hasModRMExtension) {
662     if (readModRM(insn))
663       return -1;
664     
665     *instructionID = decode(insn->opcodeType,
666                             instructionClass,
667                             insn->opcode,
668                             insn->modRM);
669   } else {
670     *instructionID = decode(insn->opcodeType,
671                             instructionClass,
672                             insn->opcode,
673                             0);
674   }
675       
676   return 0;
677 }
678
679 /*
680  * is16BitEquivalent - Determines whether two instruction names refer to
681  * equivalent instructions but one is 16-bit whereas the other is not.
682  *
683  * @param orig  - The instruction that is not 16-bit
684  * @param equiv - The instruction that is 16-bit
685  */
686 static BOOL is16BitEquvalent(const char* orig, const char* equiv) {
687   off_t i;
688   
689   for (i = 0;; i++) {
690     if (orig[i] == '\0' && equiv[i] == '\0')
691       return TRUE;
692     if (orig[i] == '\0' || equiv[i] == '\0')
693       return FALSE;
694     if (orig[i] != equiv[i]) {
695       if ((orig[i] == 'Q' || orig[i] == 'L') && equiv[i] == 'W')
696         continue;
697       if ((orig[i] == '6' || orig[i] == '3') && equiv[i] == '1')
698         continue;
699       if ((orig[i] == '4' || orig[i] == '2') && equiv[i] == '6')
700         continue;
701       return FALSE;
702     }
703   }
704 }
705
706 /*
707  * getID - Determines the ID of an instruction, consuming the ModR/M byte as 
708  *   appropriate for extended and escape opcodes.  Determines the attributes and 
709  *   context for the instruction before doing so.
710  *
711  * @param insn  - The instruction whose ID is to be determined.
712  * @return      - 0 if the ModR/M could be read when needed or was not needed;
713  *                nonzero otherwise.
714  */
715 static int getID(struct InternalInstruction* insn, void *miiArg) {
716   uint8_t attrMask;
717   uint16_t instructionID;
718   
719   dbgprintf(insn, "getID()");
720     
721   attrMask = ATTR_NONE;
722
723   if (insn->mode == MODE_64BIT)
724     attrMask |= ATTR_64BIT;
725     
726   if (insn->vexSize) {
727     attrMask |= ATTR_VEX;
728
729     if (insn->vexSize == 3) {
730       switch (ppFromVEX3of3(insn->vexPrefix[2])) {
731       case VEX_PREFIX_66:
732         attrMask |= ATTR_OPSIZE;    
733         break;
734       case VEX_PREFIX_F3:
735         attrMask |= ATTR_XS;
736         break;
737       case VEX_PREFIX_F2:
738         attrMask |= ATTR_XD;
739         break;
740       }
741     
742       if (lFromVEX3of3(insn->vexPrefix[2]))
743         attrMask |= ATTR_VEXL;
744     }
745     else if (insn->vexSize == 2) {
746       switch (ppFromVEX2of2(insn->vexPrefix[1])) {
747       case VEX_PREFIX_66:
748         attrMask |= ATTR_OPSIZE;    
749         break;
750       case VEX_PREFIX_F3:
751         attrMask |= ATTR_XS;
752         break;
753       case VEX_PREFIX_F2:
754         attrMask |= ATTR_XD;
755         break;
756       }
757     
758       if (lFromVEX2of2(insn->vexPrefix[1]))
759         attrMask |= ATTR_VEXL;
760     }
761     else {
762       return -1;
763     }
764   }
765   else {
766     if (isPrefixAtLocation(insn, 0x66, insn->necessaryPrefixLocation))
767       attrMask |= ATTR_OPSIZE;
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   
1020   switch (insn->eaDisplacement) {
1021   case EA_DISP_NONE:
1022     insn->consumedDisplacement = FALSE;
1023     break;
1024   case EA_DISP_8:
1025     if (consumeInt8(insn, &d8))
1026       return -1;
1027     insn->displacement = d8;
1028     break;
1029   case EA_DISP_16:
1030     if (consumeInt16(insn, &d16))
1031       return -1;
1032     insn->displacement = d16;
1033     break;
1034   case EA_DISP_32:
1035     if (consumeInt32(insn, &d32))
1036       return -1;
1037     insn->displacement = d32;
1038     break;
1039   }
1040   
1041   insn->consumedDisplacement = TRUE;
1042   return 0;
1043 }
1044
1045 /*
1046  * readModRM - Consumes all addressing information (ModR/M byte, SIB byte, and
1047  *   displacement) for an instruction and interprets it.
1048  *
1049  * @param insn  - The instruction whose addressing information is to be read.
1050  * @return      - 0 if the information was successfully read; nonzero otherwise.
1051  */
1052 static int readModRM(struct InternalInstruction* insn) {  
1053   uint8_t mod, rm, reg;
1054   
1055   dbgprintf(insn, "readModRM()");
1056   
1057   if (insn->consumedModRM)
1058     return 0;
1059   
1060   if (consumeByte(insn, &insn->modRM))
1061     return -1;
1062   insn->consumedModRM = TRUE;
1063   
1064   mod     = modFromModRM(insn->modRM);
1065   rm      = rmFromModRM(insn->modRM);
1066   reg     = regFromModRM(insn->modRM);
1067   
1068   /*
1069    * This goes by insn->registerSize to pick the correct register, which messes
1070    * up if we're using (say) XMM or 8-bit register operands.  That gets fixed in
1071    * fixupReg().
1072    */
1073   switch (insn->registerSize) {
1074   case 2:
1075     insn->regBase = MODRM_REG_AX;
1076     insn->eaRegBase = EA_REG_AX;
1077     break;
1078   case 4:
1079     insn->regBase = MODRM_REG_EAX;
1080     insn->eaRegBase = EA_REG_EAX;
1081     break;
1082   case 8:
1083     insn->regBase = MODRM_REG_RAX;
1084     insn->eaRegBase = EA_REG_RAX;
1085     break;
1086   }
1087   
1088   reg |= rFromREX(insn->rexPrefix) << 3;
1089   rm  |= bFromREX(insn->rexPrefix) << 3;
1090   
1091   insn->reg = (Reg)(insn->regBase + reg);
1092   
1093   switch (insn->addressSize) {
1094   case 2:
1095     insn->eaBaseBase = EA_BASE_BX_SI;
1096      
1097     switch (mod) {
1098     case 0x0:
1099       if (rm == 0x6) {
1100         insn->eaBase = EA_BASE_NONE;
1101         insn->eaDisplacement = EA_DISP_16;
1102         if (readDisplacement(insn))
1103           return -1;
1104       } else {
1105         insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1106         insn->eaDisplacement = EA_DISP_NONE;
1107       }
1108       break;
1109     case 0x1:
1110       insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1111       insn->eaDisplacement = EA_DISP_8;
1112       if (readDisplacement(insn))
1113         return -1;
1114       break;
1115     case 0x2:
1116       insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1117       insn->eaDisplacement = EA_DISP_16;
1118       if (readDisplacement(insn))
1119         return -1;
1120       break;
1121     case 0x3:
1122       insn->eaBase = (EABase)(insn->eaRegBase + rm);
1123       if (readDisplacement(insn))
1124         return -1;
1125       break;
1126     }
1127     break;
1128   case 4:
1129   case 8:
1130     insn->eaBaseBase = (insn->addressSize == 4 ? EA_BASE_EAX : EA_BASE_RAX);
1131     
1132     switch (mod) {
1133     case 0x0:
1134       insn->eaDisplacement = EA_DISP_NONE; /* readSIB may override this */
1135       switch (rm) {
1136       case 0x4:
1137       case 0xc:   /* in case REXW.b is set */
1138         insn->eaBase = (insn->addressSize == 4 ? 
1139                         EA_BASE_sib : EA_BASE_sib64);
1140         readSIB(insn);
1141         if (readDisplacement(insn))
1142           return -1;
1143         break;
1144       case 0x5:
1145         insn->eaBase = EA_BASE_NONE;
1146         insn->eaDisplacement = EA_DISP_32;
1147         if (readDisplacement(insn))
1148           return -1;
1149         break;
1150       default:
1151         insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1152         break;
1153       }
1154       break;
1155     case 0x1:
1156     case 0x2:
1157       insn->eaDisplacement = (mod == 0x1 ? EA_DISP_8 : EA_DISP_32);
1158       switch (rm) {
1159       case 0x4:
1160       case 0xc:   /* in case REXW.b is set */
1161         insn->eaBase = EA_BASE_sib;
1162         readSIB(insn);
1163         if (readDisplacement(insn))
1164           return -1;
1165         break;
1166       default:
1167         insn->eaBase = (EABase)(insn->eaBaseBase + rm);
1168         if (readDisplacement(insn))
1169           return -1;
1170         break;
1171       }
1172       break;
1173     case 0x3:
1174       insn->eaDisplacement = EA_DISP_NONE;
1175       insn->eaBase = (EABase)(insn->eaRegBase + rm);
1176       break;
1177     }
1178     break;
1179   } /* switch (insn->addressSize) */
1180   
1181   return 0;
1182 }
1183
1184 #define GENERIC_FIXUP_FUNC(name, base, prefix)            \
1185   static uint8_t name(struct InternalInstruction *insn,   \
1186                       OperandType type,                   \
1187                       uint8_t index,                      \
1188                       uint8_t *valid) {                   \
1189     *valid = 1;                                           \
1190     switch (type) {                                       \
1191     default:                                              \
1192       debug("Unhandled register type");                   \
1193       *valid = 0;                                         \
1194       return 0;                                           \
1195     case TYPE_Rv:                                         \
1196       return base + index;                                \
1197     case TYPE_R8:                                         \
1198       if (insn->rexPrefix &&                              \
1199          index >= 4 && index <= 7) {                      \
1200         return prefix##_SPL + (index - 4);                \
1201       } else {                                            \
1202         return prefix##_AL + index;                       \
1203       }                                                   \
1204     case TYPE_R16:                                        \
1205       return prefix##_AX + index;                         \
1206     case TYPE_R32:                                        \
1207       return prefix##_EAX + index;                        \
1208     case TYPE_R64:                                        \
1209       return prefix##_RAX + index;                        \
1210     case TYPE_XMM256:                                     \
1211       return prefix##_YMM0 + index;                       \
1212     case TYPE_XMM128:                                     \
1213     case TYPE_XMM64:                                      \
1214     case TYPE_XMM32:                                      \
1215     case TYPE_XMM:                                        \
1216       return prefix##_XMM0 + index;                       \
1217     case TYPE_MM64:                                       \
1218     case TYPE_MM32:                                       \
1219     case TYPE_MM:                                         \
1220       if (index > 7)                                      \
1221         *valid = 0;                                       \
1222       return prefix##_MM0 + index;                        \
1223     case TYPE_SEGMENTREG:                                 \
1224       if (index > 5)                                      \
1225         *valid = 0;                                       \
1226       return prefix##_ES + index;                         \
1227     case TYPE_DEBUGREG:                                   \
1228       if (index > 7)                                      \
1229         *valid = 0;                                       \
1230       return prefix##_DR0 + index;                        \
1231     case TYPE_CONTROLREG:                                 \
1232       if (index > 8)                                      \
1233         *valid = 0;                                       \
1234       return prefix##_CR0 + index;                        \
1235     }                                                     \
1236   }
1237
1238 /*
1239  * fixup*Value - Consults an operand type to determine the meaning of the
1240  *   reg or R/M field.  If the operand is an XMM operand, for example, an
1241  *   operand would be XMM0 instead of AX, which readModRM() would otherwise
1242  *   misinterpret it as.
1243  *
1244  * @param insn  - The instruction containing the operand.
1245  * @param type  - The operand type.
1246  * @param index - The existing value of the field as reported by readModRM().
1247  * @param valid - The address of a uint8_t.  The target is set to 1 if the
1248  *                field is valid for the register class; 0 if not.
1249  * @return      - The proper value.
1250  */
1251 GENERIC_FIXUP_FUNC(fixupRegValue, insn->regBase,    MODRM_REG)
1252 GENERIC_FIXUP_FUNC(fixupRMValue,  insn->eaRegBase,  EA_REG)
1253
1254 /*
1255  * fixupReg - Consults an operand specifier to determine which of the
1256  *   fixup*Value functions to use in correcting readModRM()'ss interpretation.
1257  *
1258  * @param insn  - See fixup*Value().
1259  * @param op    - The operand specifier.
1260  * @return      - 0 if fixup was successful; -1 if the register returned was
1261  *                invalid for its class.
1262  */
1263 static int fixupReg(struct InternalInstruction *insn, 
1264                     const struct OperandSpecifier *op) {
1265   uint8_t valid;
1266   
1267   dbgprintf(insn, "fixupReg()");
1268   
1269   switch ((OperandEncoding)op->encoding) {
1270   default:
1271     debug("Expected a REG or R/M encoding in fixupReg");
1272     return -1;
1273   case ENCODING_VVVV:
1274     insn->vvvv = (Reg)fixupRegValue(insn,
1275                                     (OperandType)op->type,
1276                                     insn->vvvv,
1277                                     &valid);
1278     if (!valid)
1279       return -1;
1280     break;
1281   case ENCODING_REG:
1282     insn->reg = (Reg)fixupRegValue(insn,
1283                                    (OperandType)op->type,
1284                                    insn->reg - insn->regBase,
1285                                    &valid);
1286     if (!valid)
1287       return -1;
1288     break;
1289   case ENCODING_RM:
1290     if (insn->eaBase >= insn->eaRegBase) {
1291       insn->eaBase = (EABase)fixupRMValue(insn,
1292                                           (OperandType)op->type,
1293                                           insn->eaBase - insn->eaRegBase,
1294                                           &valid);
1295       if (!valid)
1296         return -1;
1297     }
1298     break;
1299   }
1300   
1301   return 0;
1302 }
1303
1304 /*
1305  * readOpcodeModifier - Reads an operand from the opcode field of an 
1306  *   instruction.  Handles AddRegFrm instructions.
1307  *
1308  * @param insn    - The instruction whose opcode field is to be read.
1309  * @param inModRM - Indicates that the opcode field is to be read from the
1310  *                  ModR/M extension; useful for escape opcodes
1311  * @return        - 0 on success; nonzero otherwise.
1312  */
1313 static int readOpcodeModifier(struct InternalInstruction* insn) {
1314   dbgprintf(insn, "readOpcodeModifier()");
1315   
1316   if (insn->consumedOpcodeModifier)
1317     return 0;
1318   
1319   insn->consumedOpcodeModifier = TRUE;
1320   
1321   switch (insn->spec->modifierType) {
1322   default:
1323     debug("Unknown modifier type.");
1324     return -1;
1325   case MODIFIER_NONE:
1326     debug("No modifier but an operand expects one.");
1327     return -1;
1328   case MODIFIER_OPCODE:
1329     insn->opcodeModifier = insn->opcode - insn->spec->modifierBase;
1330     return 0;
1331   case MODIFIER_MODRM:
1332     insn->opcodeModifier = insn->modRM - insn->spec->modifierBase;
1333     return 0;
1334   }  
1335 }
1336
1337 /*
1338  * readOpcodeRegister - Reads an operand from the opcode field of an 
1339  *   instruction and interprets it appropriately given the operand width.
1340  *   Handles AddRegFrm instructions.
1341  *
1342  * @param insn  - See readOpcodeModifier().
1343  * @param size  - The width (in bytes) of the register being specified.
1344  *                1 means AL and friends, 2 means AX, 4 means EAX, and 8 means
1345  *                RAX.
1346  * @return      - 0 on success; nonzero otherwise.
1347  */
1348 static int readOpcodeRegister(struct InternalInstruction* insn, uint8_t size) {
1349   dbgprintf(insn, "readOpcodeRegister()");
1350
1351   if (readOpcodeModifier(insn))
1352     return -1;
1353   
1354   if (size == 0)
1355     size = insn->registerSize;
1356   
1357   switch (size) {
1358   case 1:
1359     insn->opcodeRegister = (Reg)(MODRM_REG_AL + ((bFromREX(insn->rexPrefix) << 3) 
1360                                                   | insn->opcodeModifier));
1361     if (insn->rexPrefix && 
1362         insn->opcodeRegister >= MODRM_REG_AL + 0x4 &&
1363         insn->opcodeRegister < MODRM_REG_AL + 0x8) {
1364       insn->opcodeRegister = (Reg)(MODRM_REG_SPL
1365                                    + (insn->opcodeRegister - MODRM_REG_AL - 4));
1366     }
1367       
1368     break;
1369   case 2:
1370     insn->opcodeRegister = (Reg)(MODRM_REG_AX
1371                                  + ((bFromREX(insn->rexPrefix) << 3) 
1372                                     | insn->opcodeModifier));
1373     break;
1374   case 4:
1375     insn->opcodeRegister = (Reg)(MODRM_REG_EAX
1376                                  + ((bFromREX(insn->rexPrefix) << 3) 
1377                                     | insn->opcodeModifier));
1378     break;
1379   case 8:
1380     insn->opcodeRegister = (Reg)(MODRM_REG_RAX 
1381                                  + ((bFromREX(insn->rexPrefix) << 3) 
1382                                     | insn->opcodeModifier));
1383     break;
1384   }
1385   
1386   return 0;
1387 }
1388
1389 /*
1390  * readImmediate - Consumes an immediate operand from an instruction, given the
1391  *   desired operand size.
1392  *
1393  * @param insn  - The instruction whose operand is to be read.
1394  * @param size  - The width (in bytes) of the operand.
1395  * @return      - 0 if the immediate was successfully consumed; nonzero
1396  *                otherwise.
1397  */
1398 static int readImmediate(struct InternalInstruction* insn, uint8_t size) {
1399   uint8_t imm8;
1400   uint16_t imm16;
1401   uint32_t imm32;
1402   uint64_t imm64;
1403   
1404   dbgprintf(insn, "readImmediate()");
1405   
1406   if (insn->numImmediatesConsumed == 2) {
1407     debug("Already consumed two immediates");
1408     return -1;
1409   }
1410   
1411   if (size == 0)
1412     size = insn->immediateSize;
1413   else
1414     insn->immediateSize = size;
1415   
1416   switch (size) {
1417   case 1:
1418     if (consumeByte(insn, &imm8))
1419       return -1;
1420     insn->immediates[insn->numImmediatesConsumed] = imm8;
1421     break;
1422   case 2:
1423     if (consumeUInt16(insn, &imm16))
1424       return -1;
1425     insn->immediates[insn->numImmediatesConsumed] = imm16;
1426     break;
1427   case 4:
1428     if (consumeUInt32(insn, &imm32))
1429       return -1;
1430     insn->immediates[insn->numImmediatesConsumed] = imm32;
1431     break;
1432   case 8:
1433     if (consumeUInt64(insn, &imm64))
1434       return -1;
1435     insn->immediates[insn->numImmediatesConsumed] = imm64;
1436     break;
1437   }
1438   
1439   insn->numImmediatesConsumed++;
1440   
1441   return 0;
1442 }
1443
1444 /*
1445  * readVVVV - Consumes vvvv from an instruction if it has a VEX prefix.
1446  *
1447  * @param insn  - The instruction whose operand is to be read.
1448  * @return      - 0 if the vvvv was successfully consumed; nonzero
1449  *                otherwise.
1450  */
1451 static int readVVVV(struct InternalInstruction* insn) {
1452   dbgprintf(insn, "readVVVV()");
1453         
1454   if (insn->vexSize == 3)
1455     insn->vvvv = vvvvFromVEX3of3(insn->vexPrefix[2]);
1456   else if (insn->vexSize == 2)
1457     insn->vvvv = vvvvFromVEX2of2(insn->vexPrefix[1]);
1458   else
1459     return -1;
1460
1461   if (insn->mode != MODE_64BIT)
1462     insn->vvvv &= 0x7;
1463
1464   return 0;
1465 }
1466
1467 /*
1468  * readOperands - Consults the specifier for an instruction and consumes all
1469  *   operands for that instruction, interpreting them as it goes.
1470  *
1471  * @param insn  - The instruction whose operands are to be read and interpreted.
1472  * @return      - 0 if all operands could be read; nonzero otherwise.
1473  */
1474 static int readOperands(struct InternalInstruction* insn) {
1475   int index;
1476   int hasVVVV, needVVVV;
1477   int sawRegImm = 0;
1478   
1479   dbgprintf(insn, "readOperands()");
1480
1481   /* If non-zero vvvv specified, need to make sure one of the operands
1482      uses it. */
1483   hasVVVV = !readVVVV(insn);
1484   needVVVV = hasVVVV && (insn->vvvv != 0);
1485   
1486   for (index = 0; index < X86_MAX_OPERANDS; ++index) {
1487     switch (insn->spec->operands[index].encoding) {
1488     case ENCODING_NONE:
1489       break;
1490     case ENCODING_REG:
1491     case ENCODING_RM:
1492       if (readModRM(insn))
1493         return -1;
1494       if (fixupReg(insn, &insn->spec->operands[index]))
1495         return -1;
1496       break;
1497     case ENCODING_CB:
1498     case ENCODING_CW:
1499     case ENCODING_CD:
1500     case ENCODING_CP:
1501     case ENCODING_CO:
1502     case ENCODING_CT:
1503       dbgprintf(insn, "We currently don't hande code-offset encodings");
1504       return -1;
1505     case ENCODING_IB:
1506       if (sawRegImm) {
1507         /* Saw a register immediate so don't read again and instead split the
1508            previous immediate.  FIXME: This is a hack. */
1509         insn->immediates[insn->numImmediatesConsumed] =
1510           insn->immediates[insn->numImmediatesConsumed - 1] & 0xf;
1511         ++insn->numImmediatesConsumed;
1512         break;
1513       }
1514       if (readImmediate(insn, 1))
1515         return -1;
1516       if (insn->spec->operands[index].type == TYPE_IMM3 &&
1517           insn->immediates[insn->numImmediatesConsumed - 1] > 7)
1518         return -1;
1519       if (insn->spec->operands[index].type == TYPE_XMM128 ||
1520           insn->spec->operands[index].type == TYPE_XMM256)
1521         sawRegImm = 1;
1522       break;
1523     case ENCODING_IW:
1524       if (readImmediate(insn, 2))
1525         return -1;
1526       break;
1527     case ENCODING_ID:
1528       if (readImmediate(insn, 4))
1529         return -1;
1530       break;
1531     case ENCODING_IO:
1532       if (readImmediate(insn, 8))
1533         return -1;
1534       break;
1535     case ENCODING_Iv:
1536       if (readImmediate(insn, insn->immediateSize))
1537         return -1;
1538       break;
1539     case ENCODING_Ia:
1540       if (readImmediate(insn, insn->addressSize))
1541         return -1;
1542       break;
1543     case ENCODING_RB:
1544       if (readOpcodeRegister(insn, 1))
1545         return -1;
1546       break;
1547     case ENCODING_RW:
1548       if (readOpcodeRegister(insn, 2))
1549         return -1;
1550       break;
1551     case ENCODING_RD:
1552       if (readOpcodeRegister(insn, 4))
1553         return -1;
1554       break;
1555     case ENCODING_RO:
1556       if (readOpcodeRegister(insn, 8))
1557         return -1;
1558       break;
1559     case ENCODING_Rv:
1560       if (readOpcodeRegister(insn, 0))
1561         return -1;
1562       break;
1563     case ENCODING_I:
1564       if (readOpcodeModifier(insn))
1565         return -1;
1566       break;
1567     case ENCODING_VVVV:
1568       needVVVV = 0; /* Mark that we have found a VVVV operand. */
1569       if (!hasVVVV)
1570         return -1;
1571       if (fixupReg(insn, &insn->spec->operands[index]))
1572         return -1;
1573       break;
1574     case ENCODING_DUP:
1575       break;
1576     default:
1577       dbgprintf(insn, "Encountered an operand with an unknown encoding.");
1578       return -1;
1579     }
1580   }
1581
1582   /* If we didn't find ENCODING_VVVV operand, but non-zero vvvv present, fail */
1583   if (needVVVV) return -1;
1584   
1585   return 0;
1586 }
1587
1588 /*
1589  * decodeInstruction - Reads and interprets a full instruction provided by the
1590  *   user.
1591  *
1592  * @param insn      - A pointer to the instruction to be populated.  Must be 
1593  *                    pre-allocated.
1594  * @param reader    - The function to be used to read the instruction's bytes.
1595  * @param readerArg - A generic argument to be passed to the reader to store
1596  *                    any internal state.
1597  * @param logger    - If non-NULL, the function to be used to write log messages
1598  *                    and warnings.
1599  * @param loggerArg - A generic argument to be passed to the logger to store
1600  *                    any internal state.
1601  * @param startLoc  - The address (in the reader's address space) of the first
1602  *                    byte in the instruction.
1603  * @param mode      - The mode (real mode, IA-32e, or IA-32e in 64-bit mode) to
1604  *                    decode the instruction in.
1605  * @return          - 0 if the instruction's memory could be read; nonzero if
1606  *                    not.
1607  */
1608 int decodeInstruction(struct InternalInstruction* insn,
1609                       byteReader_t reader,
1610                       void* readerArg,
1611                       dlog_t logger,
1612                       void* loggerArg,
1613                       void* miiArg,
1614                       uint64_t startLoc,
1615                       DisassemblerMode mode) {
1616   memset(insn, 0, sizeof(struct InternalInstruction));
1617     
1618   insn->reader = reader;
1619   insn->readerArg = readerArg;
1620   insn->dlog = logger;
1621   insn->dlogArg = loggerArg;
1622   insn->startLocation = startLoc;
1623   insn->readerCursor = startLoc;
1624   insn->mode = mode;
1625   insn->numImmediatesConsumed = 0;
1626   
1627   if (readPrefixes(insn)       ||
1628       readOpcode(insn)         ||
1629       getID(insn, miiArg)      ||
1630       insn->instructionID == 0 ||
1631       readOperands(insn))
1632     return -1;
1633   
1634   insn->length = insn->readerCursor - insn->startLocation;
1635   
1636   dbgprintf(insn, "Read from 0x%llx to 0x%llx: length %zu",
1637             startLoc, insn->readerCursor, insn->length);
1638     
1639   if (insn->length > 15)
1640     dbgprintf(insn, "Instruction exceeds 15-byte limit");
1641   
1642   return 0;
1643 }