]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - include/lldb/Expression/IRExecutionUnit.h
Vendor import of lldb trunk r290819:
[FreeBSD/FreeBSD.git] / include / lldb / Expression / IRExecutionUnit.h
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 liblldb_IRExecutionUnit_h_
11 #define liblldb_IRExecutionUnit_h_
12
13 // C Includes
14 // C++ Includes
15 #include <atomic>
16 #include <memory>
17 #include <string>
18 #include <vector>
19
20 // Other libraries and framework includes
21 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
22 #include "llvm/IR/Module.h"
23
24 // Project includes
25 #include "lldb/Core/DataBufferHeap.h"
26 #include "lldb/Expression/IRMemoryMap.h"
27 #include "lldb/Symbol/ObjectFile.h"
28 #include "lldb/Symbol/SymbolContext.h"
29 #include "lldb/lldb-forward.h"
30 #include "lldb/lldb-private.h"
31
32 namespace llvm {
33
34 class Module;
35 class ExecutionEngine;
36 class ObjectCache;
37
38 } // namespace llvm
39
40 namespace lldb_private {
41
42 class Error;
43
44 //----------------------------------------------------------------------
45 /// @class IRExecutionUnit IRExecutionUnit.h "lldb/Expression/IRExecutionUnit.h"
46 /// @brief Contains the IR and, optionally, JIT-compiled code for a module.
47 ///
48 /// This class encapsulates the compiled version of an expression, in IR
49 /// form (for interpretation purposes) and in raw machine code form (for
50 /// execution in the target).
51 ///
52 /// This object wraps an IR module that comes from the expression parser,
53 /// and knows how to use the JIT to make it into executable code.  It can
54 /// then be used as input to the IR interpreter, or the address of the
55 /// executable code can be passed to a thread plan to run in the target.
56 ///
57 /// This class creates a subclass of LLVM's SectionMemoryManager, because that
58 /// is
59 /// how the JIT emits code.  Because LLDB needs to move JIT-compiled code
60 /// into the target process, the IRExecutionUnit knows how to copy the
61 /// emitted code into the target process.
62 //----------------------------------------------------------------------
63 class IRExecutionUnit : public std::enable_shared_from_this<IRExecutionUnit>,
64                         public IRMemoryMap,
65                         public ObjectFileJITDelegate {
66 public:
67   //------------------------------------------------------------------
68   /// Constructor
69   //------------------------------------------------------------------
70   IRExecutionUnit(std::unique_ptr<llvm::LLVMContext> &context_ap,
71                   std::unique_ptr<llvm::Module> &module_ap, ConstString &name,
72                   const lldb::TargetSP &target_sp, const SymbolContext &sym_ctx,
73                   std::vector<std::string> &cpu_features);
74
75   //------------------------------------------------------------------
76   /// Destructor
77   //------------------------------------------------------------------
78   ~IRExecutionUnit() override;
79
80   ConstString GetFunctionName() { return m_name; }
81
82   llvm::Module *GetModule() { return m_module; }
83
84   llvm::Function *GetFunction() {
85     return ((m_module != nullptr) ? m_module->getFunction(m_name.AsCString())
86                                   : nullptr);
87   }
88
89   void GetRunnableInfo(Error &error, lldb::addr_t &func_addr,
90                        lldb::addr_t &func_end);
91
92   //------------------------------------------------------------------
93   /// Accessors for IRForTarget and other clients that may want binary
94   /// data placed on their behalf.  The binary data is owned by the
95   /// IRExecutionUnit unless the client explicitly chooses to free it.
96   //------------------------------------------------------------------
97
98   lldb::addr_t WriteNow(const uint8_t *bytes, size_t size, Error &error);
99
100   void FreeNow(lldb::addr_t allocation);
101
102   //------------------------------------------------------------------
103   /// ObjectFileJITDelegate overrides
104   //------------------------------------------------------------------
105   lldb::ByteOrder GetByteOrder() const override;
106
107   uint32_t GetAddressByteSize() const override;
108
109   void PopulateSymtab(lldb_private::ObjectFile *obj_file,
110                       lldb_private::Symtab &symtab) override;
111
112   void PopulateSectionList(lldb_private::ObjectFile *obj_file,
113                            lldb_private::SectionList &section_list) override;
114
115   bool GetArchitecture(lldb_private::ArchSpec &arch) override;
116
117   lldb::ModuleSP GetJITModule();
118
119   lldb::addr_t FindSymbol(const ConstString &name);
120
121   void GetStaticInitializers(std::vector<lldb::addr_t> &static_initializers);
122
123   //----------------------------------------------------------------------
124   /// @class JittedFunction IRExecutionUnit.h
125   /// "lldb/Expression/IRExecutionUnit.h"
126   /// @brief Encapsulates a single function that has been generated by the JIT.
127   ///
128   /// Functions that have been generated by the JIT are first resident in the
129   /// local process, and then placed in the target process.  JittedFunction
130   /// represents a function possibly resident in both.
131   //----------------------------------------------------------------------
132   struct JittedEntity {
133     ConstString m_name;        ///< The function's name
134     lldb::addr_t m_local_addr; ///< The address of the function in LLDB's memory
135     lldb::addr_t
136         m_remote_addr; ///< The address of the function in the target's memory
137
138     //------------------------------------------------------------------
139     /// Constructor
140     ///
141     /// Initializes class variabes.
142     ///
143     /// @param[in] name
144     ///     The name of the function.
145     ///
146     /// @param[in] local_addr
147     ///     The address of the function in LLDB, or LLDB_INVALID_ADDRESS if
148     ///     it is not present in LLDB's memory.
149     ///
150     /// @param[in] remote_addr
151     ///     The address of the function in the target, or LLDB_INVALID_ADDRESS
152     ///     if it is not present in the target's memory.
153     //------------------------------------------------------------------
154     JittedEntity(const char *name,
155                  lldb::addr_t local_addr = LLDB_INVALID_ADDRESS,
156                  lldb::addr_t remote_addr = LLDB_INVALID_ADDRESS)
157         : m_name(name), m_local_addr(local_addr), m_remote_addr(remote_addr) {}
158   };
159
160   struct JittedFunction : JittedEntity {
161     bool m_external;
162     JittedFunction(const char *name, bool external,
163                    lldb::addr_t local_addr = LLDB_INVALID_ADDRESS,
164                    lldb::addr_t remote_addr = LLDB_INVALID_ADDRESS)
165         : JittedEntity(name, local_addr, remote_addr), m_external(external) {}
166   };
167
168   struct JittedGlobalVariable : JittedEntity {
169     JittedGlobalVariable(const char *name,
170                          lldb::addr_t local_addr = LLDB_INVALID_ADDRESS,
171                          lldb::addr_t remote_addr = LLDB_INVALID_ADDRESS)
172         : JittedEntity(name, local_addr, remote_addr) {}
173   };
174
175   const std::vector<JittedFunction> &GetJittedFunctions() {
176     return m_jitted_functions;
177   }
178
179   const std::vector<JittedGlobalVariable> &GetJittedGlobalVariables() {
180     return m_jitted_global_variables;
181   }
182
183 private:
184   //------------------------------------------------------------------
185   /// Look up the object in m_address_map that contains a given address,
186   /// find where it was copied to, and return the remote address at the
187   /// same offset into the copied entity
188   ///
189   /// @param[in] local_address
190   ///     The address in the debugger.
191   ///
192   /// @return
193   ///     The address in the target process.
194   //------------------------------------------------------------------
195   lldb::addr_t GetRemoteAddressForLocal(lldb::addr_t local_address);
196
197   //------------------------------------------------------------------
198   /// Look up the object in m_address_map that contains a given address,
199   /// find where it was copied to, and return its address range in the
200   /// target process
201   ///
202   /// @param[in] local_address
203   ///     The address in the debugger.
204   ///
205   /// @return
206   ///     The range of the containing object in the target process.
207   //------------------------------------------------------------------
208   typedef std::pair<lldb::addr_t, uintptr_t> AddrRange;
209   AddrRange GetRemoteRangeForLocal(lldb::addr_t local_address);
210
211   //------------------------------------------------------------------
212   /// Commit all allocations to the process and record where they were stored.
213   ///
214   /// @param[in] process
215   ///     The process to allocate memory in.
216   ///
217   /// @return
218   ///     True <=> all allocations were performed successfully.
219   ///     This method will attempt to free allocated memory if the
220   ///     operation fails.
221   //------------------------------------------------------------------
222   bool CommitAllocations(lldb::ProcessSP &process_sp);
223
224   //------------------------------------------------------------------
225   /// Report all committed allocations to the execution engine.
226   ///
227   /// @param[in] engine
228   ///     The execution engine to notify.
229   //------------------------------------------------------------------
230   void ReportAllocations(llvm::ExecutionEngine &engine);
231
232   //------------------------------------------------------------------
233   /// Write the contents of all allocations to the process.
234   ///
235   /// @param[in] local_address
236   ///     The process containing the allocations.
237   ///
238   /// @return
239   ///     True <=> all allocations were performed successfully.
240   //------------------------------------------------------------------
241   bool WriteData(lldb::ProcessSP &process_sp);
242
243   Error DisassembleFunction(Stream &stream, lldb::ProcessSP &process_sp);
244
245   struct SearchSpec;
246
247   void CollectCandidateCNames(std::vector<SearchSpec> &C_specs,
248                               const ConstString &name);
249
250   void CollectCandidateCPlusPlusNames(std::vector<SearchSpec> &CPP_specs,
251                                       const std::vector<SearchSpec> &C_specs,
252                                       const SymbolContext &sc);
253
254   void CollectFallbackNames(std::vector<SearchSpec> &fallback_specs,
255                             const std::vector<SearchSpec> &C_specs);
256
257   lldb::addr_t FindInSymbols(const std::vector<SearchSpec> &specs,
258                              const lldb_private::SymbolContext &sc);
259
260   lldb::addr_t FindInRuntimes(const std::vector<SearchSpec> &specs,
261                               const lldb_private::SymbolContext &sc);
262
263   lldb::addr_t FindInUserDefinedSymbols(const std::vector<SearchSpec> &specs,
264                                         const lldb_private::SymbolContext &sc);
265
266   void ReportSymbolLookupError(const ConstString &name);
267
268   class MemoryManager : public llvm::SectionMemoryManager {
269   public:
270     MemoryManager(IRExecutionUnit &parent);
271
272     ~MemoryManager() override;
273
274     //------------------------------------------------------------------
275     /// Allocate space for executable code, and add it to the
276     /// m_spaceBlocks map
277     ///
278     /// @param[in] Size
279     ///     The size of the area.
280     ///
281     /// @param[in] Alignment
282     ///     The required alignment of the area.
283     ///
284     /// @param[in] SectionID
285     ///     A unique identifier for the section.
286     ///
287     /// @return
288     ///     Allocated space.
289     //------------------------------------------------------------------
290     uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
291                                  unsigned SectionID,
292                                  llvm::StringRef SectionName) override;
293
294     //------------------------------------------------------------------
295     /// Allocate space for data, and add it to the m_spaceBlocks map
296     ///
297     /// @param[in] Size
298     ///     The size of the area.
299     ///
300     /// @param[in] Alignment
301     ///     The required alignment of the area.
302     ///
303     /// @param[in] SectionID
304     ///     A unique identifier for the section.
305     ///
306     /// @param[in] IsReadOnly
307     ///     Flag indicating the section is read-only.
308     ///
309     /// @return
310     ///     Allocated space.
311     //------------------------------------------------------------------
312     uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
313                                  unsigned SectionID,
314                                  llvm::StringRef SectionName,
315                                  bool IsReadOnly) override;
316
317     //------------------------------------------------------------------
318     /// Called when object loading is complete and section page
319     /// permissions can be applied. Currently unimplemented for LLDB.
320     ///
321     /// @param[out] ErrMsg
322     ///     The error that prevented the page protection from succeeding.
323     ///
324     /// @return
325     ///     True in case of failure, false in case of success.
326     //------------------------------------------------------------------
327     bool finalizeMemory(std::string *ErrMsg) override {
328       // TODO: Ensure that the instruction cache is flushed because
329       // relocations are updated by dy-load.  See:
330       //   sys::Memory::InvalidateInstructionCache
331       //   llvm::SectionMemoryManager
332       return false;
333     }
334
335     void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
336                           size_t Size) override {}
337
338     uint64_t getSymbolAddress(const std::string &Name) override;
339
340     void *getPointerToNamedFunction(const std::string &Name,
341                                     bool AbortOnFailure = true) override;
342
343   private:
344     std::unique_ptr<SectionMemoryManager> m_default_mm_ap; ///< The memory
345                                                            ///allocator to use
346                                                            ///in actually
347                                                            ///creating space.
348                                                            ///All calls are
349                                                            ///passed through to
350                                                            ///it.
351     IRExecutionUnit &m_parent; ///< The execution unit this is a proxy for.
352   };
353
354   static const unsigned eSectionIDInvalid = (unsigned)-1;
355
356   //----------------------------------------------------------------------
357   /// @class AllocationRecord IRExecutionUnit.h
358   /// "lldb/Expression/IRExecutionUnit.h"
359   /// @brief Encapsulates a single allocation request made by the JIT.
360   ///
361   /// Allocations made by the JIT are first queued up and then applied in
362   /// bulk to the underlying process.
363   //----------------------------------------------------------------------
364   enum class AllocationKind { Stub, Code, Data, Global, Bytes };
365
366   static lldb::SectionType
367   GetSectionTypeFromSectionName(const llvm::StringRef &name,
368                                 AllocationKind alloc_kind);
369
370   struct AllocationRecord {
371     std::string m_name;
372     lldb::addr_t m_process_address;
373     uintptr_t m_host_address;
374     uint32_t m_permissions;
375     lldb::SectionType m_sect_type;
376     size_t m_size;
377     unsigned m_alignment;
378     unsigned m_section_id;
379
380     AllocationRecord(uintptr_t host_address, uint32_t permissions,
381                      lldb::SectionType sect_type, size_t size,
382                      unsigned alignment, unsigned section_id, const char *name)
383         : m_name(), m_process_address(LLDB_INVALID_ADDRESS),
384           m_host_address(host_address), m_permissions(permissions),
385           m_sect_type(sect_type), m_size(size), m_alignment(alignment),
386           m_section_id(section_id) {
387       if (name && name[0])
388         m_name = name;
389     }
390
391     void dump(Log *log);
392   };
393
394   bool CommitOneAllocation(lldb::ProcessSP &process_sp, Error &error,
395                            AllocationRecord &record);
396
397   typedef std::vector<AllocationRecord> RecordVector;
398   RecordVector m_records;
399
400   std::unique_ptr<llvm::LLVMContext> m_context_ap;
401   std::unique_ptr<llvm::ExecutionEngine> m_execution_engine_ap;
402   std::unique_ptr<llvm::ObjectCache> m_object_cache_ap;
403   std::unique_ptr<llvm::Module>
404       m_module_ap;        ///< Holder for the module until it's been handed off
405   llvm::Module *m_module; ///< Owned by the execution engine
406   std::vector<std::string> m_cpu_features;
407   std::vector<JittedFunction> m_jitted_functions; ///< A vector of all functions
408                                                   ///that have been JITted into
409                                                   ///machine code
410   std::vector<JittedGlobalVariable> m_jitted_global_variables; ///< A vector of
411                                                                ///all functions
412                                                                ///that have been
413                                                                ///JITted into
414                                                                ///machine code
415   const ConstString m_name;
416   SymbolContext m_sym_ctx; ///< Used for symbol lookups
417   std::vector<ConstString> m_failed_lookups;
418
419   std::atomic<bool> m_did_jit;
420
421   lldb::addr_t m_function_load_addr;
422   lldb::addr_t m_function_end_load_addr;
423
424   bool m_strip_underscore; ///< True for platforms where global symbols have a _
425                            ///prefix
426   bool m_reported_allocations; ///< True after allocations have been reported.
427                                ///It is possible that
428   ///< sections will be allocated when this is true, in which case they weren't
429   ///< depended on by any function.  (Top-level code defining a variable, but
430   ///< defining no functions using that variable, would do this.)  If this
431   ///< is true, any allocations need to be committed immediately -- no
432   ///< opportunity for relocation.
433 };
434
435 } // namespace lldb_private
436
437 #endif // liblldb_IRExecutionUnit_h_