1 //===-- RuntimeDyldImpl.h - Run-time dynamic linker for MC-JIT --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Interface for the implementations of runtime dynamic linker facilities.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
15 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_RUNTIMEDYLDIMPL_H
16 
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
21 #include "llvm/ExecutionEngine/RuntimeDyld.h"
22 #include "llvm/ExecutionEngine/RuntimeDyldChecker.h"
23 #include "llvm/Object/ObjectFile.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/Host.h"
28 #include "llvm/Support/Mutex.h"
29 #include "llvm/Support/SwapByteOrder.h"
30 #include <map>
31 #include <unordered_map>
32 #include <system_error>
33 
34 using namespace llvm;
35 using namespace llvm::object;
36 
37 namespace llvm {
38 
39 class Twine;
40 
41 #define UNIMPLEMENTED_RELOC(RelType) \
42   case RelType: \
43     return make_error<RuntimeDyldError>("Unimplemented relocation: " #RelType)
44 
45 /// SectionEntry - represents a section emitted into memory by the dynamic
46 /// linker.
47 class SectionEntry {
48   /// Name - section name.
49   std::string Name;
50 
51   /// Address - address in the linker's memory where the section resides.
52   uint8_t *Address;
53 
54   /// Size - section size. Doesn't include the stubs.
55   size_t Size;
56 
57   /// LoadAddress - the address of the section in the target process's memory.
58   /// Used for situations in which JIT-ed code is being executed in the address
59   /// space of a separate process.  If the code executes in the same address
60   /// space where it was JIT-ed, this just equals Address.
61   uint64_t LoadAddress;
62 
63   /// StubOffset - used for architectures with stub functions for far
64   /// relocations (like ARM).
65   uintptr_t StubOffset;
66 
67   /// The total amount of space allocated for this section.  This includes the
68   /// section size and the maximum amount of space that the stubs can occupy.
69   size_t AllocationSize;
70 
71   /// ObjAddress - address of the section in the in-memory object file.  Used
72   /// for calculating relocations in some object formats (like MachO).
73   uintptr_t ObjAddress;
74 
75 public:
76   SectionEntry(StringRef name, uint8_t *address, size_t size,
77                size_t allocationSize, uintptr_t objAddress)
78       : Name(name), Address(address), Size(size),
79         LoadAddress(reinterpret_cast<uintptr_t>(address)), StubOffset(size),
80         AllocationSize(allocationSize), ObjAddress(objAddress) {
81     // AllocationSize is used only in asserts, prevent an "unused private field"
82     // warning:
83     (void)AllocationSize;
84   }
85 
86   StringRef getName() const { return Name; }
87 
88   uint8_t *getAddress() const { return Address; }
89 
90   /// \brief Return the address of this section with an offset.
91   uint8_t *getAddressWithOffset(unsigned OffsetBytes) const {
92     assert(OffsetBytes <= AllocationSize && "Offset out of bounds!");
93     return Address + OffsetBytes;
94   }
95 
96   size_t getSize() const { return Size; }
97 
98   uint64_t getLoadAddress() const { return LoadAddress; }
99   void setLoadAddress(uint64_t LA) { LoadAddress = LA; }
100 
101   /// \brief Return the load address of this section with an offset.
102   uint64_t getLoadAddressWithOffset(unsigned OffsetBytes) const {
103     assert(OffsetBytes <= AllocationSize && "Offset out of bounds!");
104     return LoadAddress + OffsetBytes;
105   }
106 
107   uintptr_t getStubOffset() const { return StubOffset; }
108 
109   void advanceStubOffset(unsigned StubSize) {
110     StubOffset += StubSize;
111     assert(StubOffset <= AllocationSize && "Not enough space allocated!");
112   }
113 
114   uintptr_t getObjAddress() const { return ObjAddress; }
115 };
116 
117 /// RelocationEntry - used to represent relocations internally in the dynamic
118 /// linker.
119 class RelocationEntry {
120 public:
121   /// SectionID - the section this relocation points to.
122   unsigned SectionID;
123 
124   /// Offset - offset into the section.
125   uint64_t Offset;
126 
127   /// RelType - relocation type.
128   uint32_t RelType;
129 
130   /// Addend - the relocation addend encoded in the instruction itself.  Also
131   /// used to make a relocation section relative instead of symbol relative.
132   int64_t Addend;
133 
134   struct SectionPair {
135       uint32_t SectionA;
136       uint32_t SectionB;
137   };
138 
139   /// SymOffset - Section offset of the relocation entry's symbol (used for GOT
140   /// lookup).
141   union {
142     uint64_t SymOffset;
143     SectionPair Sections;
144   };
145 
146   /// True if this is a PCRel relocation (MachO specific).
147   bool IsPCRel;
148 
149   /// The size of this relocation (MachO specific).
150   unsigned Size;
151 
152   // COFF specific.
153   bool IsTargetThumbFunc;
154 
155   RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend)
156       : SectionID(id), Offset(offset), RelType(type), Addend(addend),
157         SymOffset(0), IsPCRel(false), Size(0), IsTargetThumbFunc(false) {}
158 
159   RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
160                   uint64_t symoffset)
161       : SectionID(id), Offset(offset), RelType(type), Addend(addend),
162         SymOffset(symoffset), IsPCRel(false), Size(0),
163         IsTargetThumbFunc(false) {}
164 
165   RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
166                   bool IsPCRel, unsigned Size)
167       : SectionID(id), Offset(offset), RelType(type), Addend(addend),
168         SymOffset(0), IsPCRel(IsPCRel), Size(Size), IsTargetThumbFunc(false) {}
169 
170   RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
171                   unsigned SectionA, uint64_t SectionAOffset, unsigned SectionB,
172                   uint64_t SectionBOffset, bool IsPCRel, unsigned Size)
173       : SectionID(id), Offset(offset), RelType(type),
174         Addend(SectionAOffset - SectionBOffset + addend), IsPCRel(IsPCRel),
175         Size(Size), IsTargetThumbFunc(false) {
176     Sections.SectionA = SectionA;
177     Sections.SectionB = SectionB;
178   }
179 
180   RelocationEntry(unsigned id, uint64_t offset, uint32_t type, int64_t addend,
181                   unsigned SectionA, uint64_t SectionAOffset, unsigned SectionB,
182                   uint64_t SectionBOffset, bool IsPCRel, unsigned Size,
183                   bool IsTargetThumbFunc)
184       : SectionID(id), Offset(offset), RelType(type),
185         Addend(SectionAOffset - SectionBOffset + addend), IsPCRel(IsPCRel),
186         Size(Size), IsTargetThumbFunc(IsTargetThumbFunc) {
187     Sections.SectionA = SectionA;
188     Sections.SectionB = SectionB;
189   }
190 };
191 
192 class RelocationValueRef {
193 public:
194   unsigned SectionID;
195   uint64_t Offset;
196   int64_t Addend;
197   const char *SymbolName;
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   }
205   inline bool operator<(const RelocationValueRef &Other) const {
206     if (SectionID != Other.SectionID)
207       return SectionID < Other.SectionID;
208     if (Offset != Other.Offset)
209       return Offset < Other.Offset;
210     if (Addend != Other.Addend)
211       return Addend < Other.Addend;
212     return SymbolName < Other.SymbolName;
213   }
214 };
215 
216 /// @brief Symbol info for RuntimeDyld.
217 class SymbolTableEntry {
218 public:
219   SymbolTableEntry()
220       : Offset(0), SectionID(0) {}
221 
222   SymbolTableEntry(unsigned SectionID, uint64_t Offset, JITSymbolFlags Flags)
223       : Offset(Offset), SectionID(SectionID), Flags(Flags) {}
224 
225   unsigned getSectionID() const { return SectionID; }
226   uint64_t getOffset() const { return Offset; }
227 
228   JITSymbolFlags getFlags() const { return Flags; }
229 
230 private:
231   uint64_t Offset;
232   unsigned SectionID;
233   JITSymbolFlags Flags;
234 };
235 
236 typedef StringMap<SymbolTableEntry> RTDyldSymbolTable;
237 
238 class RuntimeDyldImpl {
239   friend class RuntimeDyld::LoadedObjectInfo;
240   friend class RuntimeDyldCheckerImpl;
241 protected:
242   static const unsigned AbsoluteSymbolSection = ~0U;
243 
244   // The MemoryManager to load objects into.
245   RuntimeDyld::MemoryManager &MemMgr;
246 
247   // The symbol resolver to use for external symbols.
248   JITSymbolResolver &Resolver;
249 
250   // Attached RuntimeDyldChecker instance. Null if no instance attached.
251   RuntimeDyldCheckerImpl *Checker;
252 
253   // A list of all sections emitted by the dynamic linker.  These sections are
254   // referenced in the code by means of their index in this list - SectionID.
255   typedef SmallVector<SectionEntry, 64> SectionList;
256   SectionList Sections;
257 
258   typedef unsigned SID; // Type for SectionIDs
259 #define RTDYLD_INVALID_SECTION_ID ((RuntimeDyldImpl::SID)(-1))
260 
261   // Keep a map of sections from object file to the SectionID which
262   // references it.
263   typedef std::map<SectionRef, unsigned> ObjSectionToIDMap;
264 
265   // A global symbol table for symbols from all loaded modules.
266   RTDyldSymbolTable GlobalSymbolTable;
267 
268   // Keep a map of common symbols to their info pairs
269   typedef std::vector<SymbolRef> CommonSymbolList;
270 
271   // For each symbol, keep a list of relocations based on it. Anytime
272   // its address is reassigned (the JIT re-compiled the function, e.g.),
273   // the relocations get re-resolved.
274   // The symbol (or section) the relocation is sourced from is the Key
275   // in the relocation list where it's stored.
276   typedef SmallVector<RelocationEntry, 64> RelocationList;
277   // Relocations to sections already loaded. Indexed by SectionID which is the
278   // source of the address. The target where the address will be written is
279   // SectionID/Offset in the relocation itself.
280   std::unordered_map<unsigned, RelocationList> Relocations;
281 
282   // Relocations to external symbols that are not yet resolved.  Symbols are
283   // external when they aren't found in the global symbol table of all loaded
284   // modules.  This map is indexed by symbol name.
285   StringMap<RelocationList> ExternalSymbolRelocations;
286 
287 
288   typedef std::map<RelocationValueRef, uintptr_t> StubMap;
289 
290   Triple::ArchType Arch;
291   bool IsTargetLittleEndian;
292   bool IsMipsO32ABI;
293   bool IsMipsN32ABI;
294   bool IsMipsN64ABI;
295 
296   // True if all sections should be passed to the memory manager, false if only
297   // sections containing relocations should be. Defaults to 'false'.
298   bool ProcessAllSections;
299 
300   // This mutex prevents simultaneously loading objects from two different
301   // threads.  This keeps us from having to protect individual data structures
302   // and guarantees that section allocation requests to the memory manager
303   // won't be interleaved between modules.  It is also used in mapSectionAddress
304   // and resolveRelocations to protect write access to internal data structures.
305   //
306   // loadObject may be called on the same thread during the handling of of
307   // processRelocations, and that's OK.  The handling of the relocation lists
308   // is written in such a way as to work correctly if new elements are added to
309   // the end of the list while the list is being processed.
310   sys::Mutex lock;
311 
312   virtual unsigned getMaxStubSize() = 0;
313   virtual unsigned getStubAlignment() = 0;
314 
315   bool HasError;
316   std::string ErrorStr;
317 
318   uint64_t getSectionLoadAddress(unsigned SectionID) const {
319     return Sections[SectionID].getLoadAddress();
320   }
321 
322   uint8_t *getSectionAddress(unsigned SectionID) const {
323     return Sections[SectionID].getAddress();
324   }
325 
326   void writeInt16BE(uint8_t *Addr, uint16_t Value) {
327     if (IsTargetLittleEndian)
328       sys::swapByteOrder(Value);
329     *Addr       = (Value >> 8) & 0xFF;
330     *(Addr + 1) = Value & 0xFF;
331   }
332 
333   void writeInt32BE(uint8_t *Addr, uint32_t Value) {
334     if (IsTargetLittleEndian)
335       sys::swapByteOrder(Value);
336     *Addr       = (Value >> 24) & 0xFF;
337     *(Addr + 1) = (Value >> 16) & 0xFF;
338     *(Addr + 2) = (Value >> 8) & 0xFF;
339     *(Addr + 3) = Value & 0xFF;
340   }
341 
342   void writeInt64BE(uint8_t *Addr, uint64_t Value) {
343     if (IsTargetLittleEndian)
344       sys::swapByteOrder(Value);
345     *Addr       = (Value >> 56) & 0xFF;
346     *(Addr + 1) = (Value >> 48) & 0xFF;
347     *(Addr + 2) = (Value >> 40) & 0xFF;
348     *(Addr + 3) = (Value >> 32) & 0xFF;
349     *(Addr + 4) = (Value >> 24) & 0xFF;
350     *(Addr + 5) = (Value >> 16) & 0xFF;
351     *(Addr + 6) = (Value >> 8) & 0xFF;
352     *(Addr + 7) = Value & 0xFF;
353   }
354 
355   virtual void setMipsABI(const ObjectFile &Obj) {
356     IsMipsO32ABI = false;
357     IsMipsN32ABI = false;
358     IsMipsN64ABI = false;
359   }
360 
361   /// Endian-aware read Read the least significant Size bytes from Src.
362   uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const;
363 
364   /// Endian-aware write. Write the least significant Size bytes from Value to
365   /// Dst.
366   void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const;
367 
368   /// \brief Given the common symbols discovered in the object file, emit a
369   /// new section for them and update the symbol mappings in the object and
370   /// symbol table.
371   Error emitCommonSymbols(const ObjectFile &Obj,
372                           CommonSymbolList &CommonSymbols);
373 
374   /// \brief 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);
381 
382   /// \brief 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);
390 
391   // \brief Add a relocation entry that uses the given section.
392   void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID);
393 
394   // \brief 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);
397 
398   /// \brief 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);
401 
402   /// \brief Resolves relocations from Relocs list with address from Value.
403   void resolveRelocationList(const RelocationList &Relocs, uint64_t Value);
404 
405   /// \brief 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;
409 
410   /// \brief 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;
418 
419   /// \brief Resolve relocations to external symbols.
420   void resolveExternalSymbols();
421 
422   // \brief Compute an upper bound of the memory that is required to load all
423   // sections
424   Error computeTotalAllocSize(const ObjectFile &Obj,
425                               uint64_t &CodeSize, uint32_t &CodeAlign,
426                               uint64_t &RODataSize, uint32_t &RODataAlign,
427                               uint64_t &RWDataSize, uint32_t &RWDataAlign);
428 
429   // \brief Compute the stub buffer size required for a section
430   unsigned computeSectionStubBufSize(const ObjectFile &Obj,
431                                      const SectionRef &Section);
432 
433   // \brief Implementation of the generic part of the loadObject algorithm.
434   Expected<ObjSectionToIDMap> loadObjectImpl(const object::ObjectFile &Obj);
435 
436   // \brief Return true if the relocation R may require allocating a stub.
437   virtual bool relocationNeedsStub(const RelocationRef &R) const {
438     return true;    // Conservative answer
439   }
440 
441 public:
442   RuntimeDyldImpl(RuntimeDyld::MemoryManager &MemMgr,
443                   JITSymbolResolver &Resolver)
444     : MemMgr(MemMgr), Resolver(Resolver), Checker(nullptr),
445       ProcessAllSections(false), HasError(false) {
446   }
447 
448   virtual ~RuntimeDyldImpl();
449 
450   void setProcessAllSections(bool ProcessAllSections) {
451     this->ProcessAllSections = ProcessAllSections;
452   }
453 
454   void setRuntimeDyldChecker(RuntimeDyldCheckerImpl *Checker) {
455     this->Checker = Checker;
456   }
457 
458   virtual std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
459   loadObject(const object::ObjectFile &Obj) = 0;
460 
461   uint8_t* getSymbolLocalAddress(StringRef Name) const {
462     // FIXME: Just look up as a function for now. Overly simple of course.
463     // Work in progress.
464     RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
465     if (pos == GlobalSymbolTable.end())
466       return nullptr;
467     const auto &SymInfo = pos->second;
468     // Absolute symbols do not have a local address.
469     if (SymInfo.getSectionID() == AbsoluteSymbolSection)
470       return nullptr;
471     return getSectionAddress(SymInfo.getSectionID()) + SymInfo.getOffset();
472   }
473 
474   JITEvaluatedSymbol getSymbol(StringRef Name) const {
475     // FIXME: Just look up as a function for now. Overly simple of course.
476     // Work in progress.
477     RTDyldSymbolTable::const_iterator pos = GlobalSymbolTable.find(Name);
478     if (pos == GlobalSymbolTable.end())
479       return nullptr;
480     const auto &SymEntry = pos->second;
481     uint64_t SectionAddr = 0;
482     if (SymEntry.getSectionID() != AbsoluteSymbolSection)
483       SectionAddr = getSectionLoadAddress(SymEntry.getSectionID());
484     uint64_t TargetAddr = SectionAddr + SymEntry.getOffset();
485     return JITEvaluatedSymbol(TargetAddr, SymEntry.getFlags());
486   }
487 
488   void resolveRelocations();
489 
490   void reassignSectionAddress(unsigned SectionID, uint64_t Addr);
491 
492   void mapSectionAddress(const void *LocalAddress, uint64_t TargetAddress);
493 
494   // Is the linker in an error state?
495   bool hasError() { return HasError; }
496 
497   // Mark the error condition as handled and continue.
498   void clearError() { HasError = false; }
499 
500   // Get the error message.
501   StringRef getErrorString() { return ErrorStr; }
502 
503   virtual bool isCompatibleFile(const ObjectFile &Obj) const = 0;
504 
505   virtual void registerEHFrames();
506 
507   virtual void deregisterEHFrames();
508 
509   virtual Error finalizeLoad(const ObjectFile &ObjImg,
510                              ObjSectionToIDMap &SectionMap) {
511     return Error::success();
512   }
513 };
514 
515 } // end namespace llvm
516 
517 #endif
518