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