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