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