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