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