[clang-tidy][use-internal-linkage] fix false positive for consteval function (#122141)
[llvm-project.git] / llvm / lib / ExecutionEngine / RuntimeDyld / RuntimeDyldImpl.h
blob24b03a058981a0533ebf8f7b6a6d9223eed43402
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/ExecutionEngine/Orc/SymbolStringPool.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/Mutex.h"
27 #include "llvm/Support/SwapByteOrder.h"
28 #include "llvm/TargetParser/Host.h"
29 #include "llvm/TargetParser/Triple.h"
30 #include <deque>
31 #include <map>
32 #include <system_error>
33 #include <unordered_map>
35 using namespace llvm;
36 using namespace llvm::object;
38 namespace llvm {
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(std::string(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 /// Offset - offset into the section.
121 uint64_t Offset;
123 /// Addend - the relocation addend encoded in the instruction itself. Also
124 /// used to make a relocation section relative instead of symbol relative.
125 int64_t Addend;
127 /// SectionID - the section this relocation points to.
128 unsigned SectionID;
130 /// RelType - relocation type.
131 uint32_t RelType;
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 /// The size of this relocation (MachO specific).
146 unsigned Size;
148 /// True if this is a PCRel relocation (MachO specific).
149 bool IsPCRel : 1;
151 // ARM (MachO and COFF) specific.
152 bool IsTargetThumbFunc : 1;
154 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend)
155 : Offset(offset), Addend(addend), SectionID(id), RelType(type),
156 SymOffset(0), Size(0), IsPCRel(false), IsTargetThumbFunc(false) {}
158 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
159 uint64_t symoffset)
160 : Offset(offset), Addend(addend), SectionID(id), RelType(type),
161 SymOffset(symoffset), Size(0), IsPCRel(false),
162 IsTargetThumbFunc(false) {}
164 RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
165 bool IsPCRel, unsigned Size)
166 : Offset(offset), Addend(addend), SectionID(id), RelType(type),
167 SymOffset(0), Size(Size), IsPCRel(IsPCRel), 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 : Offset(offset), Addend(SectionAOffset - SectionBOffset + addend),
173 SectionID(id), RelType(type), Size(Size), IsPCRel(IsPCRel),
174 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 : Offset(offset), Addend(SectionAOffset - SectionBOffset + addend),
184 SectionID(id), RelType(type), Size(Size), IsPCRel(IsPCRel),
185 IsTargetThumbFunc(IsTargetThumbFunc) {
186 Sections.SectionA = SectionA;
187 Sections.SectionB = SectionB;
191 class RelocationValueRef {
192 public:
193 unsigned SectionID = 0;
194 uint64_t Offset = 0;
195 int64_t Addend = 0;
196 const char *SymbolName = nullptr;
197 bool IsStubThumb = false;
199 inline bool operator==(const RelocationValueRef &Other) const {
200 return SectionID == Other.SectionID && Offset == Other.Offset &&
201 Addend == Other.Addend && SymbolName == Other.SymbolName &&
202 IsStubThumb == Other.IsStubThumb;
204 inline bool operator<(const RelocationValueRef &Other) const {
205 if (SectionID != Other.SectionID)
206 return SectionID < Other.SectionID;
207 if (Offset != Other.Offset)
208 return Offset < Other.Offset;
209 if (Addend != Other.Addend)
210 return Addend < Other.Addend;
211 if (IsStubThumb != Other.IsStubThumb)
212 return IsStubThumb < Other.IsStubThumb;
213 return SymbolName < Other.SymbolName;
217 /// Symbol info for RuntimeDyld.
218 class SymbolTableEntry {
219 public:
220 SymbolTableEntry() = default;
222 SymbolTableEntry(unsigned SectionID, uint64_t Offset, JITSymbolFlags Flags)
223 : Offset(Offset), SectionID(SectionID), Flags(Flags) {}
225 unsigned getSectionID() const { return SectionID; }
226 uint64_t getOffset() const { return Offset; }
227 void setOffset(uint64_t NewOffset) { Offset = NewOffset; }
229 JITSymbolFlags getFlags() const { return Flags; }
231 private:
232 uint64_t Offset = 0;
233 unsigned SectionID = 0;
234 JITSymbolFlags Flags = JITSymbolFlags::None;
237 typedef StringMap<SymbolTableEntry> RTDyldSymbolTable;
239 class RuntimeDyldImpl {
240 friend class RuntimeDyld::LoadedObjectInfo;
241 protected:
242 static const unsigned AbsoluteSymbolSection = ~0U;
244 // The MemoryManager to load objects into.
245 RuntimeDyld::MemoryManager &MemMgr;
247 // The symbol resolver to use for external symbols.
248 JITSymbolResolver &Resolver;
250 // A list of all sections emitted by the dynamic linker. These sections are
251 // referenced in the code by means of their index in this list - SectionID.
252 // Because references may be kept while the list grows, use a container that
253 // guarantees reference stability.
254 typedef std::deque<SectionEntry> SectionList;
255 SectionList Sections;
257 typedef unsigned SID; // Type for SectionIDs
258 #define RTDYLD_INVALID_SECTION_ID ((RuntimeDyldImpl::SID)(-1))
260 // Keep a map of sections from object file to the SectionID which
261 // references it.
262 typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
264 // A global symbol table for symbols from all loaded modules.
265 RTDyldSymbolTable GlobalSymbolTable;
267 // Keep a map of common symbols to their info pairs
268 typedef std::vector<SymbolRef> CommonSymbolList;
270 // For each symbol, keep a list of relocations based on it. Anytime
271 // its address is reassigned (the JIT re-compiled the function, e.g.),
272 // the relocations get re-resolved.
273 // The symbol (or section) the relocation is sourced from is the Key
274 // in the relocation list where it's stored.
275 typedef SmallVector<RelocationEntry, 64> RelocationList;
276 // Relocations to sections already loaded. Indexed by SectionID which is the
277 // source of the address. The target where the address will be written is
278 // SectionID/Offset in the relocation itself.
279 std::unordered_map<unsigned, RelocationList> Relocations;
281 // Relocations to external symbols that are not yet resolved. Symbols are
282 // external when they aren't found in the global symbol table of all loaded
283 // modules. This map is indexed by symbol name.
284 StringMap<RelocationList> ExternalSymbolRelocations;
287 typedef std::map<RelocationValueRef, uintptr_t> StubMap;
289 Triple::ArchType Arch;
290 bool IsTargetLittleEndian;
291 bool IsMipsO32ABI;
292 bool IsMipsN32ABI;
293 bool IsMipsN64ABI;
295 // True if all sections should be passed to the memory manager, false if only
296 // sections containing relocations should be. Defaults to 'false'.
297 bool ProcessAllSections;
299 // This mutex prevents simultaneously loading objects from two different
300 // threads. This keeps us from having to protect individual data structures
301 // and guarantees that section allocation requests to the memory manager
302 // won't be interleaved between modules. It is also used in mapSectionAddress
303 // and resolveRelocations to protect write access to internal data structures.
305 // loadObject may be called on the same thread during the handling of
306 // processRelocations, and that's OK. The handling of the relocation lists
307 // is written in such a way as to work correctly if new elements are added to
308 // the end of the list while the list is being processed.
309 sys::Mutex lock;
311 using NotifyStubEmittedFunction =
312 RuntimeDyld::NotifyStubEmittedFunction;
313 NotifyStubEmittedFunction NotifyStubEmitted;
315 virtual unsigned getMaxStubSize() const = 0;
316 virtual Align getStubAlignment() = 0;
318 bool HasError;
319 std::string ErrorStr;
321 void writeInt16BE(uint8_t *Addr, uint16_t Value) {
322 llvm::support::endian::write<uint16_t>(Addr, Value,
323 IsTargetLittleEndian
324 ? llvm::endianness::little
325 : llvm::endianness::big);
328 void writeInt32BE(uint8_t *Addr, uint32_t Value) {
329 llvm::support::endian::write<uint32_t>(Addr, Value,
330 IsTargetLittleEndian
331 ? llvm::endianness::little
332 : llvm::endianness::big);
335 void writeInt64BE(uint8_t *Addr, uint64_t Value) {
336 llvm::support::endian::write<uint64_t>(Addr, Value,
337 IsTargetLittleEndian
338 ? llvm::endianness::little
339 : llvm::endianness::big);
342 virtual void setMipsABI(const ObjectFile &Obj) {
343 IsMipsO32ABI = false;
344 IsMipsN32ABI = false;
345 IsMipsN64ABI = false;
348 /// Endian-aware read Read the least significant Size bytes from Src.
349 uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const;
351 /// Endian-aware write. Write the least significant Size bytes from Value to
352 /// Dst.
353 void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const;
355 /// Generate JITSymbolFlags from a libObject symbol.
356 virtual Expected<JITSymbolFlags> getJITSymbolFlags(const SymbolRef &Sym);
358 /// Modify the given target address based on the given symbol flags.
359 /// This can be used by subclasses to tweak addresses based on symbol flags,
360 /// For example: the MachO/ARM target uses it to set the low bit if the target
361 /// is a thumb symbol.
362 virtual uint64_t modifyAddressBasedOnFlags(uint64_t Addr,
363 JITSymbolFlags Flags) const {
364 return Addr;
367 /// Given the common symbols discovered in the object file, emit a
368 /// new section for them and update the symbol mappings in the object and
369 /// symbol table.
370 Error emitCommonSymbols(const ObjectFile &Obj,
371 CommonSymbolList &CommonSymbols, uint64_t CommonSize,
372 uint32_t CommonAlign);
374 /// Emits section data from the object file to the MemoryManager.
375 /// \param IsCode if it's true then allocateCodeSection() will be
376 /// used for emits, else allocateDataSection() will be used.
377 /// \return SectionID.
378 Expected<unsigned> emitSection(const ObjectFile &Obj,
379 const SectionRef &Section,
380 bool IsCode);
382 /// Find Section in LocalSections. If the secton is not found - emit
383 /// it and store in LocalSections.
384 /// \param IsCode if it's true then allocateCodeSection() will be
385 /// used for emmits, else allocateDataSection() will be used.
386 /// \return SectionID.
387 Expected<unsigned> findOrEmitSection(const ObjectFile &Obj,
388 const SectionRef &Section, bool IsCode,
389 ObjSectionToIDMap &LocalSections);
391 // Add a relocation entry that uses the given section.
392 void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID);
394 // Add a relocation entry that uses the given symbol. This symbol may
395 // be found in the global symbol table, or it may be external.
396 void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName);
398 /// Emits long jump instruction to Addr.
399 /// \return Pointer to the memory area for emitting target address.
400 uint8_t *createStubFunction(uint8_t *Addr, unsigned AbiVariant = 0);
402 /// Resolves relocations from Relocs list with address from Value.
403 void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
405 /// A object file specific relocation resolver
406 /// \param RE The relocation to be resolved
407 /// \param Value Target symbol address to apply the relocation action
408 virtual void resolveRelocation(const RelocationEntry &RE, uint64_t Value) = 0;
410 /// Parses one or more object file relocations (some object files use
411 /// relocation pairs) and stores it to Relocations or SymbolRelocations
412 /// (this depends on the object file type).
413 /// \return Iterator to the next relocation that needs to be parsed.
414 virtual Expected<relocation_iterator>
415 processRelocationRef(unsigned SectionID, relocation_iterator RelI,
416 const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID,
417 StubMap &Stubs) = 0;
419 void applyExternalSymbolRelocations(
420 const StringMap<JITEvaluatedSymbol> ExternalSymbolMap);
422 /// Resolve relocations to external symbols.
423 Error resolveExternalSymbols();
425 // Compute an upper bound of the memory that is required to load all
426 // sections
427 Error computeTotalAllocSize(const ObjectFile &Obj, uint64_t &CodeSize,
428 Align &CodeAlign, uint64_t &RODataSize,
429 Align &RODataAlign, uint64_t &RWDataSize,
430 Align &RWDataAlign);
432 // Compute GOT size
433 unsigned computeGOTSize(const ObjectFile &Obj);
435 // Compute the stub buffer size required for a section
436 unsigned computeSectionStubBufSize(const ObjectFile &Obj,
437 const SectionRef &Section);
439 // Implementation of the generic part of the loadObject algorithm.
440 Expected<ObjSectionToIDMap> loadObjectImpl(const object::ObjectFile &Obj);
442 // Return size of Global Offset Table (GOT) entry
443 virtual size_t getGOTEntrySize() { return 0; }
445 // Hook for the subclasses to do further processing when a symbol is added to
446 // the global symbol table. This function may modify the symbol table entry.
447 virtual void processNewSymbol(const SymbolRef &ObjSymbol, SymbolTableEntry& Entry) {}
449 // Return true if the relocation R may require allocating a GOT entry.
450 virtual bool relocationNeedsGot(const RelocationRef &R) const {
451 return false;
454 // Return true if the relocation R may require allocating a stub.
455 virtual bool relocationNeedsStub(const RelocationRef &R) const {
456 return true; // Conservative answer
459 // Return true if the relocation R may require allocating a DLL import stub.
460 virtual bool relocationNeedsDLLImportStub(const RelocationRef &R) const {
461 return false;
464 // Add the size of a DLL import stub to the buffer size
465 virtual unsigned sizeAfterAddingDLLImportStub(unsigned Size) const {
466 return Size;
469 public:
470 RuntimeDyldImpl(RuntimeDyld::MemoryManager &MemMgr,
471 JITSymbolResolver &Resolver)
472 : MemMgr(MemMgr), Resolver(Resolver),
473 ProcessAllSections(false), HasError(false) {
476 virtual ~RuntimeDyldImpl();
478 void setProcessAllSections(bool ProcessAllSections) {
479 this->ProcessAllSections = ProcessAllSections;
482 virtual std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
483 loadObject(const object::ObjectFile &Obj) = 0;
485 uint64_t getSectionLoadAddress(unsigned SectionID) const {
486 if (SectionID == AbsoluteSymbolSection)
487 return 0;
488 else
489 return Sections[SectionID].getLoadAddress();
492 uint8_t *getSectionAddress(unsigned SectionID) const {
493 if (SectionID == AbsoluteSymbolSection)
494 return nullptr;
495 else
496 return Sections[SectionID].getAddress();
499 StringRef getSectionContent(unsigned SectionID) const {
500 if (SectionID == AbsoluteSymbolSection)
501 return {};
502 else
503 return StringRef(
504 reinterpret_cast<char *>(Sections[SectionID].getAddress()),
505 Sections[SectionID].getStubOffset() + getMaxStubSize());
508 uint8_t* getSymbolLocalAddress(StringRef Name) const {
509 // FIXME: Just look up as a function for now. Overly simple of course.
510 // Work in progress.
511 RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
512 if (pos == GlobalSymbolTable.end())
513 return nullptr;
514 const auto &SymInfo = pos->second;
515 // Absolute symbols do not have a local address.
516 if (SymInfo.getSectionID() == AbsoluteSymbolSection)
517 return nullptr;
518 return getSectionAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
521 unsigned getSymbolSectionID(StringRef Name) const {
522 auto GSTItr = GlobalSymbolTable.find(Name);
523 if (GSTItr == GlobalSymbolTable.end())
524 return ~0U;
525 return GSTItr->second.getSectionID();
528 JITEvaluatedSymbol getSymbol(StringRef Name) const {
529 // FIXME: Just look up as a function for now. Overly simple of course.
530 // Work in progress.
531 RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
532 if (pos == GlobalSymbolTable.end())
533 return nullptr;
534 const auto &SymEntry = pos->second;
535 uint64_t SectionAddr = 0;
536 if (SymEntry.getSectionID() != AbsoluteSymbolSection)
537 SectionAddr = getSectionLoadAddress(SymEntry.getSectionID());
538 uint64_t TargetAddr = SectionAddr + SymEntry.getOffset();
540 // FIXME: Have getSymbol should return the actual address and the client
541 // modify it based on the flags. This will require clients to be
542 // aware of the target architecture, which we should build
543 // infrastructure for.
544 TargetAddr = modifyAddressBasedOnFlags(TargetAddr, SymEntry.getFlags());
545 return JITEvaluatedSymbol(TargetAddr, SymEntry.getFlags());
548 std::map<StringRef, JITEvaluatedSymbol> getSymbolTable() const {
549 std::map<StringRef, JITEvaluatedSymbol> Result;
551 for (const auto &KV : GlobalSymbolTable) {
552 auto SectionID = KV.second.getSectionID();
553 uint64_t SectionAddr = getSectionLoadAddress(SectionID);
554 Result[KV.first()] =
555 JITEvaluatedSymbol(SectionAddr + KV.second.getOffset(), KV.second.getFlags());
558 return Result;
561 void resolveRelocations();
563 void resolveLocalRelocations();
565 static void finalizeAsync(
566 std::unique_ptr<RuntimeDyldImpl> This,
567 unique_function<void(object::OwningBinary<object::ObjectFile>,
568 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>,
569 Error)>
570 OnEmitted,
571 object::OwningBinary<object::ObjectFile> O,
572 std::unique_ptr<RuntimeDyld::LoadedObjectInfo> Info);
574 void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
576 void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
578 // Is the linker in an error state?
579 bool hasError() { return HasError; }
581 // Mark the error condition as handled and continue.
582 void clearError() { HasError = false; }
584 // Get the error message.
585 StringRef getErrorString() { return ErrorStr; }
587 virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
589 void setNotifyStubEmitted(NotifyStubEmittedFunction NotifyStubEmitted) {
590 this->NotifyStubEmitted = std::move(NotifyStubEmitted);
593 virtual void registerEHFrames();
595 void deregisterEHFrames();
597 virtual Error finalizeLoad(const ObjectFile &ObjImg,
598 ObjSectionToIDMap &SectionMap) {
599 return Error::success();
603 } // end namespace llvm
605 #endif