IRExecutionUnit.h revision 1cf3da8b0fb0cabf2431b5fe521842929fca69a3
1//===-- IRExecutionUnit.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_IRExecutionUnit_h_
11#define lldb_IRExecutionUnit_h_
12
13// C Includes
14// C++ Includes
15#include <atomic>
16#include <string>
17#include <vector>
18#include <map>
19
20// Other libraries and framework includes
21// Project includes
22#include "lldb/lldb-forward.h"
23#include "lldb/lldb-private.h"
24#include "lldb/Core/ClangForward.h"
25#include "llvm/ExecutionEngine/JITMemoryManager.h"
26#include "lldb/Expression/ClangExpression.h"
27#include "lldb/Expression/ClangExpressionParser.h"
28#include "lldb/Host/Mutex.h"
29
30namespace llvm {
31
32class Module;
33class ExecutionEngine;
34
35}
36
37namespace lldb_private {
38
39class Error;
40
41//----------------------------------------------------------------------
42/// @class IRExecutionUnit IRExecutionUnit.h "lldb/Expression/IRExecutionUnit.h"
43/// @brief Contains the IR and, optionally, JIT-compiled code for a module.
44///
45/// This class encapsulates the compiled version of an expression, in IR
46/// form (for interpretation purposes) and in raw machine code form (for
47/// execution in the target).
48///
49/// This object wraps an IR module that comes from the expression parser,
50/// and knows how to use the JIT to make it into executable code.  It can
51/// then be used as input to the IR interpreter, or the address of the
52/// executable code can be passed to a thread plan to run in the target.
53///
54/// This class creates a subclass of LLVM's JITMemoryManager, because that is
55/// how the JIT emits code.  Because LLDB needs to move JIT-compiled code
56/// into the target process, the IRExecutionUnit knows how to copy the
57/// emitted code into the target process.
58//----------------------------------------------------------------------
59class IRExecutionUnit
60{
61public:
62    //------------------------------------------------------------------
63    /// Constructor
64    //------------------------------------------------------------------
65    IRExecutionUnit (std::auto_ptr<llvm::Module> &module_ap,
66                     ConstString &name,
67                     lldb::ProcessSP process_sp,
68                     std::vector<std::string> &cpu_features);
69
70    //------------------------------------------------------------------
71    /// Destructor
72    //------------------------------------------------------------------
73    ~IRExecutionUnit();
74
75    llvm::Module *GetModule()
76    {
77        return m_module;
78    }
79
80    void GetRunnableInfo(Error &error,
81                         lldb::addr_t &func_addr,
82                         lldb::addr_t &func_end);
83
84    //------------------------------------------------------------------
85    /// Accessors for IRForTarget and other clients that may want binary
86    /// data placed on their behalf.  The binary data is owned by the
87    /// IRExecutionUnit unless the client explicitly chooses to free it.
88    //------------------------------------------------------------------
89
90    lldb::addr_t WriteNow(const uint8_t *bytes,
91                          size_t size,
92                          Error &error);
93
94    void FreeNow(lldb::addr_t allocation);
95
96private:
97    //------------------------------------------------------------------
98    /// Look up the object in m_address_map that contains a given address,
99    /// find where it was copied to, and return the remote address at the
100    /// same offset into the copied entity
101    ///
102    /// @param[in] local_address
103    ///     The address in the debugger.
104    ///
105    /// @return
106    ///     The address in the target process.
107    //------------------------------------------------------------------
108    lldb::addr_t
109    GetRemoteAddressForLocal (lldb::addr_t local_address);
110
111    //------------------------------------------------------------------
112    /// Look up the object in m_address_map that contains a given address,
113    /// find where it was copied to, and return its address range in the
114    /// target process
115    ///
116    /// @param[in] local_address
117    ///     The address in the debugger.
118    ///
119    /// @return
120    ///     The range of the containing object in the target process.
121    //------------------------------------------------------------------
122    typedef std::pair <lldb::addr_t, uintptr_t> AddrRange;
123    AddrRange
124    GetRemoteRangeForLocal (lldb::addr_t local_address);
125
126    //------------------------------------------------------------------
127    /// Commit all allocations to the process and record where they were stored.
128    ///
129    /// @param[in] process
130    ///     The process to allocate memory in.
131    ///
132    /// @return
133    ///     True <=> all allocations were performed successfully.
134    ///     This method will attempt to free allocated memory if the
135    ///     operation fails.
136    //------------------------------------------------------------------
137    bool
138    CommitAllocations (lldb::ProcessSP &process_sp);
139
140    //------------------------------------------------------------------
141    /// Report all committed allocations to the execution engine.
142    ///
143    /// @param[in] engine
144    ///     The execution engine to notify.
145    //------------------------------------------------------------------
146    void
147    ReportAllocations (llvm::ExecutionEngine &engine);
148
149    //------------------------------------------------------------------
150    /// Write the contents of all allocations to the process.
151    ///
152    /// @param[in] local_address
153    ///     The process containing the allocations.
154    ///
155    /// @return
156    ///     True <=> all allocations were performed successfully.
157    //------------------------------------------------------------------
158    bool
159    WriteData (lldb::ProcessSP &process_sp);
160
161    Error
162    DisassembleFunction (Stream &stream,
163                         lldb::ProcessSP &process_sp);
164
165    class MemoryManager : public llvm::JITMemoryManager
166    {
167    public:
168        MemoryManager (IRExecutionUnit &parent);
169
170        //------------------------------------------------------------------
171        /// Passthrough interface stub
172        //------------------------------------------------------------------
173        virtual void setMemoryWritable ();
174
175        //------------------------------------------------------------------
176        /// Passthrough interface stub
177        //------------------------------------------------------------------
178        virtual void setMemoryExecutable ();
179
180        //------------------------------------------------------------------
181        /// Passthrough interface stub
182        //------------------------------------------------------------------
183        virtual void setPoisonMemory (bool poison)
184        {
185            m_default_mm_ap->setPoisonMemory (poison);
186        }
187
188        //------------------------------------------------------------------
189        /// Passthrough interface stub
190        //------------------------------------------------------------------
191        virtual void AllocateGOT()
192        {
193            m_default_mm_ap->AllocateGOT();
194        }
195
196        //------------------------------------------------------------------
197        /// Passthrough interface stub
198        //------------------------------------------------------------------
199        virtual uint8_t *getGOTBase() const
200        {
201            return m_default_mm_ap->getGOTBase();
202        }
203
204        //------------------------------------------------------------------
205        /// Passthrough interface stub
206        //------------------------------------------------------------------
207        virtual uint8_t *startFunctionBody(const llvm::Function *F,
208                                           uintptr_t &ActualSize);
209
210        //------------------------------------------------------------------
211        /// Allocate room for a dyld stub for a lazy-referenced function,
212        /// and add it to the m_stubs map
213        ///
214        /// @param[in] F
215        ///     The function being referenced.
216        ///
217        /// @param[in] StubSize
218        ///     The size of the stub.
219        ///
220        /// @param[in] Alignment
221        ///     The required alignment of the stub.
222        ///
223        /// @return
224        ///     Allocated space for the stub.
225        //------------------------------------------------------------------
226        virtual uint8_t *allocateStub(const llvm::GlobalValue* F,
227                                      unsigned StubSize,
228                                      unsigned Alignment);
229
230        //------------------------------------------------------------------
231        /// Complete the body of a function, and add it to the m_functions map
232        ///
233        /// @param[in] F
234        ///     The function being completed.
235        ///
236        /// @param[in] FunctionStart
237        ///     The first instruction of the function.
238        ///
239        /// @param[in] FunctionEnd
240        ///     The last byte of the last instruction of the function.
241        //------------------------------------------------------------------
242        virtual void endFunctionBody(const llvm::Function *F,
243                                     uint8_t *FunctionStart,
244                                     uint8_t *FunctionEnd);
245        //------------------------------------------------------------------
246        /// Allocate space for an unspecified purpose, and add it to the
247        /// m_spaceBlocks map
248        ///
249        /// @param[in] Size
250        ///     The size of the area.
251        ///
252        /// @param[in] Alignment
253        ///     The required alignment of the area.
254        ///
255        /// @return
256        ///     Allocated space.
257        //------------------------------------------------------------------
258        virtual uint8_t *allocateSpace(intptr_t Size, unsigned Alignment);
259
260        //------------------------------------------------------------------
261        /// Allocate space for executable code, and add it to the
262        /// m_spaceBlocks map
263        ///
264        /// @param[in] Size
265        ///     The size of the area.
266        ///
267        /// @param[in] Alignment
268        ///     The required alignment of the area.
269        ///
270        /// @param[in] SectionID
271        ///     A unique identifier for the section.
272        ///
273        /// @return
274        ///     Allocated space.
275        //------------------------------------------------------------------
276        virtual uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
277                                             unsigned SectionID);
278
279        //------------------------------------------------------------------
280        /// Allocate space for data, and add it to the m_spaceBlocks map
281        ///
282        /// @param[in] Size
283        ///     The size of the area.
284        ///
285        /// @param[in] Alignment
286        ///     The required alignment of the area.
287        ///
288        /// @param[in] SectionID
289        ///     A unique identifier for the section.
290        ///
291        /// @param[in] IsReadOnly
292        ///     Flag indicating the section is read-only.
293        ///
294        /// @return
295        ///     Allocated space.
296        //------------------------------------------------------------------
297        virtual uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
298                                             unsigned SectionID, bool IsReadOnly);
299
300        //------------------------------------------------------------------
301        /// Allocate space for a global variable, and add it to the
302        /// m_spaceBlocks map
303        ///
304        /// @param[in] Size
305        ///     The size of the variable.
306        ///
307        /// @param[in] Alignment
308        ///     The required alignment of the variable.
309        ///
310        /// @return
311        ///     Allocated space for the global.
312        //------------------------------------------------------------------
313        virtual uint8_t *allocateGlobal(uintptr_t Size,
314                                        unsigned Alignment);
315
316        //------------------------------------------------------------------
317        /// Called when object loading is complete and section page
318        /// permissions can be applied. Currently unimplemented for LLDB.
319        ///
320        /// @param[out] ErrMsg
321        ///     The error that prevented the page protection from succeeding.
322        ///
323        /// @return
324        ///     True in case of failure, false in case of success.
325        //------------------------------------------------------------------
326        bool applyPermissions(std::string *ErrMsg) { return false; }
327
328        //------------------------------------------------------------------
329        /// Passthrough interface stub
330        //------------------------------------------------------------------
331        virtual void deallocateFunctionBody(void *Body);
332
333        //------------------------------------------------------------------
334        /// Passthrough interface stub
335        //------------------------------------------------------------------
336        virtual uint8_t* startExceptionTable(const llvm::Function* F,
337                                             uintptr_t &ActualSize);
338
339        //------------------------------------------------------------------
340        /// Complete the exception table for a function, and add it to the
341        /// m_exception_tables map
342        ///
343        /// @param[in] F
344        ///     The function whose exception table is being written.
345        ///
346        /// @param[in] TableStart
347        ///     The first byte of the exception table.
348        ///
349        /// @param[in] TableEnd
350        ///     The last byte of the exception table.
351        ///
352        /// @param[in] FrameRegister
353        ///     I don't know what this does, but it's passed through.
354        //------------------------------------------------------------------
355        virtual void endExceptionTable(const llvm::Function *F,
356                                       uint8_t *TableStart,
357                                       uint8_t *TableEnd,
358                                       uint8_t* FrameRegister);
359
360        //------------------------------------------------------------------
361        /// Passthrough interface stub
362        //------------------------------------------------------------------
363        virtual void deallocateExceptionTable(void *ET);
364
365        //------------------------------------------------------------------
366        /// Passthrough interface stub
367        //------------------------------------------------------------------
368        virtual size_t GetDefaultCodeSlabSize() {
369            return m_default_mm_ap->GetDefaultCodeSlabSize();
370        }
371
372        //------------------------------------------------------------------
373        /// Passthrough interface stub
374        //------------------------------------------------------------------
375        virtual size_t GetDefaultDataSlabSize() {
376            return m_default_mm_ap->GetDefaultDataSlabSize();
377        }
378
379        virtual size_t GetDefaultStubSlabSize() {
380            return m_default_mm_ap->GetDefaultStubSlabSize();
381        }
382
383        //------------------------------------------------------------------
384        /// Passthrough interface stub
385        //------------------------------------------------------------------
386        virtual unsigned GetNumCodeSlabs() {
387            return m_default_mm_ap->GetNumCodeSlabs();
388        }
389
390        //------------------------------------------------------------------
391        /// Passthrough interface stub
392        //------------------------------------------------------------------
393        virtual unsigned GetNumDataSlabs() {
394            return m_default_mm_ap->GetNumDataSlabs();
395        }
396
397        //------------------------------------------------------------------
398        /// Passthrough interface stub
399        //------------------------------------------------------------------
400        virtual unsigned GetNumStubSlabs() {
401            return m_default_mm_ap->GetNumStubSlabs();
402        }
403
404        //------------------------------------------------------------------
405        /// Passthrough interface stub
406        //------------------------------------------------------------------
407        virtual void *getPointerToNamedFunction(const std::string &Name,
408                                                bool AbortOnFailure = true) {
409            return m_default_mm_ap->getPointerToNamedFunction(Name, AbortOnFailure);
410        }
411    private:
412        std::auto_ptr<JITMemoryManager>     m_default_mm_ap;    ///< The memory allocator to use in actually creating space.  All calls are passed through to it.
413        IRExecutionUnit                    &m_parent;           ///< The execution unit this is a proxy for.
414    };
415
416    //----------------------------------------------------------------------
417    /// @class Allocation IRExecutionUnit.h "lldb/Expression/IRExecutionUnit.h"
418    /// @brief A record of a region that has been allocated by the JIT.
419    ///
420    /// The IRExecutionUnit makes records of all regions that need copying;
421    /// upon requests, it allocates and
422    //----------------------------------------------------------------------
423    struct Allocation
424    {
425        lldb::addr_t    m_remote_allocation;///< The (unaligned) base for the remote allocation
426        lldb::addr_t    m_remote_start;     ///< The base address of the remote allocation
427        uintptr_t       m_local_start;      ///< The base address of the local allocation - LLDB_INVALID_ADDRESS means it was allocated with WriteNow
428        uintptr_t       m_size;             ///< The size of the allocation
429        unsigned        m_section_id;       ///< The ID of the section
430        unsigned        m_alignment;        ///< The required alignment for the allocation
431        bool            m_executable;       ///< True <=> the allocation must be executable in the target
432        bool            m_allocated;        ///< True <=> the allocation has been propagated to the target
433
434        static const unsigned eSectionIDNone = (unsigned)-1;
435
436        //------------------------------------------------------------------
437        /// Constructor
438        //------------------------------------------------------------------
439        Allocation () :
440            m_remote_allocation(0),
441            m_remote_start(0),
442            m_local_start(0),
443            m_size(0),
444            m_section_id(eSectionIDNone),
445            m_alignment(0),
446            m_executable(false),
447            m_allocated(false)
448        {
449        }
450
451        void dump (lldb::LogSP log);
452    };
453
454    //----------------------------------------------------------------------
455    /// @class JittedFunction ClangExpressionParser.h "lldb/Expression/ClangExpressionParser.h"
456    /// @brief Encapsulates a single function that has been generated by the JIT.
457    ///
458    /// Functions that have been generated by the JIT are first resident in the
459    /// local process, and then placed in the target process.  JittedFunction
460    /// represents a function possibly resident in both.
461    //----------------------------------------------------------------------
462    struct JittedFunction {
463        std::string m_name;             ///< The function's name
464        lldb::addr_t m_local_addr;      ///< The address of the function in LLDB's memory
465        lldb::addr_t m_remote_addr;     ///< The address of the function in the target's memory
466
467        //------------------------------------------------------------------
468        /// Constructor
469        ///
470        /// Initializes class variabes.
471        ///
472        /// @param[in] name
473        ///     The name of the function.
474        ///
475        /// @param[in] local_addr
476        ///     The address of the function in LLDB, or LLDB_INVALID_ADDRESS if
477        ///     it is not present in LLDB's memory.
478        ///
479        /// @param[in] remote_addr
480        ///     The address of the function in the target, or LLDB_INVALID_ADDRESS
481        ///     if it is not present in the target's memory.
482        //------------------------------------------------------------------
483        JittedFunction (const char *name,
484                        lldb::addr_t local_addr = LLDB_INVALID_ADDRESS,
485                        lldb::addr_t remote_addr = LLDB_INVALID_ADDRESS) :
486            m_name (name),
487            m_local_addr (local_addr),
488            m_remote_addr (remote_addr)
489        {
490        }
491    };
492
493    lldb::ProcessWP                         m_process_wp;
494    typedef std::vector<Allocation>         AllocationList;
495    AllocationList                          m_allocations;          ///< The base address of the remote allocation
496    std::auto_ptr<llvm::ExecutionEngine>    m_execution_engine_ap;
497    std::auto_ptr<llvm::Module>             m_module_ap;            ///< Holder for the module until it's been handed off
498    llvm::Module                           *m_module;               ///< Owned by the execution engine
499    std::vector<std::string>                m_cpu_features;
500    llvm::SmallVector<JittedFunction, 1>    m_jitted_functions;     ///< A vector of all functions that have been JITted into machine code
501    const ConstString                       m_name;
502
503    std::atomic<bool>                       m_did_jit;
504    Mutex                                   m_jit_mutex;
505
506    lldb::addr_t                            m_function_load_addr;
507    lldb::addr_t                            m_function_end_load_addr;
508};
509
510} // namespace lldb_private
511
512#endif  // lldb_IRExecutionUnit_h_
513