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