[DAGCombiner] Eliminate dead stores to stack.
[llvm-complete.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyldImpl.h
bloba4f1c55ca3946ab997e52671c6c39fa617c7fd89
1 //===-- RuntimeDyldImpl.h - Run-time dynamic linker for MC-JIT --*- 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 // Interface for the implementations of runtime dynamic linker facilities.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
14 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
20 #include "llvm/ExecutionEngine/RuntimeDyld.h"
21 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Support/Mutex.h"
28 #include "llvm/Support/SwapByteOrder.h"
29 #include <map>
30 #include <system_error>
31 #include <unordered_map>
33 using namespace llvm;
34 using namespace llvm::object;
36 namespace llvm {
38 class Twine;
40 #define UNIMPLEMENTED_RELOC(RelType) \
41 case RelType: \
42 return make_error<RuntimeDyldError>("Unimplemented relocation: " #RelType)
44 /// SectionEntry - represents a section emitted into memory by the dynamic
45 /// linker.
46 class SectionEntry {
47 /// Name - section name.
48 std::string Name;
50 /// Address - address in the linker's memory where the section resides.
51 uint8_t *Address;
53 /// Size - section size. Doesn't include the stubs.
54 size_t Size;
56 /// LoadAddress - the address of the section in the target process's memory.
57 /// Used for situations in which JIT-ed code is being executed in the address
58 /// space of a separate process. If the code executes in the same address
59 /// space where it was JIT-ed, this just equals Address.
60 uint64_t LoadAddress;
62 /// StubOffset - used for architectures with stub functions for far
63 /// relocations (like ARM).
64 uintptr_t StubOffset;
66 /// The total amount of space allocated for this section. This includes the
67 /// section size and the maximum amount of space that the stubs can occupy.
68 size_t AllocationSize;
70 /// ObjAddress - address of the section in the in-memory object file. Used
71 /// for calculating relocations in some object formats (like MachO).
72 uintptr_t ObjAddress;
74 public:
75 SectionEntry(StringRef name, uint8_t *address, size_t size,
76 size_t allocationSize, uintptr_t objAddress)
77 : Name(name), Address(address), Size(size),
78 LoadAddress(reinterpret_cast<uintptr_t>(address)), StubOffset(size),
79 AllocationSize(allocationSize), ObjAddress(objAddress) {
80 // AllocationSize is used only in asserts, prevent an "unused private field"
81 // warning:
82 (void)AllocationSize;
85 StringRef getName() const { return Name; }
87 uint8_t *getAddress() const { return Address; }
89 /// Return the address of this section with an offset.
90 uint8_t *getAddressWithOffset(unsigned OffsetBytes) const {
91 assert(OffsetBytes <= AllocationSize && "Offset out of bounds!");
92 return Address + OffsetBytes;
95 size_t getSize() const { return Size; }
97 uint64_t getLoadAddress() const { return LoadAddress; }
98 void setLoadAddress(uint64_t LA) { LoadAddress = LA; }
100 /// Return the load address of this section with an offset.
101 uint64_t getLoadAddressWithOffset(unsigned OffsetBytes) const {
102 assert(OffsetBytes <= AllocationSize && "Offset out of bounds!");
103 return LoadAddress + OffsetBytes;
106 uintptr_t getStubOffset() const { return StubOffset; }
108 void advanceStubOffset(unsigned StubSize) {
109 StubOffset += StubSize;
110 assert(StubOffset <= AllocationSize && "Not enough space allocated!");
113 uintptr_t getObjAddress() const { return ObjAddress; }
116 /// RelocationEntry - used to represent relocations internally in the dynamic
117 /// linker.
118 class RelocationEntry {
119 public:
120 /// SectionID - the section this relocation points to.
121 unsigned SectionID;
123 /// Offset - offset into the section.
124 uint64_t Offset;
126 /// RelType - relocation type.
127 uint32_t RelType;
129 /// Addend - the relocation addend encoded in the instruction itself. Also
130 /// used to make a relocation section relative instead of symbol relative.
131 int64_t Addend;
133 struct SectionPair {
134 uint32_t SectionA;
135 uint32_t SectionB;
138 /// SymOffset - Section offset of the relocation entry's symbol (used for GOT
139 /// lookup).
140 union {
141 uint64_t SymOffset;
142 SectionPair Sections;
145 /// True if this is a PCRel relocation (MachO specific).
146 bool IsPCRel;
148 /// The size of this relocation (MachO specific).
149 unsigned Size;
151 // ARM (MachO and COFF) specific.
152 bool IsTargetThumbFunc = false;
154 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend)
155 : SectionID(id), Offset(offset), RelType(type), Addend(addend),
156 SymOffset(0), IsPCRel(false), Size(0), IsTargetThumbFunc(false) {}
158 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
159 uint64_t symoffset)
160 : SectionID(id), Offset(offset), RelType(type), Addend(addend),
161 SymOffset(symoffset), IsPCRel(false), Size(0),
162 IsTargetThumbFunc(false) {}
164 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
165 bool IsPCRel, unsigned Size)
166 : SectionID(id), Offset(offset), RelType(type), Addend(addend),
167 SymOffset(0), IsPCRel(IsPCRel), Size(Size), IsTargetThumbFunc(false) {}
169 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
170 unsigned SectionA, uint64_t SectionAOffset, unsigned SectionB,
171 uint64_t SectionBOffset, bool IsPCRel, unsigned Size)
172 : SectionID(id), Offset(offset), RelType(type),
173 Addend(SectionAOffset - SectionBOffset + addend), IsPCRel(IsPCRel),
174 Size(Size), IsTargetThumbFunc(false) {
175 Sections.SectionA = SectionA;
176 Sections.SectionB = SectionB;
179 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
180 unsigned SectionA, uint64_t SectionAOffset, unsigned SectionB,
181 uint64_t SectionBOffset, bool IsPCRel, unsigned Size,
182 bool IsTargetThumbFunc)
183 : SectionID(id), Offset(offset), RelType(type),
184 Addend(SectionAOffset - SectionBOffset + addend), IsPCRel(IsPCRel),
185 Size(Size), IsTargetThumbFunc(IsTargetThumbFunc) {
186 Sections.SectionA = SectionA;
187 Sections.SectionB = SectionB;
191 class RelocationValueRef {
192 public:
193 unsigned SectionID;
194 uint64_t Offset;
195 int64_t Addend;
196 const char *SymbolName;
197 bool IsStubThumb = false;
198 RelocationValueRef() : SectionID(0), Offset(0), Addend(0),
199 SymbolName(nullptr) {}
201 inline bool operator==(const RelocationValueRef &Other) const {
202 return SectionID == Other.SectionID && Offset == Other.Offset &&
203 Addend == Other.Addend && SymbolName == Other.SymbolName &&
204 IsStubThumb == Other.IsStubThumb;
206 inline bool operator<(const RelocationValueRef &Other) const {
207 if (SectionID != Other.SectionID)
208 return SectionID < Other.SectionID;
209 if (Offset != Other.Offset)
210 return Offset < Other.Offset;
211 if (Addend != Other.Addend)
212 return Addend < Other.Addend;
213 if (IsStubThumb != Other.IsStubThumb)
214 return IsStubThumb < Other.IsStubThumb;
215 return SymbolName < Other.SymbolName;
219 /// Symbol info for RuntimeDyld.
220 class SymbolTableEntry {
221 public:
222 SymbolTableEntry() = default;
224 SymbolTableEntry(unsigned SectionID, uint64_t Offset, JITSymbolFlags Flags)
225 : Offset(Offset), SectionID(SectionID), Flags(Flags) {}
227 unsigned getSectionID() const { return SectionID; }
228 uint64_t getOffset() const { return Offset; }
229 void setOffset(uint64_t NewOffset) { Offset = NewOffset; }
231 JITSymbolFlags getFlags() const { return Flags; }
233 private:
234 uint64_t Offset = 0;
235 unsigned SectionID = 0;
236 JITSymbolFlags Flags = JITSymbolFlags::None;
239 typedef StringMap<SymbolTableEntry> RTDyldSymbolTable;
241 class RuntimeDyldImpl {
242 friend class RuntimeDyld::LoadedObjectInfo;
243 friend class RuntimeDyldCheckerImpl;
244 protected:
245 static const unsigned AbsoluteSymbolSection = ~0U;
247 // The MemoryManager to load objects into.
248 RuntimeDyld::MemoryManager &MemMgr;
250 // The symbol resolver to use for external symbols.
251 JITSymbolResolver &Resolver;
253 // Attached RuntimeDyldChecker instance. Null if no instance attached.
254 RuntimeDyldCheckerImpl *Checker;
256 // A list of all sections emitted by the dynamic linker. These sections are
257 // referenced in the code by means of their index in this list - SectionID.
258 typedef SmallVector<SectionEntry, 64> SectionList;
259 SectionList Sections;
261 typedef unsigned SID; // Type for SectionIDs
262 #define RTDYLD_INVALID_SECTION_ID ((RuntimeDyldImpl::SID)(-1))
264 // Keep a map of sections from object file to the SectionID which
265 // references it.
266 typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
268 // A global symbol table for symbols from all loaded modules.
269 RTDyldSymbolTable GlobalSymbolTable;
271 // Keep a map of common symbols to their info pairs
272 typedef std::vector<SymbolRef> CommonSymbolList;
274 // For each symbol, keep a list of relocations based on it. Anytime
275 // its address is reassigned (the JIT re-compiled the function, e.g.),
276 // the relocations get re-resolved.
277 // The symbol (or section) the relocation is sourced from is the Key
278 // in the relocation list where it's stored.
279 typedef SmallVector<RelocationEntry, 64> RelocationList;
280 // Relocations to sections already loaded. Indexed by SectionID which is the
281 // source of the address. The target where the address will be written is
282 // SectionID/Offset in the relocation itself.
283 std::unordered_map<unsigned, RelocationList> Relocations;
285 // Relocations to external symbols that are not yet resolved. Symbols are
286 // external when they aren't found in the global symbol table of all loaded
287 // modules. This map is indexed by symbol name.
288 StringMap<RelocationList> ExternalSymbolRelocations;
291 typedef std::map<RelocationValueRef, uintptr_t> StubMap;
293 Triple::ArchType Arch;
294 bool IsTargetLittleEndian;
295 bool IsMipsO32ABI;
296 bool IsMipsN32ABI;
297 bool IsMipsN64ABI;
299 // True if all sections should be passed to the memory manager, false if only
300 // sections containing relocations should be. Defaults to 'false'.
301 bool ProcessAllSections;
303 // This mutex prevents simultaneously loading objects from two different
304 // threads. This keeps us from having to protect individual data structures
305 // and guarantees that section allocation requests to the memory manager
306 // won't be interleaved between modules. It is also used in mapSectionAddress
307 // and resolveRelocations to protect write access to internal data structures.
309 // loadObject may be called on the same thread during the handling of of
310 // processRelocations, and that's OK. The handling of the relocation lists
311 // is written in such a way as to work correctly if new elements are added to
312 // the end of the list while the list is being processed.
313 sys::Mutex lock;
315 virtual unsigned getMaxStubSize() = 0;
316 virtual unsigned getStubAlignment() = 0;
318 bool HasError;
319 std::string ErrorStr;
321 uint64_t getSectionLoadAddress(unsigned SectionID) const {
322 return Sections[SectionID].getLoadAddress();
325 uint8_t *getSectionAddress(unsigned SectionID) const {
326 return Sections[SectionID].getAddress();
329 void writeInt16BE(uint8_t *Addr, uint16_t Value) {
330 if (IsTargetLittleEndian)
331 sys::swapByteOrder(Value);
332 *Addr = (Value >> 8) & 0xFF;
333 *(Addr + 1) = Value & 0xFF;
336 void writeInt32BE(uint8_t *Addr, uint32_t Value) {
337 if (IsTargetLittleEndian)
338 sys::swapByteOrder(Value);
339 *Addr = (Value >> 24) & 0xFF;
340 *(Addr + 1) = (Value >> 16) & 0xFF;
341 *(Addr + 2) = (Value >> 8) & 0xFF;
342 *(Addr + 3) = Value & 0xFF;
345 void writeInt64BE(uint8_t *Addr, uint64_t Value) {
346 if (IsTargetLittleEndian)
347 sys::swapByteOrder(Value);
348 *Addr = (Value >> 56) & 0xFF;
349 *(Addr + 1) = (Value >> 48) & 0xFF;
350 *(Addr + 2) = (Value >> 40) & 0xFF;
351 *(Addr + 3) = (Value >> 32) & 0xFF;
352 *(Addr + 4) = (Value >> 24) & 0xFF;
353 *(Addr + 5) = (Value >> 16) & 0xFF;
354 *(Addr + 6) = (Value >> 8) & 0xFF;
355 *(Addr + 7) = Value & 0xFF;
358 virtual void setMipsABI(const ObjectFile &Obj) {
359 IsMipsO32ABI = false;
360 IsMipsN32ABI = false;
361 IsMipsN64ABI = false;
364 /// Endian-aware read Read the least significant Size bytes from Src.
365 uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const;
367 /// Endian-aware write. Write the least significant Size bytes from Value to
368 /// Dst.
369 void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const;
371 /// Generate JITSymbolFlags from a libObject symbol.
372 virtual Expected<JITSymbolFlags> getJITSymbolFlags(const SymbolRef &Sym);
374 /// Modify the given target address based on the given symbol flags.
375 /// This can be used by subclasses to tweak addresses based on symbol flags,
376 /// For example: the MachO/ARM target uses it to set the low bit if the target
377 /// is a thumb symbol.
378 virtual uint64_t modifyAddressBasedOnFlags(uint64_t Addr,
379 JITSymbolFlags Flags) const {
380 return Addr;
383 /// Given the common symbols discovered in the object file, emit a
384 /// new section for them and update the symbol mappings in the object and
385 /// symbol table.
386 Error emitCommonSymbols(const ObjectFile &Obj,
387 CommonSymbolList &CommonSymbols, uint64_t CommonSize,
388 uint32_t CommonAlign);
390 /// Emits section data from the object file to the MemoryManager.
391 /// \param IsCode if it's true then allocateCodeSection() will be
392 /// used for emits, else allocateDataSection() will be used.
393 /// \return SectionID.
394 Expected<unsigned> emitSection(const ObjectFile &Obj,
395 const SectionRef &Section,
396 bool IsCode);
398 /// Find Section in LocalSections. If the secton is not found - emit
399 /// it and store in LocalSections.
400 /// \param IsCode if it's true then allocateCodeSection() will be
401 /// used for emmits, else allocateDataSection() will be used.
402 /// \return SectionID.
403 Expected<unsigned> findOrEmitSection(const ObjectFile &Obj,
404 const SectionRef &Section, bool IsCode,
405 ObjSectionToIDMap &LocalSections);
407 // Add a relocation entry that uses the given section.
408 void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID);
410 // Add a relocation entry that uses the given symbol. This symbol may
411 // be found in the global symbol table, or it may be external.
412 void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName);
414 /// Emits long jump instruction to Addr.
415 /// \return Pointer to the memory area for emitting target address.
416 uint8_t *createStubFunction(uint8_t *Addr, unsigned AbiVariant = 0);
418 /// Resolves relocations from Relocs list with address from Value.
419 void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
421 /// A object file specific relocation resolver
422 /// \param RE The relocation to be resolved
423 /// \param Value Target symbol address to apply the relocation action
424 virtual void resolveRelocation(const RelocationEntry &RE, uint64_t Value) = 0;
426 /// Parses one or more object file relocations (some object files use
427 /// relocation pairs) and stores it to Relocations or SymbolRelocations
428 /// (this depends on the object file type).
429 /// \return Iterator to the next relocation that needs to be parsed.
430 virtual Expected<relocation_iterator>
431 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
432 const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID,
433 StubMap &Stubs) = 0;
435 void applyExternalSymbolRelocations(
436 const StringMap<JITEvaluatedSymbol> ExternalSymbolMap);
438 /// Resolve relocations to external symbols.
439 Error resolveExternalSymbols();
441 // Compute an upper bound of the memory that is required to load all
442 // sections
443 Error computeTotalAllocSize(const ObjectFile &Obj,
444 uint64_t &CodeSize, uint32_t &CodeAlign,
445 uint64_t &RODataSize, uint32_t &RODataAlign,
446 uint64_t &RWDataSize, uint32_t &RWDataAlign);
448 // Compute GOT size
449 unsigned computeGOTSize(const ObjectFile &Obj);
451 // Compute the stub buffer size required for a section
452 unsigned computeSectionStubBufSize(const ObjectFile &Obj,
453 const SectionRef &Section);
455 // Implementation of the generic part of the loadObject algorithm.
456 Expected<ObjSectionToIDMap> loadObjectImpl(const object::ObjectFile &Obj);
458 // Return size of Global Offset Table (GOT) entry
459 virtual size_t getGOTEntrySize() { return 0; }
461 // Return true if the relocation R may require allocating a GOT entry.
462 virtual bool relocationNeedsGot(const RelocationRef &R) const {
463 return false;
466 // Return true if the relocation R may require allocating a stub.
467 virtual bool relocationNeedsStub(const RelocationRef &R) const {
468 return true; // Conservative answer
471 public:
472 RuntimeDyldImpl(RuntimeDyld::MemoryManager &MemMgr,
473 JITSymbolResolver &Resolver)
474 : MemMgr(MemMgr), Resolver(Resolver), Checker(nullptr),
475 ProcessAllSections(false), HasError(false) {
478 virtual ~RuntimeDyldImpl();
480 void setProcessAllSections(bool ProcessAllSections) {
481 this->ProcessAllSections = ProcessAllSections;
484 void setRuntimeDyldChecker(RuntimeDyldCheckerImpl *Checker) {
485 this->Checker = Checker;
488 virtual std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
489 loadObject(const object::ObjectFile &Obj) = 0;
491 uint8_t* getSymbolLocalAddress(StringRef Name) const {
492 // FIXME: Just look up as a function for now. Overly simple of course.
493 // Work in progress.
494 RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
495 if (pos == GlobalSymbolTable.end())
496 return nullptr;
497 const auto &SymInfo = pos->second;
498 // Absolute symbols do not have a local address.
499 if (SymInfo.getSectionID() == AbsoluteSymbolSection)
500 return nullptr;
501 return getSectionAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
504 JITEvaluatedSymbol getSymbol(StringRef Name) const {
505 // FIXME: Just look up as a function for now. Overly simple of course.
506 // Work in progress.
507 RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
508 if (pos == GlobalSymbolTable.end())
509 return nullptr;
510 const auto &SymEntry = pos->second;
511 uint64_t SectionAddr = 0;
512 if (SymEntry.getSectionID() != AbsoluteSymbolSection)
513 SectionAddr = getSectionLoadAddress(SymEntry.getSectionID());
514 uint64_t TargetAddr = SectionAddr + SymEntry.getOffset();
516 // FIXME: Have getSymbol should return the actual address and the client
517 // modify it based on the flags. This will require clients to be
518 // aware of the target architecture, which we should build
519 // infrastructure for.
520 TargetAddr = modifyAddressBasedOnFlags(TargetAddr, SymEntry.getFlags());
521 return JITEvaluatedSymbol(TargetAddr, SymEntry.getFlags());
524 std::map<StringRef, JITEvaluatedSymbol> getSymbolTable() const {
525 std::map<StringRef, JITEvaluatedSymbol> Result;
527 for (auto &KV : GlobalSymbolTable) {
528 auto SectionID = KV.second.getSectionID();
529 uint64_t SectionAddr = 0;
530 if (SectionID != AbsoluteSymbolSection)
531 SectionAddr = getSectionLoadAddress(SectionID);
532 Result[KV.first()] =
533 JITEvaluatedSymbol(SectionAddr + KV.second.getOffset(), KV.second.getFlags());
536 return Result;
539 void resolveRelocations();
541 void resolveLocalRelocations();
543 static void finalizeAsync(std::unique_ptr<RuntimeDyldImpl> This,
544 std::function<void(Error)> OnEmitted,
545 std::unique_ptr<MemoryBuffer> UnderlyingBuffer);
547 void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
549 void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
551 // Is the linker in an error state?
552 bool hasError() { return HasError; }
554 // Mark the error condition as handled and continue.
555 void clearError() { HasError = false; }
557 // Get the error message.
558 StringRef getErrorString() { return ErrorStr; }
560 virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
562 virtual void registerEHFrames();
564 void deregisterEHFrames();
566 virtual Error finalizeLoad(const ObjectFile &ObjImg,
567 ObjSectionToIDMap &SectionMap) {
568 return Error::success();
572 } // end namespace llvm
574 #endif