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/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>
32 
33 using namespace llvm;
34 using namespace llvm::object;
35 
36 namespace llvm {
37 
38 class Twine;
39 
40 #define UNIMPLEMENTED_RELOC(RelType) \
41   case RelType: \
42     return make_error<RuntimeDyldError>("Unimplemented relocation: " #RelType)
43 
44 /// SectionEntry - represents a section emitted into memory by the dynamic
45 /// linker.
46 class SectionEntry {
47   /// Name - section name.
48   std::string Name;
49 
50   /// Address - address in the linker's memory where the section resides.
51   uint8_t *Address;
52 
53   /// Size - section size. Doesn't include the stubs.
54   size_t Size;
55 
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;
61 
62   /// StubOffset - used for architectures with stub functions for far
63   /// relocations (like ARM).
64   uintptr_t StubOffset;
65 
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;
69 
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;
73 
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;
83   }
84 
85   StringRef getName() const { return Name; }
86 
87   uint8_t *getAddress() const { return Address; }
88 
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;
93   }
94 
95   size_t getSize() const { return Size; }
96 
97   uint64_t getLoadAddress() const { return LoadAddress; }
98   void setLoadAddress(uint64_t LA) { LoadAddress = LA; }
99 
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;
104   }
105 
106   uintptr_t getStubOffset() const { return StubOffset; }
107 
108   void advanceStubOffset(unsigned StubSize) {
109     StubOffset += StubSize;
110     assert(StubOffset <= AllocationSize && "Not enough space allocated!");
111   }
112 
113   uintptr_t getObjAddress() const { return ObjAddress; }
114 };
115 
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;
122 
123   /// Offset - offset into the section.
124   uint64_t Offset;
125 
126   /// RelType - relocation type.
127   uint32_t RelType;
128 
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;
132 
133   struct SectionPair {
134       uint32_t SectionA;
135       uint32_t SectionB;
136   };
137 
138   /// SymOffset - Section offset of the relocation entry's symbol (used for GOT
139   /// lookup).
140   union {
141     uint64_t SymOffset;
142     SectionPair Sections;
143   };
144 
145   /// True if this is a PCRel relocation (MachO specific).
146   bool IsPCRel;
147 
148   /// The size of this relocation (MachO specific).
149   unsigned Size;
150 
151   // ARM (MachO and COFF) specific.
152   bool IsTargetThumbFunc = false;
153 
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) {}
157 
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) {}
163 
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) {}
168 
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;
177   }
178 
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;
188   }
189 };
190 
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) {}
200 
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;
205   }
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;
216   }
217 };
218 
219 /// Symbol info for RuntimeDyld.
220 class SymbolTableEntry {
221 public:
222   SymbolTableEntry() = default;
223 
224   SymbolTableEntry(unsigned SectionID, uint64_t Offset, JITSymbolFlags Flags)
225       : Offset(Offset), SectionID(SectionID), Flags(Flags) {}
226 
227   unsigned getSectionID() const { return SectionID; }
228   uint64_t getOffset() const { return Offset; }
229   void setOffset(uint64_t NewOffset) { Offset = NewOffset; }
230 
231   JITSymbolFlags getFlags() const { return Flags; }
232 
233 private:
234   uint64_t Offset = 0;
235   unsigned SectionID = 0;
236   JITSymbolFlags Flags = JITSymbolFlags::None;
237 };
238 
239 typedef StringMap<SymbolTableEntry> RTDyldSymbolTable;
240 
241 class RuntimeDyldImpl {
242   friend class RuntimeDyld::LoadedObjectInfo;
243 protected:
244   static const unsigned AbsoluteSymbolSection = ~0U;
245 
246   // The MemoryManager to load objects into.
247   RuntimeDyld::MemoryManager &MemMgr;
248 
249   // The symbol resolver to use for external symbols.
250   JITSymbolResolver &Resolver;
251 
252   // A list of all sections emitted by the dynamic linker.  These sections are
253   // referenced in the code by means of their index in this list - SectionID.
254   typedef SmallVector<SectionEntry, 64> SectionList;
255   SectionList Sections;
256 
257   typedef unsigned SID; // Type for SectionIDs
258 #define RTDYLD_INVALID_SECTION_ID ((RuntimeDyldImpl::SID)(-1))
259 
260   // Keep a map of sections from object file to the SectionID which
261   // references it.
262   typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
263 
264   // A global symbol table for symbols from all loaded modules.
265   RTDyldSymbolTable GlobalSymbolTable;
266 
267   // Keep a map of common symbols to their info pairs
268   typedef std::vector<SymbolRef> CommonSymbolList;
269 
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;
280 
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;
285 
286 
287   typedef std::map<RelocationValueRef, uintptr_t> StubMap;
288 
289   Triple::ArchType Arch;
290   bool IsTargetLittleEndian;
291   bool IsMipsO32ABI;
292   bool IsMipsN32ABI;
293   bool IsMipsN64ABI;
294 
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;
298 
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.
304   //
305   // loadObject may be called on the same thread during the handling of 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;
310 
311   using NotifyStubEmittedFunction =
312     RuntimeDyld::NotifyStubEmittedFunction;
313   NotifyStubEmittedFunction NotifyStubEmitted;
314 
315   virtual unsigned getMaxStubSize() const = 0;
316   virtual unsigned getStubAlignment() = 0;
317 
318   bool HasError;
319   std::string ErrorStr;
320 
321   void writeInt16BE(uint8_t *Addr, uint16_t Value) {
322     if (IsTargetLittleEndian)
323       sys::swapByteOrder(Value);
324     *Addr       = (Value >> 8) & 0xFF;
325     *(Addr + 1) = Value & 0xFF;
326   }
327 
328   void writeInt32BE(uint8_t *Addr, uint32_t Value) {
329     if (IsTargetLittleEndian)
330       sys::swapByteOrder(Value);
331     *Addr       = (Value >> 24) & 0xFF;
332     *(Addr + 1) = (Value >> 16) & 0xFF;
333     *(Addr + 2) = (Value >> 8) & 0xFF;
334     *(Addr + 3) = Value & 0xFF;
335   }
336 
337   void writeInt64BE(uint8_t *Addr, uint64_t Value) {
338     if (IsTargetLittleEndian)
339       sys::swapByteOrder(Value);
340     *Addr       = (Value >> 56) & 0xFF;
341     *(Addr + 1) = (Value >> 48) & 0xFF;
342     *(Addr + 2) = (Value >> 40) & 0xFF;
343     *(Addr + 3) = (Value >> 32) & 0xFF;
344     *(Addr + 4) = (Value >> 24) & 0xFF;
345     *(Addr + 5) = (Value >> 16) & 0xFF;
346     *(Addr + 6) = (Value >> 8) & 0xFF;
347     *(Addr + 7) = Value & 0xFF;
348   }
349 
350   virtual void setMipsABI(const ObjectFile &Obj) {
351     IsMipsO32ABI = false;
352     IsMipsN32ABI = false;
353     IsMipsN64ABI = false;
354   }
355 
356   /// Endian-aware read Read the least significant Size bytes from Src.
357   uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const;
358 
359   /// Endian-aware write. Write the least significant Size bytes from Value to
360   /// Dst.
361   void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const;
362 
363   /// Generate JITSymbolFlags from a libObject symbol.
364   virtual Expected<JITSymbolFlags> getJITSymbolFlags(const SymbolRef &Sym);
365 
366   /// Modify the given target address based on the given symbol flags.
367   /// This can be used by subclasses to tweak addresses based on symbol flags,
368   /// For example: the MachO/ARM target uses it to set the low bit if the target
369   /// is a thumb symbol.
370   virtual uint64_t modifyAddressBasedOnFlags(uint64_t Addr,
371                                              JITSymbolFlags Flags) const {
372     return Addr;
373   }
374 
375   /// Given the common symbols discovered in the object file, emit a
376   /// new section for them and update the symbol mappings in the object and
377   /// symbol table.
378   Error emitCommonSymbols(const ObjectFile &Obj,
379                           CommonSymbolList &CommonSymbols, uint64_t CommonSize,
380                           uint32_t CommonAlign);
381 
382   /// Emits section data from the object file to the MemoryManager.
383   /// \param IsCode if it's true then allocateCodeSection() will be
384   ///        used for emits, else allocateDataSection() will be used.
385   /// \return SectionID.
386   Expected<unsigned> emitSection(const ObjectFile &Obj,
387                                  const SectionRef &Section,
388                                  bool IsCode);
389 
390   /// Find Section in LocalSections. If the secton is not found - emit
391   ///        it and store in LocalSections.
392   /// \param IsCode if it's true then allocateCodeSection() will be
393   ///        used for emmits, else allocateDataSection() will be used.
394   /// \return SectionID.
395   Expected<unsigned> findOrEmitSection(const ObjectFile &Obj,
396                                        const SectionRef &Section, bool IsCode,
397                                        ObjSectionToIDMap &LocalSections);
398 
399   // Add a relocation entry that uses the given section.
400   void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID);
401 
402   // Add a relocation entry that uses the given symbol.  This symbol may
403   // be found in the global symbol table, or it may be external.
404   void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName);
405 
406   /// Emits long jump instruction to Addr.
407   /// \return Pointer to the memory area for emitting target address.
408   uint8_t *createStubFunction(uint8_t *Addr, unsigned AbiVariant = 0);
409 
410   /// Resolves relocations from Relocs list with address from Value.
411   void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
412 
413   /// A object file specific relocation resolver
414   /// \param RE The relocation to be resolved
415   /// \param Value Target symbol address to apply the relocation action
416   virtual void resolveRelocation(const RelocationEntry &RE, uint64_t Value) = 0;
417 
418   /// Parses one or more object file relocations (some object files use
419   ///        relocation pairs) and stores it to Relocations or SymbolRelocations
420   ///        (this depends on the object file type).
421   /// \return Iterator to the next relocation that needs to be parsed.
422   virtual Expected<relocation_iterator>
423   processRelocationRef(unsigned SectionID, relocation_iterator RelI,
424                        const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID,
425                        StubMap &Stubs) = 0;
426 
427   void applyExternalSymbolRelocations(
428       const StringMap<JITEvaluatedSymbol> ExternalSymbolMap);
429 
430   /// Resolve relocations to external symbols.
431   Error resolveExternalSymbols();
432 
433   // Compute an upper bound of the memory that is required to load all
434   // sections
435   Error computeTotalAllocSize(const ObjectFile &Obj,
436                               uint64_t &CodeSize, uint32_t &CodeAlign,
437                               uint64_t &RODataSize, uint32_t &RODataAlign,
438                               uint64_t &RWDataSize, uint32_t &RWDataAlign);
439 
440   // Compute GOT size
441   unsigned computeGOTSize(const ObjectFile &Obj);
442 
443   // Compute the stub buffer size required for a section
444   unsigned computeSectionStubBufSize(const ObjectFile &Obj,
445                                      const SectionRef &Section);
446 
447   // Implementation of the generic part of the loadObject algorithm.
448   Expected<ObjSectionToIDMap> loadObjectImpl(const object::ObjectFile &Obj);
449 
450   // Return size of Global Offset Table (GOT) entry
451   virtual size_t getGOTEntrySize() { return 0; }
452 
453   // Return true if the relocation R may require allocating a GOT entry.
454   virtual bool relocationNeedsGot(const RelocationRef &R) const {
455     return false;
456   }
457 
458   // Return true if the relocation R may require allocating a stub.
459   virtual bool relocationNeedsStub(const RelocationRef &R) const {
460     return true;    // Conservative answer
461   }
462 
463 public:
464   RuntimeDyldImpl(RuntimeDyld::MemoryManager &MemMgr,
465                   JITSymbolResolver &Resolver)
466     : MemMgr(MemMgr), Resolver(Resolver),
467       ProcessAllSections(false), HasError(false) {
468   }
469 
470   virtual ~RuntimeDyldImpl();
471 
472   void setProcessAllSections(bool ProcessAllSections) {
473     this->ProcessAllSections = ProcessAllSections;
474   }
475 
476   virtual std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
477   loadObject(const object::ObjectFile &Obj) = 0;
478 
479   uint64_t getSectionLoadAddress(unsigned SectionID) const {
480     return Sections[SectionID].getLoadAddress();
481   }
482 
483   uint8_t *getSectionAddress(unsigned SectionID) const {
484     return Sections[SectionID].getAddress();
485   }
486 
487   StringRef getSectionContent(unsigned SectionID) const {
488     return StringRef(reinterpret_cast<char *>(Sections[SectionID].getAddress()),
489                      Sections[SectionID].getStubOffset() + getMaxStubSize());
490   }
491 
492   uint8_t* getSymbolLocalAddress(StringRef Name) const {
493     // FIXME: Just look up as a function for now. Overly simple of course.
494     // Work in progress.
495     RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
496     if (pos == GlobalSymbolTable.end())
497       return nullptr;
498     const auto &SymInfo = pos->second;
499     // Absolute symbols do not have a local address.
500     if (SymInfo.getSectionID() == AbsoluteSymbolSection)
501       return nullptr;
502     return getSectionAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
503   }
504 
505   unsigned getSymbolSectionID(StringRef Name) const {
506     auto GSTItr = GlobalSymbolTable.find(Name);
507     if (GSTItr == GlobalSymbolTable.end())
508       return ~0U;
509     return GSTItr->second.getSectionID();
510   }
511 
512   JITEvaluatedSymbol getSymbol(StringRef Name) const {
513     // FIXME: Just look up as a function for now. Overly simple of course.
514     // Work in progress.
515     RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
516     if (pos == GlobalSymbolTable.end())
517       return nullptr;
518     const auto &SymEntry = pos->second;
519     uint64_t SectionAddr = 0;
520     if (SymEntry.getSectionID() != AbsoluteSymbolSection)
521       SectionAddr = getSectionLoadAddress(SymEntry.getSectionID());
522     uint64_t TargetAddr = SectionAddr + SymEntry.getOffset();
523 
524     // FIXME: Have getSymbol should return the actual address and the client
525     //        modify it based on the flags. This will require clients to be
526     //        aware of the target architecture, which we should build
527     //        infrastructure for.
528     TargetAddr = modifyAddressBasedOnFlags(TargetAddr, SymEntry.getFlags());
529     return JITEvaluatedSymbol(TargetAddr, SymEntry.getFlags());
530   }
531 
532   std::map<StringRef, JITEvaluatedSymbol> getSymbolTable() const {
533     std::map<StringRef, JITEvaluatedSymbol> Result;
534 
535     for (auto &KV : GlobalSymbolTable) {
536       auto SectionID = KV.second.getSectionID();
537       uint64_t SectionAddr = 0;
538       if (SectionID != AbsoluteSymbolSection)
539         SectionAddr = getSectionLoadAddress(SectionID);
540       Result[KV.first()] =
541         JITEvaluatedSymbol(SectionAddr + KV.second.getOffset(), KV.second.getFlags());
542     }
543 
544     return Result;
545   }
546 
547   void resolveRelocations();
548 
549   void resolveLocalRelocations();
550 
551   static void finalizeAsync(std::unique_ptr<RuntimeDyldImpl> This,
552                             unique_function<void(Error)> OnEmitted,
553                             std::unique_ptr<MemoryBuffer> UnderlyingBuffer);
554 
555   void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
556 
557   void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
558 
559   // Is the linker in an error state?
560   bool hasError() { return HasError; }
561 
562   // Mark the error condition as handled and continue.
563   void clearError() { HasError = false; }
564 
565   // Get the error message.
566   StringRef getErrorString() { return ErrorStr; }
567 
568   virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
569 
570   void setNotifyStubEmitted(NotifyStubEmittedFunction NotifyStubEmitted) {
571     this->NotifyStubEmitted = std::move(NotifyStubEmitted);
572   }
573 
574   virtual void registerEHFrames();
575 
576   void deregisterEHFrames();
577 
578   virtual Error finalizeLoad(const ObjectFile &ObjImg,
579                              ObjSectionToIDMap &SectionMap) {
580     return Error::success();
581   }
582 };
583 
584 } // end namespace llvm
585 
586 #endif
587