EmulateInstruction.h revision 3063c95c54ac0303287c34f9f5af7ba7b6b8f0bc
1//===-- EmulateInstruction.h ------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef lldb_EmulateInstruction_h_
11#define lldb_EmulateInstruction_h_
12
13#include <string>
14
15#include "lldb/lldb-private.h"
16#include "lldb/lldb-public.h"
17#include "lldb/Core/ArchSpec.h"
18#include "lldb/Core/PluginInterface.h"
19#include "lldb/Core/Opcode.h"
20#include "lldb/Interpreter/NamedOptionValue.h"
21
22//----------------------------------------------------------------------
23/// @class EmulateInstruction EmulateInstruction.h "lldb/Core/EmulateInstruction.h"
24/// @brief A class that allows emulation of CPU opcodes.
25///
26/// This class is a plug-in interface that is accessed through the
27/// standard static FindPlugin function call in the EmulateInstruction
28/// class. The FindPlugin takes a target triple and returns a new object
29/// if there is a plug-in that supports the architecture and OS. Four
30/// callbacks and a baton are provided. The four callbacks are read
31/// register, write register, read memory and write memory.
32///
33/// This class is currently designed for these main use cases:
34/// - Auto generation of Call Frame Information (CFI) from assembly code
35/// - Predicting single step breakpoint locations
36/// - Emulating instructions for breakpoint traps
37///
38/// Objects can be asked to read an instruction which will cause a call
39/// to the read register callback to get the PC, followed by a read
40/// memory call to read the opcode. If ReadInstruction () returns true,
41/// then a call to EmulateInstruction::EvaluateInstruction () can be
42/// made. At this point the EmulateInstruction subclass will use all of
43/// the callbacks to emulate an instruction.
44///
45/// Clients that provide the callbacks can either do the read/write
46/// registers/memory to actually emulate the instruction on a real or
47/// virtual CPU, or watch for the EmulateInstruction::Context which
48/// is context for the read/write register/memory which explains why
49/// the callback is being called. Examples of a context are:
50/// "pushing register 3 onto the stack at offset -12", or "adjusting
51/// stack pointer by -16". This extra context allows the generation of
52/// CFI information from assembly code without having to actually do
53/// the read/write register/memory.
54///
55/// Clients must be prepared that not all instructions for an
56/// Instruction Set Architecture (ISA) will be emulated.
57///
58/// Subclasses at the very least should implement the instructions that
59/// save and restore regiters onto the stack and adjustment to the stack
60/// pointer. By just implementing a few instructions for an ISA that are
61/// the typical prologue opcodes, you can then generate CFI using a
62/// class that will soon be available.
63///
64/// Implmenting all of the instructions that affect the PC can then
65/// allow single step prediction support.
66///
67/// Implmenting all of the instructions allows for emulation of opcodes
68/// for breakpoint traps and will pave the way for "thread centric"
69/// debugging. The current debugging model is "process centric" where
70/// all threads must be stopped when any thread is stopped since when
71/// hitting software breakpoints once must disable the breakpoint by
72/// restoring the original breakpoint opcde, single stepping and
73/// restoring the breakpoint trap. If all threads were allowed to run
74/// then other threads could miss the breakpoint.
75///
76/// This class centralizes the code that usually is done in separate
77/// code paths in a debugger (single step prediction, finding save
78/// restore locations of registers for unwinding stack frame variables,
79/// and emulating the intruction is just a bonus.
80//----------------------------------------------------------------------
81
82namespace lldb_private {
83
84class EmulateInstruction :
85    public PluginInterface
86{
87public:
88
89    static EmulateInstruction*
90    FindPlugin (const ArchSpec &arch,
91                InstructionType supported_inst_type,
92                const char *plugin_name);
93
94    enum ContextType
95    {
96        eContextInvalid = 0,
97        // Read an instruciton opcode from memory
98        eContextReadOpcode,
99
100        // Usually used for writing a register value whose source value in an
101        // immediate
102        eContextImmediate,
103
104        // Exclusively used when saving a register to the stack as part of the
105        // prologue
106        eContextPushRegisterOnStack,
107
108        // Exclusively used when restoring a register off the stack as part of
109        // the epilogue
110        eContextPopRegisterOffStack,
111
112        // Add or subtract a value from the stack
113        eContextAdjustStackPointer,
114
115        // Add or subtract a value from a base address register (other than SP)
116        eContextAdjustBaseRegister,
117
118        // Add or subtract a value from the PC or store a value to the PC.
119        eContextAdjustPC,
120
121        // Used in WriteRegister callbacks to indicate where the
122        eContextRegisterPlusOffset,
123
124        // Used in WriteMemory callback to indicate where the data came from
125        eContextRegisterStore,
126
127        eContextRegisterLoad,
128
129        // Used when performing a PC-relative branch where the
130        eContextRelativeBranchImmediate,
131
132        // Used when performing an absolute branch where the
133        eContextAbsoluteBranchRegister,
134
135        // Used when performing a supervisor call to an operating system to
136        // provide a service:
137        eContextSupervisorCall,
138
139        // Used when performing a MemU operation to read the PC-relative offset
140        // from an address.
141        eContextTableBranchReadMemory,
142
143        // Used when random bits are written into a register
144        eContextWriteRegisterRandomBits,
145
146        // Used when random bits are written to memory
147        eContextWriteMemoryRandomBits,
148
149        eContextArithmetic,
150
151        eContextAdvancePC,
152
153        eContextReturnFromException
154    };
155
156    enum InfoType {
157        eInfoTypeRegisterPlusOffset,
158        eInfoTypeRegisterPlusIndirectOffset,
159        eInfoTypeRegisterToRegisterPlusOffset,
160        eInfoTypeRegisterToRegisterPlusIndirectOffset,
161        eInfoTypeRegisterRegisterOperands,
162        eInfoTypeOffset,
163        eInfoTypeRegister,
164        eInfoTypeImmediate,
165        eInfoTypeImmediateSigned,
166        eInfoTypeAddress,
167        eInfoTypeISAAndImmediate,
168        eInfoTypeISAAndImmediateSigned,
169        eInfoTypeISA,
170        eInfoTypeNoArgs
171    } InfoType;
172
173    struct Context
174    {
175        ContextType type;
176        enum InfoType info_type;
177        union
178        {
179            struct RegisterPlusOffset
180            {
181                RegisterInfo reg;          // base register
182                int64_t signed_offset; // signed offset added to base register
183            } RegisterPlusOffset;
184
185            struct RegisterPlusIndirectOffset
186            {
187                RegisterInfo base_reg;      // base register number
188                RegisterInfo offset_reg;    // offset register kind
189            } RegisterPlusIndirectOffset;
190
191            struct RegisterToRegisterPlusOffset
192            {
193                RegisterInfo data_reg;      // source/target register for data
194                RegisterInfo base_reg;      // base register for address calculation
195                int64_t offset;         // offset for address calculation
196            } RegisterToRegisterPlusOffset;
197
198            struct RegisterToRegisterPlusIndirectOffset
199            {
200                RegisterInfo base_reg;      // base register for address calculation
201                RegisterInfo offset_reg;    // offset register for address calculation
202                RegisterInfo data_reg;      // source/target register for data
203            } RegisterToRegisterPlusIndirectOffset;
204
205            struct RegisterRegisterOperands
206            {
207                RegisterInfo operand1;      // register containing first operand for binary op
208                RegisterInfo operand2;      // register containing second operand for binary op
209            } RegisterRegisterOperands;
210
211            int64_t signed_offset;      // signed offset by which to adjust self (for registers only)
212
213            RegisterInfo reg;               // plain register
214
215            uint64_t unsigned_immediate;// unsigned immediate value
216            int64_t signed_immediate;   // signed immediate value
217
218            lldb::addr_t address;       // direct address
219
220            struct ISAAndImmediate
221            {
222                uint32_t isa;
223                uint32_t unsigned_data32;   // immdiate data
224            } ISAAndImmediate;
225
226            struct ISAAndImmediateSigned
227            {
228                uint32_t isa;
229                int32_t signed_data32;      // signed immdiate data
230            } ISAAndImmediateSigned;
231
232            uint32_t isa;
233
234        } info;
235
236        void
237        SetRegisterPlusOffset (RegisterInfo base_reg,
238                               int64_t signed_offset)
239        {
240            info_type = eInfoTypeRegisterPlusOffset;
241            info.RegisterPlusOffset.reg = base_reg;
242            info.RegisterPlusOffset.signed_offset = signed_offset;
243        }
244
245        void
246        SetRegisterPlusIndirectOffset (RegisterInfo base_reg,
247                                       RegisterInfo offset_reg)
248        {
249            info_type = eInfoTypeRegisterPlusIndirectOffset;
250            info.RegisterPlusIndirectOffset.base_reg   = base_reg;
251            info.RegisterPlusIndirectOffset.offset_reg = offset_reg;
252        }
253
254        void
255        SetRegisterToRegisterPlusOffset (RegisterInfo data_reg,
256                                         RegisterInfo base_reg,
257                                         int64_t offset)
258        {
259            info_type = eInfoTypeRegisterToRegisterPlusOffset;
260            info.RegisterToRegisterPlusOffset.data_reg = data_reg;
261            info.RegisterToRegisterPlusOffset.base_reg = base_reg;
262            info.RegisterToRegisterPlusOffset.offset   = offset;
263        }
264
265        void
266        SetRegisterToRegisterPlusIndirectOffset (RegisterInfo base_reg,
267                                                 RegisterInfo offset_reg,
268                                                 RegisterInfo data_reg)
269        {
270            info_type = eInfoTypeRegisterToRegisterPlusIndirectOffset;
271            info.RegisterToRegisterPlusIndirectOffset.base_reg   = base_reg;
272            info.RegisterToRegisterPlusIndirectOffset.offset_reg = offset_reg;
273            info.RegisterToRegisterPlusIndirectOffset.data_reg   = data_reg;
274        }
275
276        void
277        SetRegisterRegisterOperands (RegisterInfo op1_reg,
278                                     RegisterInfo op2_reg)
279        {
280            info_type = eInfoTypeRegisterRegisterOperands;
281            info.RegisterRegisterOperands.operand1 = op1_reg;
282            info.RegisterRegisterOperands.operand2 = op2_reg;
283        }
284
285        void
286        SetOffset (int64_t signed_offset)
287        {
288            info_type = eInfoTypeOffset;
289            info.signed_offset = signed_offset;
290        }
291
292        void
293        SetRegister (RegisterInfo reg)
294        {
295            info_type = eInfoTypeRegister;
296            info.reg = reg;
297        }
298
299        void
300        SetImmediate (uint64_t immediate)
301        {
302            info_type = eInfoTypeImmediate;
303            info.unsigned_immediate = immediate;
304        }
305
306        void
307        SetImmediateSigned (int64_t signed_immediate)
308        {
309            info_type = eInfoTypeImmediateSigned;
310            info.signed_immediate = signed_immediate;
311        }
312
313        void
314        SetAddress (lldb::addr_t address)
315        {
316            info_type = eInfoTypeAddress;
317            info.address = address;
318        }
319        void
320        SetISAAndImmediate (uint32_t isa, uint32_t data)
321        {
322            info_type = eInfoTypeISAAndImmediate;
323            info.ISAAndImmediate.isa = isa;
324            info.ISAAndImmediate.unsigned_data32 = data;
325        }
326
327        void
328        SetISAAndImmediateSigned (uint32_t isa, int32_t data)
329        {
330            info_type = eInfoTypeISAAndImmediateSigned;
331            info.ISAAndImmediateSigned.isa = isa;
332            info.ISAAndImmediateSigned.signed_data32 = data;
333        }
334
335        void
336        SetISA (uint32_t isa)
337        {
338            info_type = eInfoTypeISA;
339            info.isa = isa;
340        }
341
342        void
343        SetNoArgs ()
344        {
345            info_type = eInfoTypeNoArgs;
346        }
347
348        void
349        Dump (FILE *fh,
350              EmulateInstruction *instruction) const;
351
352    };
353
354    typedef size_t (*ReadMemory) (EmulateInstruction *instruction,
355                                  void *baton,
356                                  const Context &context,
357                                  lldb::addr_t addr,
358                                  void *dst,
359                                  size_t length);
360
361    typedef size_t (*WriteMemory) (EmulateInstruction *instruction,
362                                   void *baton,
363                                   const Context &context,
364                                   lldb::addr_t addr,
365                                   const void *dst,
366                                   size_t length);
367
368    typedef bool   (*ReadRegister)  (EmulateInstruction *instruction,
369                                     void *baton,
370                                     const RegisterInfo &reg_info,
371                                     uint64_t &reg_value);
372
373    typedef bool   (*WriteRegister) (EmulateInstruction *instruction,
374                                     void *baton,
375                                     const Context &context,
376                                     const RegisterInfo &reg_info,
377                                     uint64_t reg_value);
378
379    EmulateInstruction (const ArchSpec &arch);
380
381    virtual ~EmulateInstruction()
382    {
383    }
384    //----------------------------------------------------------------------
385    // Mandatory overrides
386    //----------------------------------------------------------------------
387    virtual bool
388    SupportsEmulatingIntructionsOfType (InstructionType inst_type) = 0;
389
390    virtual bool
391    SetTargetTriple (const ArchSpec &arch) = 0;
392
393    virtual bool
394    ReadInstruction () = 0;
395
396    virtual bool
397    EvaluateInstruction (uint32_t evaluate_options) = 0;
398
399    virtual bool
400    TestEmulation (Stream *out_stream, ArchSpec &arch, OptionValueDictionary *test_data) = 0;
401
402    virtual bool
403    GetRegisterInfo (uint32_t reg_kind, uint32_t reg_num, RegisterInfo &reg_info) = 0;
404
405    //----------------------------------------------------------------------
406    // Optional overrides
407    //----------------------------------------------------------------------
408    virtual bool
409    SetInstruction (const Opcode &insn_opcode, const Address &inst_addr, Target *target);
410
411    virtual bool
412    CreateFunctionEntryUnwind (UnwindPlan &unwind_plan);
413
414    static const char *
415    TranslateRegister (uint32_t reg_kind, uint32_t reg_num, std::string &reg_name);
416
417    uint64_t
418    ReadRegisterUnsigned (uint32_t reg_kind,
419                          uint32_t reg_num,
420                          uint64_t fail_value,
421                          bool *success_ptr);
422
423    uint64_t
424    ReadRegisterUnsigned (const RegisterInfo &reg_info,
425                          uint64_t fail_value,
426                          bool *success_ptr);
427
428    bool
429    WriteRegisterUnsigned (const Context &context,
430                           uint32_t reg_kind,
431                           uint32_t reg_num,
432                           uint64_t reg_value);
433
434    bool
435    WriteRegisterUnsigned (const Context &context,
436                           const RegisterInfo &reg_info,
437                           uint64_t reg_value);
438
439    uint64_t
440    ReadMemoryUnsigned (const Context &context,
441                        lldb::addr_t addr,
442                        size_t byte_size,
443                        uint64_t fail_value,
444                        bool *success_ptr);
445
446    bool
447    WriteMemoryUnsigned (const Context &context,
448                         lldb::addr_t addr,
449                         uint64_t uval,
450                         size_t uval_byte_size);
451
452    uint32_t
453    GetAddressByteSize () const
454    {
455        return m_arch.GetAddressByteSize();
456    }
457
458    lldb::ByteOrder
459    GetByteOrder () const
460    {
461        return m_arch.GetByteOrder();
462    }
463
464    const Opcode &
465    GetOpcode () const
466    {
467        return m_opcode;
468    }
469
470    lldb::addr_t
471    GetAddress () const
472    {
473        return m_addr;
474    }
475
476    const ArchSpec &
477    GetArchitecture () const
478    {
479        return m_arch;
480    }
481
482
483    static size_t
484    ReadMemoryFrame (EmulateInstruction *instruction,
485                     void *baton,
486                     const Context &context,
487                     lldb::addr_t addr,
488                     void *dst,
489                     size_t length);
490
491    static size_t
492    WriteMemoryFrame (EmulateInstruction *instruction,
493                      void *baton,
494                      const Context &context,
495                      lldb::addr_t addr,
496                      const void *dst,
497                      size_t length);
498
499    static bool
500    ReadRegisterFrame  (EmulateInstruction *instruction,
501                        void *baton,
502                        const RegisterInfo &reg_info,
503                        uint64_t &reg_value);
504
505
506    static bool
507    WriteRegisterFrame (EmulateInstruction *instruction,
508                        void *baton,
509                        const Context &context,
510                        const RegisterInfo &reg_info,
511                        uint64_t reg_value);
512
513    static size_t
514    ReadMemoryDefault (EmulateInstruction *instruction,
515                       void *baton,
516                       const Context &context,
517                       lldb::addr_t addr,
518                       void *dst,
519                       size_t length);
520
521    static size_t
522    WriteMemoryDefault (EmulateInstruction *instruction,
523                        void *baton,
524                        const Context &context,
525                        lldb::addr_t addr,
526                        const void *dst,
527                        size_t length);
528
529    static bool
530    ReadRegisterDefault  (EmulateInstruction *instruction,
531                          void *baton,
532                          const RegisterInfo &reg_info,
533                          uint64_t &reg_value);
534
535
536    static bool
537    WriteRegisterDefault (EmulateInstruction *instruction,
538                          void *baton,
539                          const Context &context,
540                          const RegisterInfo &reg_info,
541                          uint64_t reg_value);
542
543    void
544    SetBaton (void *baton);
545
546    void
547    SetCallbacks (ReadMemory read_mem_callback,
548                  WriteMemory write_mem_callback,
549                  ReadRegister read_reg_callback,
550                  WriteRegister write_reg_callback);
551
552    void
553    SetReadMemCallback (ReadMemory read_mem_callback);
554
555    void
556    SetWriteMemCallback (WriteMemory write_mem_callback);
557
558    void
559    SetReadRegCallback (ReadRegister read_reg_callback);
560
561    void
562    SetWriteRegCallback (WriteRegister write_reg_callback);
563
564    static bool
565    GetBestRegisterKindAndNumber (const RegisterInfo &reg_info,
566                                  uint32_t &reg_kind,
567                                  uint32_t &reg_num);
568
569    static uint32_t
570    GetInternalRegisterNumber (RegisterContext *reg_ctx,
571                               const RegisterInfo &reg_info);
572
573protected:
574    ArchSpec            m_arch;
575    void *              m_baton;
576    ReadMemory          m_read_mem_callback;
577    WriteMemory         m_write_mem_callback;
578    ReadRegister        m_read_reg_callback;
579    WriteRegister       m_write_reg_callback;
580    lldb::addr_t        m_addr;
581    Opcode              m_opcode;
582
583
584private:
585    //------------------------------------------------------------------
586    // For EmulateInstruction only
587    //------------------------------------------------------------------
588    DISALLOW_COPY_AND_ASSIGN (EmulateInstruction);
589};
590
591}   // namespace lldb_private
592
593#endif  // lldb_EmulateInstruction_h_
594