LLDB mainline
IRExecutionUnit.h
Go to the documentation of this file.
1//===-- IRExecutionUnit.h ---------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLDB_EXPRESSION_IREXECUTIONUNIT_H
10#define LLDB_EXPRESSION_IREXECUTIONUNIT_H
11
12#include <atomic>
13#include <memory>
14#include <string>
15#include <vector>
16
17#include "llvm/ExecutionEngine/SectionMemoryManager.h"
18#include "llvm/IR/Module.h"
19
25#include "lldb/lldb-forward.h"
26#include "lldb/lldb-private.h"
27
28namespace llvm {
29
30class Module;
31class ExecutionEngine;
32class ObjectCache;
33
34} // namespace llvm
35
36namespace lldb_private {
37
38class Status;
39
40/// \class IRExecutionUnit IRExecutionUnit.h
41/// "lldb/Expression/IRExecutionUnit.h" Contains the IR and, optionally, JIT-
42/// compiled code for a module.
43///
44/// This class encapsulates the compiled version of an expression, in IR form
45/// (for interpretation purposes) and in raw machine code form (for execution
46/// in the target).
47///
48/// This object wraps an IR module that comes from the expression parser, and
49/// knows how to use the JIT to make it into executable code. It can then be
50/// used as input to the IR interpreter, or the address of the executable code
51/// can be passed to a thread plan to run in the target.
52///
53/// This class creates a subclass of LLVM's SectionMemoryManager, because that
54/// is how the JIT emits code. Because LLDB needs to move JIT-compiled code
55/// into the target process, the IRExecutionUnit knows how to copy the emitted
56/// code into the target process.
57class IRExecutionUnit : public std::enable_shared_from_this<IRExecutionUnit>,
58 public IRMemoryMap,
60public:
61 /// Constructor
62 IRExecutionUnit(std::unique_ptr<llvm::LLVMContext> &context_up,
63 std::unique_ptr<llvm::Module> &module_up, ConstString &name,
64 const lldb::TargetSP &target_sp, const SymbolContext &sym_ctx,
65 std::vector<std::string> &cpu_features);
66
67 /// Destructor
68 ~IRExecutionUnit() override;
69
71
72 llvm::Module *GetModule() { return m_module; }
73
74 llvm::Function *GetFunction() {
75 return ((m_module != nullptr) ? m_module->getFunction(m_name.GetStringRef())
76 : nullptr);
77 }
78
79 void GetRunnableInfo(Status &error, lldb::addr_t &func_addr,
80 lldb::addr_t &func_end);
81
82 /// Accessors for IRForTarget and other clients that may want binary data
83 /// placed on their behalf. The binary data is owned by the IRExecutionUnit
84 /// unless the client explicitly chooses to free it.
85
86 lldb::addr_t WriteNow(const uint8_t *bytes, size_t size, Status &error);
87
88 void FreeNow(lldb::addr_t allocation);
89
90 /// ObjectFileJITDelegate overrides
91 lldb::ByteOrder GetByteOrder() const override;
92
93 uint32_t GetAddressByteSize() const override;
94
96 lldb_private::Symtab &symtab) override;
97
99 lldb_private::SectionList &section_list) override;
100
101 ArchSpec GetArchitecture() override;
102
103 lldb::TargetSP GetTargetSP() override { return GetTarget(); }
104
106
107 lldb::addr_t FindSymbol(ConstString name, bool &missing_weak);
108
109 void GetStaticInitializers(std::vector<lldb::addr_t> &static_initializers);
110
111 /// \class JittedFunction IRExecutionUnit.h
112 /// "lldb/Expression/IRExecutionUnit.h"
113 /// Encapsulates a single function that has been generated by the JIT.
114 ///
115 /// Functions that have been generated by the JIT are first resident in the
116 /// local process, and then placed in the target process. JittedFunction
117 /// represents a function possibly resident in both.
119 ConstString m_name; ///< The function's name
120 lldb::addr_t m_local_addr; ///< The address of the function in LLDB's memory
122 m_remote_addr; ///< The address of the function in the target's memory
123
124 /// Constructor
125 ///
126 /// Initializes class variabes.
127 ///
128 /// \param[in] name
129 /// The name of the function.
130 ///
131 /// \param[in] local_addr
132 /// The address of the function in LLDB, or LLDB_INVALID_ADDRESS if
133 /// it is not present in LLDB's memory.
134 ///
135 /// \param[in] remote_addr
136 /// The address of the function in the target, or LLDB_INVALID_ADDRESS
137 /// if it is not present in the target's memory.
138 JittedEntity(const char *name,
141 : m_name(name), m_local_addr(local_addr), m_remote_addr(remote_addr) {}
142 };
143
146 JittedFunction(const char *name, bool external,
149 : JittedEntity(name, local_addr, remote_addr), m_external(external) {}
150 };
151
153 JittedGlobalVariable(const char *name,
156 : JittedEntity(name, local_addr, remote_addr) {}
157 };
158
159 const std::vector<JittedFunction> &GetJittedFunctions() {
160 return m_jitted_functions;
161 }
162
163 const std::vector<JittedGlobalVariable> &GetJittedGlobalVariables() {
165 }
166
168 for (auto const &ctx : contexts)
169 if (ctx.module_sp)
170 m_preferred_modules.Append(ctx.module_sp);
171 }
172
173private:
174 /// Look up the object in m_address_map that contains a given address, find
175 /// where it was copied to, and return the remote address at the same offset
176 /// into the copied entity
177 ///
178 /// \param[in] local_address
179 /// The address in the debugger.
180 ///
181 /// \return
182 /// The address in the target process.
184
185 typedef std::pair<lldb::addr_t, uintptr_t> AddrRange;
186
187 /// Look up the object in m_address_map that contains a given address, find
188 /// where it was copied to, and return its address range in the target
189 /// process
190 ///
191 /// \param[in] local_address
192 /// The address in the debugger.
193 ///
194 /// \return
195 /// The range of the containing object in the target process.
197
198 /// Commit all allocations to the process and record where they were stored.
199 ///
200 /// \param[in] process_sp
201 /// The process to allocate memory in.
202 ///
203 /// \return
204 /// True <=> all allocations were performed successfully.
205 /// This method will attempt to free allocated memory if the
206 /// operation fails.
207 bool CommitAllocations(lldb::ProcessSP &process_sp);
208
209 /// Report all committed allocations to the execution engine.
210 ///
211 /// \param[in] engine
212 /// The execution engine to notify.
213 void ReportAllocations(llvm::ExecutionEngine &engine);
214
215 /// Write the contents of all allocations to the process.
216 ///
217 /// \param[in] process_sp
218 /// The process containing the allocations.
219 ///
220 /// \return
221 /// True <=> all allocations were performed successfully.
222 bool WriteData(lldb::ProcessSP &process_sp);
223
224 Status DisassembleFunction(Stream &stream, lldb::ProcessSP &process_sp);
225
226 void CollectCandidateCNames(std::vector<ConstString> &C_names,
227 ConstString name);
228
229 void CollectCandidateCPlusPlusNames(std::vector<ConstString> &CPP_names,
230 const std::vector<ConstString> &C_names,
231 const SymbolContext &sc);
232
233 lldb::addr_t FindInSymbols(const std::vector<ConstString> &names,
235 bool &symbol_was_missing_weak);
236
237 lldb::addr_t FindInRuntimes(const std::vector<ConstString> &names,
239
240 lldb::addr_t FindInUserDefinedSymbols(const std::vector<ConstString> &names,
242
244
245 class MemoryManager : public llvm::SectionMemoryManager {
246 public:
248
249 ~MemoryManager() override;
250
251 /// Allocate space for executable code, and add it to the m_spaceBlocks
252 /// map
253 ///
254 /// \param[in] Size
255 /// The size of the area.
256 ///
257 /// \param[in] Alignment
258 /// The required alignment of the area.
259 ///
260 /// \param[in] SectionID
261 /// A unique identifier for the section.
262 ///
263 /// \return
264 /// Allocated space.
265 uint8_t *allocateCodeSection(uintptr_t Size, unsigned Alignment,
266 unsigned SectionID,
267 llvm::StringRef SectionName) override;
268
269 /// Allocate space for data, and add it to the m_spaceBlocks map
270 ///
271 /// \param[in] Size
272 /// The size of the area.
273 ///
274 /// \param[in] Alignment
275 /// The required alignment of the area.
276 ///
277 /// \param[in] SectionID
278 /// A unique identifier for the section.
279 ///
280 /// \param[in] IsReadOnly
281 /// Flag indicating the section is read-only.
282 ///
283 /// \return
284 /// Allocated space.
285 uint8_t *allocateDataSection(uintptr_t Size, unsigned Alignment,
286 unsigned SectionID,
287 llvm::StringRef SectionName,
288 bool IsReadOnly) override;
289
290 /// Called when object loading is complete and section page permissions
291 /// can be applied. Currently unimplemented for LLDB.
292 ///
293 /// \param[out] ErrMsg
294 /// The error that prevented the page protection from succeeding.
295 ///
296 /// \return
297 /// True in case of failure, false in case of success.
298 bool finalizeMemory(std::string *ErrMsg) override {
299 // TODO: Ensure that the instruction cache is flushed because
300 // relocations are updated by dy-load. See:
301 // sys::Memory::InvalidateInstructionCache
302 // llvm::SectionMemoryManager
303 return false;
304 }
305
306 // Ignore any EHFrame registration.
307 void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr,
308 size_t Size) override {}
309 void deregisterEHFrames() override {}
310
311 uint64_t getSymbolAddress(const std::string &Name) override;
312
313 // Find the address of the symbol Name. If Name is a missing weak symbol
314 // then missing_weak will be true.
315 uint64_t GetSymbolAddressAndPresence(const std::string &Name,
316 bool &missing_weak);
317
318 llvm::JITSymbol findSymbol(const std::string &Name) override;
319
320 void *getPointerToNamedFunction(const std::string &Name,
321 bool AbortOnFailure = true) override;
322
323 private:
324 std::unique_ptr<SectionMemoryManager> m_default_mm_up; ///< The memory
325 /// allocator to use
326 /// in actually
327 /// creating space.
328 /// All calls are
329 /// passed through to
330 /// it.
331 IRExecutionUnit &m_parent; ///< The execution unit this is a proxy for.
332 };
333
334 static const unsigned eSectionIDInvalid = (unsigned)-1;
335
337
338 static lldb::SectionType
339 GetSectionTypeFromSectionName(const llvm::StringRef &name,
340 AllocationKind alloc_kind);
341
342 /// Encapsulates a single allocation request made by the JIT.
343 ///
344 /// Allocations made by the JIT are first queued up and then applied in bulk
345 /// to the underlying process.
347 std::string m_name;
349 uintptr_t m_host_address;
352 size_t m_size;
353 unsigned m_alignment;
354 unsigned m_section_id;
355
356 AllocationRecord(uintptr_t host_address, uint32_t permissions,
357 lldb::SectionType sect_type, size_t size,
358 unsigned alignment, unsigned section_id, const char *name)
360 m_permissions(permissions), m_sect_type(sect_type), m_size(size),
361 m_alignment(alignment), m_section_id(section_id) {
362 if (name && name[0])
363 m_name = name;
364 }
365
366 void dump(Log *log);
367 };
368
370 AllocationRecord &record);
371
372 typedef std::vector<AllocationRecord> RecordVector;
374
375 std::unique_ptr<llvm::LLVMContext> m_context_up;
376 std::unique_ptr<llvm::ExecutionEngine> m_execution_engine_up;
377 std::unique_ptr<llvm::ObjectCache> m_object_cache_up;
378 std::unique_ptr<llvm::Module>
379 m_module_up; ///< Holder for the module until it's been handed off
380 llvm::Module *m_module; ///< Owned by the execution engine
381 std::vector<std::string> m_cpu_features;
382 std::vector<JittedFunction> m_jitted_functions; ///< A vector of all functions
383 ///that have been JITted into
384 ///machine code
385 std::vector<JittedGlobalVariable> m_jitted_global_variables; ///< A vector of
386 ///all functions
387 ///that have been
388 ///JITted into
389 ///machine code
391 SymbolContext m_sym_ctx; ///< Used for symbol lookups
392 std::vector<ConstString> m_failed_lookups;
393
394 std::atomic<bool> m_did_jit;
395
398
399 bool m_strip_underscore = true; ///< True for platforms where global symbols
400 /// have a _ prefix
401 bool m_reported_allocations; ///< True after allocations have been reported.
402 ///It is possible that
403 ///< sections will be allocated when this is true, in which case they weren't
404 ///< depended on by any function. (Top-level code defining a variable, but
405 ///< defining no functions using that variable, would do this.) If this
406 ///< is true, any allocations need to be committed immediately -- no
407 ///< opportunity for relocation.
408
409 ///< Any Module in this list will be used for symbol/function lookup
410 ///< before any other module (except for the module corresponding to the
411 ///< current frame).
413};
414
415} // namespace lldb_private
416
417#endif // LLDB_EXPRESSION_IREXECUTIONUNIT_H
static llvm::raw_ostream & error(Stream &strm)
An architecture specification class.
Definition ArchSpec.h:32
A uniqued constant string class.
Definition ConstString.h:40
void * getPointerToNamedFunction(const std::string &Name, bool AbortOnFailure=true) override
void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size) override
bool finalizeMemory(std::string *ErrMsg) override
Called when object loading is complete and section page permissions can be applied.
std::unique_ptr< SectionMemoryManager > m_default_mm_up
The memory allocator to use in actually creating space.
uint64_t getSymbolAddress(const std::string &Name) override
uint8_t * allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, llvm::StringRef SectionName, bool IsReadOnly) override
Allocate space for data, and add it to the m_spaceBlocks map.
IRExecutionUnit & m_parent
The execution unit this is a proxy for.
uint64_t GetSymbolAddressAndPresence(const std::string &Name, bool &missing_weak)
llvm::JITSymbol findSymbol(const std::string &Name) override
uint8_t * allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, llvm::StringRef SectionName) override
Allocate space for executable code, and add it to the m_spaceBlocks map.
std::vector< std::string > m_cpu_features
void CollectCandidateCPlusPlusNames(std::vector< ConstString > &CPP_names, const std::vector< ConstString > &C_names, const SymbolContext &sc)
lldb::addr_t WriteNow(const uint8_t *bytes, size_t size, Status &error)
Accessors for IRForTarget and other clients that may want binary data placed on their behalf.
static const unsigned eSectionIDInvalid
lldb::TargetSP GetTargetSP() override
Returns the Target this JIT-compiled code was produced for, or null if the delegate that created this...
void PopulateSymtab(lldb_private::ObjectFile *obj_file, lldb_private::Symtab &symtab) override
lldb::addr_t FindInSymbols(const std::vector< ConstString > &names, const lldb_private::SymbolContext &sc, bool &symbol_was_missing_weak)
void GetRunnableInfo(Status &error, lldb::addr_t &func_addr, lldb::addr_t &func_end)
lldb::ByteOrder GetByteOrder() const override
ObjectFileJITDelegate overrides.
SymbolContext m_sym_ctx
Used for symbol lookups.
std::vector< JittedFunction > m_jitted_functions
A vector of all functions that have been JITted into machine code.
Status DisassembleFunction(Stream &stream, lldb::ProcessSP &process_sp)
std::vector< ConstString > m_failed_lookups
std::unique_ptr< llvm::Module > m_module_up
Holder for the module until it's been handed off.
lldb::addr_t FindSymbol(ConstString name, bool &missing_weak)
lldb::addr_t FindInRuntimes(const std::vector< ConstString > &names, const lldb_private::SymbolContext &sc)
IRExecutionUnit(std::unique_ptr< llvm::LLVMContext > &context_up, std::unique_ptr< llvm::Module > &module_up, ConstString &name, const lldb::TargetSP &target_sp, const SymbolContext &sym_ctx, std::vector< std::string > &cpu_features)
Constructor.
static lldb::SectionType GetSectionTypeFromSectionName(const llvm::StringRef &name, AllocationKind alloc_kind)
uint32_t GetAddressByteSize() const override
bool CommitAllocations(lldb::ProcessSP &process_sp)
Commit all allocations to the process and record where they were stored.
bool CommitOneAllocation(lldb::ProcessSP &process_sp, Status &error, AllocationRecord &record)
void GetStaticInitializers(std::vector< lldb::addr_t > &static_initializers)
void CollectCandidateCNames(std::vector< ConstString > &C_names, ConstString name)
std::unique_ptr< llvm::ExecutionEngine > m_execution_engine_up
llvm::Module * m_module
Owned by the execution engine.
std::unique_ptr< llvm::LLVMContext > m_context_up
void AppendPreferredSymbolContexts(SymbolContextList const &contexts)
const std::vector< JittedGlobalVariable > & GetJittedGlobalVariables()
AddrRange GetRemoteRangeForLocal(lldb::addr_t local_address)
Look up the object in m_address_map that contains a given address, find where it was copied to,...
bool m_strip_underscore
True for platforms where global symbols have a _ prefix.
void ReportSymbolLookupError(ConstString name)
lldb::addr_t FindInUserDefinedSymbols(const std::vector< ConstString > &names, const lldb_private::SymbolContext &sc)
void PopulateSectionList(lldb_private::ObjectFile *obj_file, lldb_private::SectionList &section_list) override
std::vector< AllocationRecord > RecordVector
const std::vector< JittedFunction > & GetJittedFunctions()
std::pair< lldb::addr_t, uintptr_t > AddrRange
void FreeNow(lldb::addr_t allocation)
std::vector< JittedGlobalVariable > m_jitted_global_variables
A vector of all functions that have been JITted into machine code.
bool WriteData(lldb::ProcessSP &process_sp)
Write the contents of all allocations to the process.
std::unique_ptr< llvm::ObjectCache > m_object_cache_up
~IRExecutionUnit() override
Destructor.
void ReportAllocations(llvm::ExecutionEngine &engine)
Report all committed allocations to the execution engine.
lldb::addr_t GetRemoteAddressForLocal(lldb::addr_t local_address)
Look up the object in m_address_map that contains a given address, find where it was copied to,...
bool m_reported_allocations
True after allocations have been reported.
lldb::TargetSP GetTarget()
Definition IRMemoryMap.h:86
IRMemoryMap(lldb::TargetSP target_sp)
A collection class for Module objects.
Definition ModuleList.h:125
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
An error handling class.
Definition Status.h:118
A stream class that can stream formatted output to a file.
Definition Stream.h:28
Defines a list of symbol context objects.
Defines a symbol context baton that can be handed other debug core functions.
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
std::shared_ptr< lldb_private::Process > ProcessSP
ByteOrder
Byte ordering definitions.
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::Module > ModuleSP
AllocationRecord(uintptr_t host_address, uint32_t permissions, lldb::SectionType sect_type, size_t size, unsigned alignment, unsigned section_id, const char *name)
JittedEntity(const char *name, lldb::addr_t local_addr=LLDB_INVALID_ADDRESS, lldb::addr_t remote_addr=LLDB_INVALID_ADDRESS)
Constructor.
ConstString m_name
The function's name.
lldb::addr_t m_remote_addr
The address of the function in the target's memory.
lldb::addr_t m_local_addr
The address of the function in LLDB's memory.
JittedFunction(const char *name, bool external, lldb::addr_t local_addr=LLDB_INVALID_ADDRESS, lldb::addr_t remote_addr=LLDB_INVALID_ADDRESS)
JittedGlobalVariable(const char *name, lldb::addr_t local_addr=LLDB_INVALID_ADDRESS, lldb::addr_t remote_addr=LLDB_INVALID_ADDRESS)