Add xmm8-xmm15 liveness information/decoding.
[dyninst.git] / instructionAPI / src / InstructionDecoder-x86.C
1 /*
2 * Copyright (c) 1996-2009 Barton P. Miller
3 *
4 * We provide the Paradyn Parallel Performance Tools (below
5 * described as "Paradyn") on an AS IS basis, and do not warrant its
6 * validity or performance.  We reserve the right to update, modify,
7 * or discontinue this software at any time.  We shall have no
8 * obligation to supply such updates or modifications or any other
9 * form of support to you.
10 *
11 * By your use of Paradyn, you understand and agree that we (or any
12 * other person or entity with proprietary rights in Paradyn) are
13 * under no obligation to provide either maintenance services,
14 * update services, notices of latent defects, or correction of
15 * defects for Paradyn.
16 *
17 * This library is free software; you can redistribute it and/or
18 * modify it under the terms of the GNU Lesser General Public
19 * License as published by the Free Software Foundation; either
20 * version 2.1 of the License, or (at your option) any later version.
21 *
22 * This library is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25 * Lesser General Public License for more details.
26 *
27 * You should have received a copy of the GNU Lesser General Public
28 * License along with this library; if not, write to the Free Software
29 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30 */
31
32 #define INSIDE_INSTRUCTION_API
33
34 #include "common/h/Types.h"
35 #include "InstructionDecoder-x86.h"
36 #include "Expression.h"
37 #include "common/h/arch-x86.h"
38 #include "Register.h"
39 #include "Dereference.h"
40 #include "Immediate.h"
41 #include "BinaryFunction.h"
42 #include "common/h/singleton_object_pool.h"
43
44 using namespace std;
45 using namespace NS_x86;
46 namespace Dyninst
47 {
48     namespace InstructionAPI
49     {
50     
51         bool readsOperand(unsigned int opsema, unsigned int i)
52         {
53             switch(opsema) {
54                 case s1R2R:
55                     return (i == 0 || i == 1);
56                 case s1R:
57                 case s1RW:
58                     return i == 0;
59                 case s1W:
60                     return false;
61                 case s1W2RW:
62                 case s1W2R:   // second operand read, first operand written (e.g. mov)
63                     return i == 1;
64                 case s1RW2R:  // two operands read, first written (e.g. add)
65                 case s1RW2RW: // e.g. xchg
66                 case s1R2RW:
67                     return i == 0 || i == 1;
68                 case s1W2R3R: // e.g. imul
69                 case s1W2RW3R: // some mul
70                 case s1W2R3RW: // (stack) push & pop
71                     return i == 1 || i == 2;
72                 case s1W2W3R: // e.g. les
73                     return i == 2;
74                 case s1RW2R3R: // shld/shrd
75                 case s1RW2RW3R: // [i]div, cmpxch8b
76                 case s1R2R3R:
77                     return i == 0 || i == 1 || i == 2;
78                     break;
79                 case sNONE:
80                 default:
81                     return false;
82             }
83       
84         }
85       
86         bool writesOperand(unsigned int opsema, unsigned int i)
87         {
88             switch(opsema) {
89                 case s1R2R:
90                 case s1R:
91                     return false;
92                 case s1RW:
93                 case s1W:
94                     case s1W2R:   // second operand read, first operand written (e.g. mov)
95                         case s1RW2R:  // two operands read, first written (e.g. add)
96                             case s1W2R3R: // e.g. imul
97                                 case s1RW2R3R: // shld/shrd
98                                     return i == 0;
99                 case s1R2RW:
100                     return i == 1;
101                 case s1W2RW:
102                     case s1RW2RW: // e.g. xchg
103                         case s1W2RW3R: // some mul
104                             case s1W2W3R: // e.g. les
105                                 case s1RW2RW3R: // [i]div, cmpxch8b
106                                     return i == 0 || i == 1;
107                                     case s1W2R3RW: // (stack) push & pop
108                                         return i == 0 || i == 2;
109                 case sNONE:
110                 default:
111                     return false;
112             }
113         }
114
115
116     
117     INSTRUCTION_EXPORT InstructionDecoder_x86::InstructionDecoder_x86(Architecture a) :
118       InstructionDecoderImpl(a),
119     locs(NULL),
120     decodedInstruction(NULL),
121     is32BitMode(true),
122     sizePrefixPresent(false)
123     {
124     }
125     INSTRUCTION_EXPORT InstructionDecoder_x86::~InstructionDecoder_x86()
126     {
127         if(decodedInstruction) decodedInstruction->~ia32_instruction();
128         free(decodedInstruction);
129         if(locs) locs->~ia32_locations();
130         free(locs);
131
132     }
133     static const unsigned char modrm_use_sib = 4;
134     
135     INSTRUCTION_EXPORT void InstructionDecoder_x86::setMode(bool is64)
136     {
137         ia32_set_mode_64(is64);
138     }
139     
140       Expression::Ptr InstructionDecoder_x86::makeSIBExpression(const InstructionDecoder::buffer& b)
141     {
142         unsigned scale;
143         Register index;
144         Register base;
145         Result_Type registerType = ia32_is_mode_64() ? u32 : u64;
146
147         decode_SIB(locs->sib_byte, scale, index, base);
148
149         Expression::Ptr scaleAST(make_shared(singleton_object_pool<Immediate>::construct(Result(u8, dword_t(scale)))));
150         Expression::Ptr indexAST(make_shared(singleton_object_pool<RegisterAST>::construct(makeRegisterID(index, registerType,
151                                     locs->rex_x))));
152         Expression::Ptr baseAST;
153         if(base == 0x05)
154         {
155             switch(locs->modrm_mod)
156             {
157                 case 0x00:
158                     baseAST = decodeImmediate(op_d, b.start + locs->sib_position + 1);
159                     break;
160                     case 0x01: {
161                         MachRegister reg;
162                         if (locs->rex_b)
163                             reg = x86_64::r13;
164                         else
165                           reg = MachRegister::getFramePointer(m_Arch);
166                         
167                         baseAST = makeAddExpression(make_shared(singleton_object_pool<RegisterAST>::construct(reg)),
168                                                     decodeImmediate(op_b, b.start + locs->sib_position + 1),
169                                                     registerType);
170                         break;
171                     }
172                     case 0x02: {
173                         MachRegister reg;
174                         if (locs->rex_b)
175                             reg = x86_64::r13;
176                         else
177                             reg = MachRegister::getFramePointer(m_Arch);
178
179                         baseAST = makeAddExpression(make_shared(singleton_object_pool<RegisterAST>::construct(reg)), 
180                                                     decodeImmediate(op_d, b.start + locs->sib_position + 1),
181                                                     registerType);
182                         break;
183                     }
184                 case 0x03:
185                 default:
186                     assert(0);
187                     break;
188             };
189         }
190         else
191         {
192             baseAST = make_shared(singleton_object_pool<RegisterAST>::construct(makeRegisterID(base, 
193                                                                                                registerType,
194                                                                                                locs->rex_b)));
195         }
196         if(index == 0x04 && (!(ia32_is_mode_64()) || !(locs->rex_x)))
197         {
198             return baseAST;
199         }
200         return makeAddExpression(baseAST, makeMultiplyExpression(indexAST, scaleAST, registerType), registerType);
201     }
202
203       Expression::Ptr InstructionDecoder_x86::makeModRMExpression(const InstructionDecoder::buffer& b,
204                                                                   unsigned int opType)
205     {
206         unsigned int regType = op_d;
207         Result_Type aw = ia32_is_mode_64() ? u32 : u64;
208         if(ia32_is_mode_64())
209         {
210             regType = op_q;
211         }
212         Expression::Ptr e =
213             makeRegisterExpression(makeRegisterID(locs->modrm_rm, regType, (locs->rex_b == 1)));
214         switch(locs->modrm_mod)
215         {
216             case 0:
217                 if(locs->modrm_rm == modrm_use_sib) {
218                     e = makeSIBExpression(b);
219                 }
220                 if(locs->modrm_rm == 0x5 && !addrSizePrefixPresent)
221                 {
222                     assert(locs->opcode_position > -1);
223                     if(ia32_is_mode_64())
224                     {
225                         e = makeAddExpression(makeRegisterExpression(x86_64::rip),
226                                             getModRMDisplacement(b), aw);
227                     }
228                     else
229                     {
230                         e = getModRMDisplacement(b);
231                     }
232         
233                 }
234                 if(locs->modrm_rm == 0x6 && addrSizePrefixPresent)
235                 {
236                     e = getModRMDisplacement(b);
237                 }
238                 if(opType == op_lea)
239                 {
240                     return e;
241                 }
242                 return makeDereferenceExpression(e, makeSizeType(opType));
243                 assert(0);
244                 break;
245             case 1:
246             case 2:
247             {
248                 if(locs->modrm_rm == modrm_use_sib) {
249                     e = makeSIBExpression(b);
250                 }
251                 Expression::Ptr disp_e = makeAddExpression(e, getModRMDisplacement(b), aw);
252                 if(opType == op_lea)
253                 {
254                     return disp_e;
255                 }
256                 return makeDereferenceExpression(disp_e, makeSizeType(opType));
257             }
258             assert(0);
259             break;
260             case 3:
261                 return makeRegisterExpression(makeRegisterID(locs->modrm_rm, opType, (locs->rex_b == 1)));
262             default:
263                 return Expression::Ptr();
264         
265         };
266         // can't get here, but make the compiler happy...
267         assert(0);
268         return Expression::Ptr();
269     }
270
271     Expression::Ptr InstructionDecoder_x86::decodeImmediate(unsigned int opType, const unsigned char* immStart, 
272                                                             bool isSigned)
273     {
274         switch(opType)
275         {
276             case op_b:
277                 return Immediate::makeImmediate(Result(isSigned ? s8 : u8 ,*(const byte_t*)(immStart)));
278                 break;
279             case op_d:
280                 return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
281             case op_w:
282                 return Immediate::makeImmediate(Result(isSigned ? s16 : u16,*(const word_t*)(immStart)));
283                 break;
284             case op_q:
285                 return Immediate::makeImmediate(Result(isSigned ? s64 : u64,*(const int64_t*)(immStart)));
286                 break;
287             case op_v:
288             case op_z:
289         // 32 bit mode & no prefix, or 16 bit mode & prefix => 32 bit
290         // 16 bit mode, no prefix or 32 bit mode, prefix => 16 bit
291                 if(!sizePrefixPresent)
292                 {
293                     return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
294                 }
295                 else
296                 {
297                     return Immediate::makeImmediate(Result(isSigned ? s16 : u16,*(const word_t*)(immStart)));
298                 }
299         
300                 break;
301             case op_p:
302         // 32 bit mode & no prefix, or 16 bit mode & prefix => 48 bit
303         // 16 bit mode, no prefix or 32 bit mode, prefix => 32 bit
304                 if(!sizePrefixPresent)
305                 {
306                     return Immediate::makeImmediate(Result(isSigned ? s48 : u48,*(const int64_t*)(immStart)));
307                 }
308                 else
309                 {
310                     return Immediate::makeImmediate(Result(isSigned ? s32 : u32,*(const dword_t*)(immStart)));
311                 }
312         
313                 break;
314             case op_a:
315             case op_dq:
316             case op_pd:
317             case op_ps:
318             case op_s:
319             case op_si:
320             case op_lea:
321             case op_allgprs:
322             case op_512:
323             case op_c:
324                 assert(!"Can't happen: opType unexpected for valid ways to decode an immediate");
325                 return Expression::Ptr();
326             default:
327                 assert(!"Can't happen: opType out of range");
328                 return Expression::Ptr();
329         }
330     }
331     
332     Expression::Ptr InstructionDecoder_x86::getModRMDisplacement(const InstructionDecoder::buffer& b)
333     {
334         int disp_pos;
335
336         if(locs->sib_position != -1)
337         {
338             disp_pos = locs->sib_position + 1;
339         }
340         else
341         {
342             disp_pos = locs->modrm_position + 1;
343         }
344         switch(locs->modrm_mod)
345         {
346             case 1:
347                 return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, (*(const byte_t*)(b.start +
348                         disp_pos)))));
349                 break;
350             case 2:
351                 if(sizePrefixPresent)
352                 {
353                     return make_shared(singleton_object_pool<Immediate>::construct(Result(s16, *((const word_t*)(b.start +
354                             disp_pos)))));
355                 }
356                 else
357                 {
358                     return make_shared(singleton_object_pool<Immediate>::construct(Result(s32, *((const dword_t*)(b.start +
359                             disp_pos)))));
360                 }
361                 break;
362             case 0:
363                 // In 16-bit mode, the word displacement is modrm r/m 6
364                 if(sizePrefixPresent)
365                 {
366                     if(locs->modrm_rm == 6)
367                     {
368                         return make_shared(singleton_object_pool<Immediate>::construct(Result(s16,
369                                            *((const dword_t*)(b.start + disp_pos)))));
370                     }
371                     else
372                     {
373                         assert(b.start + disp_pos + 1 <= b.end);
374                         return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, 0)));
375                     }
376                     break;
377                 }
378                 // ...and in 32-bit mode, the dword displacement is modrm r/m 5
379                 else
380                 {
381                     if(locs->modrm_rm == 5)
382                     {
383                         assert(b.start + disp_pos + 4 <= b.end);
384                         return make_shared(singleton_object_pool<Immediate>::construct(Result(s32,
385                                            *((const dword_t*)(b.start + disp_pos)))));
386                     }
387                     else
388                     {
389                         assert(b.start + disp_pos + 1 <= b.end);
390                         return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, 0)));
391                     }
392                     break;
393                 }
394             default:
395                 assert(b.start + disp_pos + 1 <= b.end);
396                 return make_shared(singleton_object_pool<Immediate>::construct(Result(s8, 0)));
397                 break;
398         }
399     }
400
401     enum intelRegBanks
402     {
403         b_8bitNoREX = 0,
404         b_16bit,
405         b_32bit,
406         b_segment,
407         b_64bit,
408         b_xmm,
409         b_xmmhigh,
410         b_mm,
411         b_cr,
412         b_dr,
413         b_tr,
414         b_amd64ext,
415         b_8bitWithREX,
416         b_fpstack
417     };
418     static MachRegister IntelRegTable32[][8] = {
419         {
420             x86::al, x86::cl, x86::dl, x86::bl, x86::ah, x86::ch, x86::dh, x86::bh
421         },
422         {
423             x86::ax, x86::cx, x86::dx, x86::bx, x86::sp, x86::bp, x86::si, x86::di
424         },
425         {
426             x86::eax, x86::ecx, x86::edx, x86::ebx, x86::esp, x86::ebp, x86::esi, x86::edi
427         },
428         {
429            x86::es, x86::cs, x86::ss, x86::ds, x86::fs, x86::gs, InvalidReg, InvalidReg
430         },
431         {
432             x86_64::rax, x86_64::rcx, x86_64::rdx, x86_64::rbx, x86_64::rsp, x86_64::rbp, x86_64::rsi, x86_64::rdi
433         },
434         {
435             x86::xmm0, x86::xmm1, x86::xmm2, x86::xmm3, x86::xmm4, x86::xmm5, x86::xmm6, x86::xmm7
436         },
437         {
438             x86_64::xmm8, x86_64::xmm9, x86_64::xmm10, x86_64::xmm11, x86_64::xmm12, x86_64::xmm13, x86_64::xmm14, x86_64::xmm15
439         },
440         {
441             x86::mm0, x86::mm1, x86::mm2, x86::mm3, x86::mm4, x86::mm5, x86::mm6, x86::mm7
442         },
443         {
444             x86::cr0, x86::cr1, x86::cr2, x86::cr3, x86::cr4, x86::cr5, x86::cr6, x86::cr7
445         },
446         {
447             x86::dr0, x86::dr1, x86::dr2, x86::dr3, x86::dr4, x86::dr5, x86::dr6, x86::dr7
448         },
449         {
450             x86::tr0, x86::tr1, x86::tr2, x86::tr3, x86::tr4, x86::tr5, x86::tr6, x86::tr7
451         },
452         {
453             x86_64::r8, x86_64::r9, x86_64::r10, x86_64::r11, x86_64::r12, x86_64::r13, x86_64::r14, x86_64::r15
454         },
455         {
456             x86_64::al, x86_64::cl, x86_64::dl, x86_64::bl, x86_64::spl, x86_64::bpl, x86_64::sil, x86_64::dil
457         },
458         {
459             x86::st0, x86::st1, x86::st2, x86::st3, x86::st4, x86::st5, x86::st6, x86::st7
460         }
461
462     };
463     static MachRegister IntelRegTable64[][8] = {
464         {
465             x86_64::al, x86_64::cl, x86_64::dl, x86_64::bl, x86_64::ah, x86_64::ch, x86_64::dh, x86_64::bh
466         },
467         {
468             x86_64::ax, x86_64::cx, x86_64::dx, x86_64::bx, x86_64::sp, x86_64::bp, x86_64::si, x86_64::di
469         },
470         {
471             x86_64::eax, x86_64::ecx, x86_64::edx, x86_64::ebx, x86_64::esp, x86_64::ebp, x86_64::esi, x86_64::edi
472         },
473         {
474             x86_64::es, x86_64::cs, x86_64::ss, x86_64::ds, x86_64::fs, x86_64::gs, InvalidReg, InvalidReg
475         },
476         {
477             x86_64::rax, x86_64::rcx, x86_64::rdx, x86_64::rbx, x86_64::rsp, x86_64::rbp, x86_64::rsi, x86_64::rdi
478         },
479         {
480             x86_64::xmm0, x86_64::xmm1, x86_64::xmm2, x86_64::xmm3, x86_64::xmm4, x86_64::xmm5, x86_64::xmm6, x86_64::xmm7
481         },
482         {
483             x86_64::xmm8, x86_64::xmm9, x86_64::xmm10, x86_64::xmm11, x86_64::xmm12, x86_64::xmm13, x86_64::xmm14, x86_64::xmm15
484         },
485         {
486             x86_64::mm0, x86_64::mm1, x86_64::mm2, x86_64::mm3, x86_64::mm4, x86_64::mm5, x86_64::mm6, x86_64::mm7
487         },
488         {
489             x86_64::cr0, x86_64::cr1, x86_64::cr2, x86_64::cr3, x86_64::cr4, x86_64::cr5, x86_64::cr6, x86_64::cr7
490         },
491         {
492             x86_64::dr0, x86_64::dr1, x86_64::dr2, x86_64::dr3, x86_64::dr4, x86_64::dr5, x86_64::dr6, x86_64::dr7
493         },
494         {
495             x86_64::tr0, x86_64::tr1, x86_64::tr2, x86_64::tr3, x86_64::tr4, x86_64::tr5, x86_64::tr6, x86_64::tr7
496         },
497         {
498             x86_64::r8, x86_64::r9, x86_64::r10, x86_64::r11, x86_64::r12, x86_64::r13, x86_64::r14, x86_64::r15
499         },
500         {
501             x86_64::al, x86_64::cl, x86_64::dl, x86_64::bl, x86_64::spl, x86_64::bpl, x86_64::sil, x86_64::dil
502         },
503         {
504             x86_64::st0, x86_64::st1, x86_64::st2, x86_64::st3, x86_64::st4, x86_64::st5, x86_64::st6, x86_64::st7
505         }
506
507     };
508
509   /* Uses the appropriate lookup table based on the 
510      decoder architecture */
511   class IntelRegTable_access {
512     public:
513         inline MachRegister operator()(Architecture arch,
514                                        intelRegBanks bank,
515                                        int index)
516         {
517             assert(index >= 0 && index < 8);
518     
519             if(arch == Arch_x86_64)
520                 return IntelRegTable64[bank][index];
521             else if(arch == Arch_x86)
522                 return IntelRegTable32[bank][index];
523             else
524                 assert(0);
525             return IntelRegTable32[bank][index];
526         }
527
528   };
529   static IntelRegTable_access IntelRegTable;
530
531     MachRegister InstructionDecoder_x86::makeRegisterID(unsigned int intelReg, unsigned int opType,
532                                         bool isExtendedReg)
533     {
534         MachRegister retVal;
535
536         if(isExtendedReg)
537         {
538             retVal = IntelRegTable(m_Arch,b_amd64ext,intelReg);
539         }
540         /* Promotion to 64-bit only applies to the operand types
541            that are varible (c,v,z). Ignoring c and z because they
542            do the right thing on 32- and 64-bit code.
543         else if(locs->rex_w)
544         {
545             // AMD64 with 64-bit operands
546             retVal = IntelRegTable[b_64bit][intelReg];
547         }
548         */
549         else
550         {
551             switch(opType)
552             {
553                 case op_v:
554                     if(locs->rex_w)
555                         retVal = IntelRegTable(m_Arch,b_64bit,intelReg);
556                     else
557                         retVal = IntelRegTable(m_Arch,b_32bit,intelReg);
558                     break;
559                 case op_b:
560                     if (locs->rex_position == -1) {
561                         retVal = IntelRegTable(m_Arch,b_8bitNoREX,intelReg);
562                     } else {
563                         retVal = IntelRegTable(m_Arch,b_8bitWithREX,intelReg);
564                     }
565                     break;
566                 case op_q:
567                     retVal = IntelRegTable(m_Arch,b_64bit,intelReg);
568                     break;
569                 case op_w:
570                     retVal = IntelRegTable(m_Arch,b_16bit,intelReg);
571                     break;
572                 case op_f:
573                 case op_dbl:
574                     retVal = IntelRegTable(m_Arch,b_fpstack,intelReg);
575                     break;
576                 case op_d:
577                 case op_si:
578                     retVal = IntelRegTable(m_Arch,b_32bit,intelReg);
579                     break;
580                 default:
581                     retVal = IntelRegTable(m_Arch,b_32bit,intelReg);
582                     break;
583             }
584         }
585
586         if (!ia32_is_mode_64()) {
587           if ((retVal.val() & 0x00ffffff) == 0x0001000c)
588             assert(0);
589         }
590
591         return MachRegister((retVal.val() & ~retVal.getArchitecture()) | m_Arch);
592     }
593     
594     Result_Type InstructionDecoder_x86::makeSizeType(unsigned int opType)
595     {
596         switch(opType)
597         {
598             case op_b:
599             case op_c:
600                 return u8;
601             case op_d:
602             case op_ss:
603             case op_allgprs:
604             case op_si:
605                 return u32;
606             case op_w:
607             case op_a:
608                 return u16;
609             case op_q:
610             case op_sd:
611                 return u64;
612             case op_v:
613             case op_lea:
614             case op_z:
615                 if(is32BitMode ^ sizePrefixPresent)
616                 {
617                     return u32;
618                 }
619                 else
620                 {
621                     return u16;
622                 }
623                 break;
624             case op_p:
625                 // book says operand size; arch-x86 says word + word * operand size
626                 if(is32BitMode ^ sizePrefixPresent)
627                 {
628                     return u48;
629                 }
630                 else
631                 {
632                     return u32;
633                 }
634             case op_dq:
635                 return u64;
636             case op_512:
637                 return m512;
638             case op_pi:
639             case op_ps:
640             case op_pd:
641                 return dbl128;
642             case op_s:
643                 return u48;
644             case op_f:
645                 return sp_float;
646             case op_dbl:
647                 return dp_float;
648             case op_14:
649                 return m14;
650             default:
651                 assert(!"Can't happen!");
652                 return u8;
653         }
654     }
655
656
657     bool InstructionDecoder_x86::decodeOneOperand(const InstructionDecoder::buffer& b,
658                                                   const ia32_operand& operand,
659                                                   int & imm_index, /* immediate operand index */
660                                                   const Instruction* insn_to_complete, 
661                                                   bool isRead, bool isWritten)
662     {
663       bool isCFT = false;
664       bool isCall = false;
665       bool isConditional = false;
666       InsnCategory cat = insn_to_complete->getCategory();
667       if(cat == c_BranchInsn || cat == c_CallInsn)
668         {
669           isCFT = true;
670           if(cat == c_CallInsn)
671             {
672               isCall = true;
673             }
674         }
675       if (cat == c_BranchInsn && insn_to_complete->getOperation().getID() != e_jmp) {
676         isConditional = true;
677       }
678
679       unsigned int optype = operand.optype;
680       if (sizePrefixPresent && 
681           ((optype == op_v) ||
682            (optype == op_z))) {
683         optype = op_w;
684       }
685                 switch(operand.admet)
686                 {
687                     case 0:
688                     // No operand
689                     {
690 /*                        fprintf(stderr, "ERROR: Instruction with mismatched operands. Raw bytes: ");
691                         for(unsigned int i = 0; i < decodedInstruction->getSize(); i++) {
692                             fprintf(stderr, "%x ", b.start[i]);
693                         }
694                         fprintf(stderr, "\n");*/
695                         assert(!"Mismatched number of operands--check tables");
696                         return false;
697                     }
698                     case am_A:
699                     {
700                         // am_A only shows up as a far call/jump.  Position 1 should be universally safe.
701                         Expression::Ptr addr(decodeImmediate(optype, b.start + 1));
702                         Expression::Ptr op(makeDereferenceExpression(addr, makeSizeType(optype)));
703                         insn_to_complete->addSuccessor(op, isCall, false, false, false);
704                     }
705                     break;
706                     case am_C:
707                     {
708                         Expression::Ptr op(makeRegisterExpression(IntelRegTable(m_Arch,b_cr,locs->modrm_reg)));
709                         insn_to_complete->appendOperand(op, isRead, isWritten);
710                     }
711                     break;
712                     case am_D:
713                     {
714                         Expression::Ptr op(makeRegisterExpression(IntelRegTable(m_Arch,b_dr,locs->modrm_reg)));
715                         insn_to_complete->appendOperand(op, isRead, isWritten);
716                     }
717                     break;
718                     case am_E:
719                     // am_M is like am_E, except that mod of 0x03 should never occur (am_M specified memory,
720                     // mod of 0x03 specifies direct register access).
721                     case am_M:
722                     // am_R is the inverse of am_M; it should only have a mod of 3
723                     case am_R:
724                         if(isCFT)
725                         {
726                           insn_to_complete->addSuccessor(makeModRMExpression(b, optype), isCall, true, false, false);
727                         }
728                         else
729                         {
730                           insn_to_complete->appendOperand(makeModRMExpression(b, optype), isRead, isWritten);
731                         }
732                     break;
733                     case am_F:
734                     {
735                         Expression::Ptr op(makeRegisterExpression(x86::flags));
736                         insn_to_complete->appendOperand(op, isRead, isWritten);
737                     }
738                     break;
739                     case am_G:
740                     {
741                         Expression::Ptr op(makeRegisterExpression(makeRegisterID(locs->modrm_reg,
742                                 optype, locs->rex_r)));
743                         insn_to_complete->appendOperand(op, isRead, isWritten);
744                     }
745                     break;
746                     case am_I:
747                         insn_to_complete->appendOperand(decodeImmediate(optype, b.start + 
748                                                                         locs->imm_position[imm_index++]), 
749                                                         isRead, isWritten);
750                         break;
751                     case am_J:
752                     {
753                         Expression::Ptr Offset(decodeImmediate(optype, 
754                                                                b.start + locs->imm_position[imm_index++], 
755                                                                true));
756                         Expression::Ptr EIP(makeRegisterExpression(MachRegister::getPC(m_Arch)));
757                         Expression::Ptr InsnSize(make_shared(singleton_object_pool<Immediate>::construct(Result(u8,
758                             decodedInstruction->getSize()))));
759                         Expression::Ptr postEIP(makeAddExpression(EIP, InsnSize, u32));
760
761                         Expression::Ptr op(makeAddExpression(Offset, postEIP, u32));
762                         insn_to_complete->addSuccessor(op, isCall, false, isConditional, false);
763                         if (isConditional) 
764                           insn_to_complete->addSuccessor(postEIP, false, false, true, true);
765                     }
766                     break;
767                     case am_O:
768                     {
769                     // Address/offset width, which is *not* what's encoded by the optype...
770                     // The deref's width is what's actually encoded here.
771                         int pseudoOpType;
772                         switch(locs->address_size)
773                         {
774                             case 1:
775                                 pseudoOpType = op_b;
776                                 break;
777                             case 2:
778                                 pseudoOpType = op_w;
779                                 break;
780                             case 4:
781                                 pseudoOpType = op_d;
782                                 break;
783                             case 0:
784                                 // closest I can get to "will be address size by default"
785                                 pseudoOpType = op_v;
786                                 break;
787                             default:
788                                 assert(!"Bad address size, should be 0, 1, 2, or 4!");
789                                 pseudoOpType = op_b;
790                                 break;
791                         }
792
793
794                         int offset_position = locs->opcode_position;
795                         if(locs->modrm_position > offset_position && locs->modrm_operand <
796                            (int)(insn_to_complete->m_Operands.size()))
797                         {
798                             offset_position = locs->modrm_position;
799                         }
800                         if(locs->sib_position > offset_position)
801                         {
802                             offset_position = locs->sib_position;
803                         }
804                         offset_position++;
805                         insn_to_complete->appendOperand(makeDereferenceExpression(
806                                 decodeImmediate(pseudoOpType, b.start + offset_position), makeSizeType(optype)), 
807                                                         isRead, isWritten);
808                     }
809                     break;
810                     case am_P:
811                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch,b_mm,locs->modrm_reg)),
812                                 isRead, isWritten);
813                         break;
814                     case am_Q:
815         
816                         switch(locs->modrm_mod)
817                         {
818                             // direct dereference
819                             case 0x00:
820                             case 0x01:
821                             case 0x02:
822                               insn_to_complete->appendOperand(makeModRMExpression(b, optype), isRead, isWritten);
823                                 break;
824                             case 0x03:
825                                 // use of actual register
826                                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch,b_mm,locs->modrm_rm)),
827                                                                isRead, isWritten);
828                                 break;
829                             default:
830                                 assert(!"2-bit value modrm_mod out of range");
831                                 break;
832                         };
833                         break;
834                     case am_S:
835                     // Segment register in modrm reg field.
836                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch,b_segment,locs->modrm_reg)),
837                                 isRead, isWritten);
838                         break;
839                     case am_T:
840                         // test register in modrm reg; should only be tr6/tr7, but we'll decode any of them
841                         // NOTE: this only appears in deprecated opcodes
842                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch,b_tr,locs->modrm_reg)),
843                                                        isRead, isWritten);
844                         break;
845                     case am_V:
846                        
847                         insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch,
848                                 (locs->rex_r == 1 )? b_xmmhigh : b_xmm,locs->modrm_reg)),
849                                     isRead, isWritten);
850                         break;
851                     case am_W:
852                         switch(locs->modrm_mod)
853                         {
854                             // direct dereference
855                             case 0x00:
856                             case 0x01:
857                             case 0x02:
858                               insn_to_complete->appendOperand(makeModRMExpression(b, makeSizeType(optype)),
859                                                                isRead, isWritten);
860                                 break;
861                             case 0x03:
862                             // use of actual register
863                             {
864                                 insn_to_complete->appendOperand(makeRegisterExpression(IntelRegTable(m_Arch,
865                                         (locs->rex_b == 1) ? b_xmmhigh : b_xmm, locs->modrm_rm)),
866                                         isRead, isWritten);
867                                 break;
868                             }
869                             default:
870                                 assert(!"2-bit value modrm_mod out of range");
871                                 break;
872                         };
873                         break;
874                     case am_X:
875                     {
876                         MachRegister si_reg;
877                         if(m_Arch == Arch_x86)
878                         {
879                                 if(addrSizePrefixPresent)
880                                 {
881                                         si_reg = x86::si;
882                                 } else
883                                 {
884                                         si_reg = x86::esi;
885                                 }
886                         }
887                         else
888                         {
889                                 if(addrSizePrefixPresent)
890                                 {
891                                         si_reg = x86_64::esi;
892                                 } else
893                                 {
894                                         si_reg = x86_64::rsi;
895                                 }
896                         }
897                         Expression::Ptr ds(makeRegisterExpression(m_Arch == Arch_x86 ? x86::ds : x86_64::ds));
898                         Expression::Ptr si(makeRegisterExpression(si_reg));
899                         Expression::Ptr segmentOffset(make_shared(singleton_object_pool<Immediate>::construct(
900                                 Result(u32, 0x10))));
901                         Expression::Ptr ds_segment = makeMultiplyExpression(ds, segmentOffset, u32);
902                         Expression::Ptr ds_si = makeAddExpression(ds_segment, si, u32);
903                         insn_to_complete->appendOperand(makeDereferenceExpression(ds_si, makeSizeType(optype)),
904                                                        isRead, isWritten);
905                     }
906                     break;
907                     case am_Y:
908                     {
909                         MachRegister di_reg;
910                         if(m_Arch == Arch_x86)
911                         {
912                                 if(addrSizePrefixPresent)
913                                 {
914                                         di_reg = x86::di;
915                                 } else
916                                 {
917                                         di_reg = x86::edi;
918                                 }
919                         }
920                         else
921                         {
922                                 if(addrSizePrefixPresent)
923                                 {
924                                         di_reg = x86_64::edi;
925                                 } else
926                                 {
927                                         di_reg = x86_64::rdi;
928                                 }
929                         }
930                         Expression::Ptr es(makeRegisterExpression(m_Arch == Arch_x86 ? x86::es : x86_64::es));
931                         Expression::Ptr di(makeRegisterExpression(di_reg));
932                         Expression::Ptr es_segment = makeMultiplyExpression(es,
933                             make_shared(singleton_object_pool<Immediate>::construct(Result(u32, 0x10))), u32);
934                         Expression::Ptr es_di = makeAddExpression(es_segment, di, u32);
935                         insn_to_complete->appendOperand(makeDereferenceExpression(es_di, makeSizeType(optype)),
936                                                        isRead, isWritten);
937                     }
938                     break;
939                     case am_tworeghack:
940                     {
941                         if(optype == op_edxeax)
942                         {
943                             Expression::Ptr edx(makeRegisterExpression(m_Arch == Arch_x86 ? x86::edx : x86_64::edx));
944                             Expression::Ptr eax(makeRegisterExpression(m_Arch == Arch_x86 ? x86::eax : x86_64::eax));
945                             Expression::Ptr highAddr = makeMultiplyExpression(edx,
946                                     Immediate::makeImmediate(Result(u64, 2^32)), u64);
947                             Expression::Ptr addr = makeAddExpression(highAddr, eax, u64);
948                             Expression::Ptr op = makeDereferenceExpression(addr, u64);
949                             insn_to_complete->appendOperand(op, isRead, isWritten);
950                         }
951                         else if (optype == op_ecxebx)
952                         {
953                             Expression::Ptr ecx(makeRegisterExpression(m_Arch == Arch_x86 ? x86::ecx : x86_64::ecx));
954                             Expression::Ptr ebx(makeRegisterExpression(m_Arch == Arch_x86 ? x86::ebx : x86_64::ebx));
955                             Expression::Ptr highAddr = makeMultiplyExpression(ecx,
956                                     Immediate::makeImmediate(Result(u64, 2^32)), u64);
957                             Expression::Ptr addr = makeAddExpression(highAddr, ebx, u64);
958                             Expression::Ptr op = makeDereferenceExpression(addr, u64);
959                             insn_to_complete->appendOperand(op, isRead, isWritten);
960                         }
961                     }
962                     break;
963                     
964                     case am_reg:
965                     {
966                         MachRegister r(optype);
967                         r = MachRegister(r.val() & ~r.getArchitecture() | m_Arch);
968                         if(locs->rex_b && insn_to_complete->m_Operands.empty())
969                         {
970                             r = MachRegister((r.val()) | x86_64::r8.val());
971                         }
972                         if(sizePrefixPresent)
973                         {
974                             r = MachRegister((r.val() & ~x86::FULL) | x86::W_REG);
975                         }
976                         Expression::Ptr op(makeRegisterExpression(r));
977                         insn_to_complete->appendOperand(op, isRead, isWritten);
978                     }
979                     break;
980                 case am_stackH:
981                 case am_stackP:
982                 // handled elsewhere
983                     break;
984                 case am_allgprs:
985                 {
986                     if(m_Arch == Arch_x86)
987                     {
988                         insn_to_complete->appendOperand(makeRegisterExpression(x86::eax), isRead, isWritten);
989                         insn_to_complete->appendOperand(makeRegisterExpression(x86::ecx), isRead, isWritten);
990                         insn_to_complete->appendOperand(makeRegisterExpression(x86::edx), isRead, isWritten);
991                         insn_to_complete->appendOperand(makeRegisterExpression(x86::ebx), isRead, isWritten);
992                         insn_to_complete->appendOperand(makeRegisterExpression(x86::esp), isRead, isWritten);
993                         insn_to_complete->appendOperand(makeRegisterExpression(x86::ebp), isRead, isWritten);
994                         insn_to_complete->appendOperand(makeRegisterExpression(x86::esi), isRead, isWritten);
995                         insn_to_complete->appendOperand(makeRegisterExpression(x86::edi), isRead, isWritten);
996                     }
997                     else
998                     {
999                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::eax), isRead, isWritten);
1000                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::ecx), isRead, isWritten);
1001                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::edx), isRead, isWritten);
1002                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::ebx), isRead, isWritten);
1003                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::esp), isRead, isWritten);
1004                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::ebp), isRead, isWritten);
1005                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::esi), isRead, isWritten);
1006                         insn_to_complete->appendOperand(makeRegisterExpression(x86_64::edi), isRead, isWritten);
1007                     }
1008                 }
1009                     break;
1010                 case am_ImplImm: {
1011                   insn_to_complete->appendOperand(Immediate::makeImmediate(Result(makeSizeType(optype), 1)), isRead, isWritten);
1012                   break;
1013                 }
1014
1015                 default:
1016                     printf("decodeOneOperand() called with unknown addressing method %d\n", operand.admet);
1017                         break;
1018                 };
1019                 return true;
1020             }
1021
1022     extern ia32_entry invalid;
1023     
1024     void InstructionDecoder_x86::doIA32Decode(InstructionDecoder::buffer& b)
1025     {
1026         if(decodedInstruction == NULL)
1027         {
1028             decodedInstruction = reinterpret_cast<ia32_instruction*>(malloc(sizeof(ia32_instruction)));
1029             assert(decodedInstruction);
1030         }
1031         if(locs == NULL)
1032         {
1033             locs = reinterpret_cast<ia32_locations*>(malloc(sizeof(ia32_locations)));
1034             assert(locs);
1035         }
1036         locs = new(locs) ia32_locations; //reinit();
1037         assert(locs->sib_position == -1);
1038         decodedInstruction = new (decodedInstruction) ia32_instruction(NULL, NULL, locs);
1039         ia32_decode(IA32_DECODE_PREFIXES, b.start, *decodedInstruction);
1040         sizePrefixPresent = (decodedInstruction->getPrefix()->getOperSzPrefix() == 0x66);
1041         addrSizePrefixPresent = (decodedInstruction->getPrefix()->getAddrSzPrefix() == 0x67);
1042     }
1043     
1044     void InstructionDecoder_x86::decodeOpcode(InstructionDecoder::buffer& b)
1045     {
1046         static ia32_entry invalid = { e_No_Entry, 0, 0, true, { {0,0}, {0,0}, {0,0} }, 0, 0 };
1047         doIA32Decode(b);
1048         if(decodedInstruction->getEntry()) {
1049             m_Operation = make_shared(singleton_object_pool<Operation>::construct(decodedInstruction->getEntry(),
1050                                     decodedInstruction->getPrefix(), locs, m_Arch));
1051         }
1052         else
1053         {
1054                 // Gap parsing can trigger this case; in particular, when it encounters prefixes in an invalid order.
1055                 // Notably, if a REX prefix (0x40-0x48) appears followed by another prefix (0x66, 0x67, etc)
1056                 // we'll reject the instruction as invalid and send it back with no entry.  Since this is a common
1057                 // byte sequence to see in, for example, ASCII strings, we want to simply accept this and move on, not
1058                 // yell at the user.
1059             m_Operation = make_shared(singleton_object_pool<Operation>::construct(&invalid,
1060                                     decodedInstruction->getPrefix(), locs, m_Arch));
1061         }
1062         b.start += decodedInstruction->getSize();
1063     }
1064     
1065       bool InstructionDecoder_x86::decodeOperands(const Instruction* insn_to_complete)
1066     {
1067         int imm_index = 0; // handle multiple immediate operands
1068         if(!decodedInstruction) return false;
1069         unsigned int opsema = decodedInstruction->getEntry()->opsema & 0xFF;
1070         InstructionDecoder::buffer b(insn_to_complete->ptr(), insn_to_complete->size());
1071         
1072         for(unsigned i = 0; i < 3; i++)
1073         {
1074             if(decodedInstruction->getEntry()->operands[i].admet == 0 && 
1075                decodedInstruction->getEntry()->operands[i].optype == 0)
1076                 return true;
1077             if(!decodeOneOperand(b,
1078                                  decodedInstruction->getEntry()->operands[i], 
1079                                  imm_index, 
1080                                  insn_to_complete, 
1081                                  readsOperand(opsema, i),
1082                                  writesOperand(opsema, i)))
1083             {
1084                 return false;
1085             }
1086         }
1087     
1088         return true;
1089     }
1090
1091     
1092       INSTRUCTION_EXPORT Instruction::Ptr InstructionDecoder_x86::decode(InstructionDecoder::buffer& b)
1093     {
1094         return InstructionDecoderImpl::decode(b);
1095     }
1096     void InstructionDecoder_x86::doDelayedDecode(const Instruction* insn_to_complete)
1097     {
1098       InstructionDecoder::buffer b(insn_to_complete->ptr(), insn_to_complete->size());
1099       //insn_to_complete->m_Operands.reserve(4);
1100       doIA32Decode(b);        
1101       decodeOperands(insn_to_complete);
1102     }
1103     
1104 };
1105 };
1106