LLVM  7.0.0svn
RuntimeDyldCOFFX86_64.h
Go to the documentation of this file.
1 //===-- RuntimeDyldCOFFX86_64.h --- COFF/X86_64 specific code ---*- 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 // COFF x86_x64 support for MC-JIT runtime dynamic linker.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDCOFF86_64_H
15 #define LLVM_LIB_EXECUTIONENGINE_RUNTIMEDYLD_TARGETS_RUNTIMEDYLDCOFF86_64_H
16 
17 #include "../RuntimeDyldCOFF.h"
18 #include "llvm/BinaryFormat/COFF.h"
19 #include "llvm/Object/COFF.h"
20 
21 #define DEBUG_TYPE "dyld"
22 
23 namespace llvm {
24 
26 
27 private:
28  // When a module is loaded we save the SectionID of the unwind
29  // sections in a table until we receive a request to register all
30  // unregisteredEH frame sections with the memory manager.
31  SmallVector<SID, 2> UnregisteredEHFrameSections;
32  SmallVector<SID, 2> RegisteredEHFrameSections;
33  uint64_t ImageBase;
34 
35  // Fake an __ImageBase pointer by returning the section with the lowest adress
36  uint64_t getImageBase() {
37  if (!ImageBase) {
39  for (const SectionEntry &Section : Sections)
40  ImageBase = std::min(ImageBase, Section.getLoadAddress());
41  }
42  return ImageBase;
43  }
44 
45  void write32BitOffset(uint8_t *Target, int64_t Addend, uint64_t Delta) {
46  uint64_t Result = Addend + Delta;
47  assert(Result <= UINT32_MAX && "Relocation overflow");
48  writeBytesUnaligned(Result, Target, 4);
49  }
50 
51 public:
54  : RuntimeDyldCOFF(MM, Resolver), ImageBase(0) {}
55 
56  unsigned getStubAlignment() override { return 1; }
57 
58  // 2-byte jmp instruction + 32-bit relative address + 64-bit absolute jump
59  unsigned getMaxStubSize() override { return 14; }
60 
61  // The target location for the relocation is described by RE.SectionID and
62  // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
63  // SectionEntry has three members describing its location.
64  // SectionEntry::Address is the address at which the section has been loaded
65  // into memory in the current (host) process. SectionEntry::LoadAddress is
66  // the address that the section will have in the target process.
67  // SectionEntry::ObjAddress is the address of the bits for this section in the
68  // original emitted object image (also in the current address space).
69  //
70  // Relocations will be applied as if the section were loaded at
71  // SectionEntry::LoadAddress, but they will be applied at an address based
72  // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer
73  // to Target memory contents if they are required for value calculations.
74  //
75  // The Value parameter here is the load address of the symbol for the
76  // relocation to be applied. For relocations which refer to symbols in the
77  // current object Value will be the LoadAddress of the section in which
78  // the symbol resides (RE.Addend provides additional information about the
79  // symbol location). For external symbols, Value will be the address of the
80  // symbol in the target address space.
81  void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override {
83  uint8_t *Target = Section.getAddressWithOffset(RE.Offset);
84 
85  switch (RE.RelType) {
86 
93  uint64_t FinalAddress = Section.getLoadAddressWithOffset(RE.Offset);
94  // Delta is the distance from the start of the reloc to the end of the
95  // instruction with the reloc.
96  uint64_t Delta = 4 + (RE.RelType - COFF::IMAGE_REL_AMD64_REL32);
97  Value -= FinalAddress + Delta;
98  uint64_t Result = Value + RE.Addend;
99  assert(((int64_t)Result <= INT32_MAX) && "Relocation overflow");
100  assert(((int64_t)Result >= INT32_MIN) && "Relocation underflow");
101  writeBytesUnaligned(Result, Target, 4);
102  break;
103  }
104 
106  // ADDR32NB requires an offset less than 2GB from 'ImageBase'.
107  // The MemoryManager can make sure this is always true by forcing the
108  // memory layout to be: CodeSection < ReadOnlySection < ReadWriteSection.
109  const uint64_t ImageBase = getImageBase();
110  if (Value < ImageBase || ((Value - ImageBase) > UINT32_MAX)) {
111  llvm::errs() << "IMAGE_REL_AMD64_ADDR32NB relocation requires an"
112  << "ordered section layout.\n";
113  write32BitOffset(Target, 0, 0);
114  } else {
115  write32BitOffset(Target, RE.Addend, Value - ImageBase);
116  }
117  break;
118  }
119 
121  writeBytesUnaligned(Value + RE.Addend, Target, 8);
122  break;
123  }
124 
125  default:
126  llvm_unreachable("Relocation type not implemented yet!");
127  break;
128  }
129  }
130 
131  std::tuple<uint64_t, uint64_t, uint64_t>
132  generateRelocationStub(unsigned SectionID, StringRef TargetName,
133  uint64_t Offset, uint64_t RelType, uint64_t Addend,
134  StubMap &Stubs) {
135  uintptr_t StubOffset;
136  SectionEntry &Section = Sections[SectionID];
137 
138  RelocationValueRef OriginalRelValueRef;
139  OriginalRelValueRef.SectionID = SectionID;
140  OriginalRelValueRef.Offset = Offset;
141  OriginalRelValueRef.Addend = Addend;
142  OriginalRelValueRef.SymbolName = TargetName.data();
143 
144  auto Stub = Stubs.find(OriginalRelValueRef);
145  if (Stub == Stubs.end()) {
146  DEBUG(dbgs() << " Create a new stub function for " << TargetName.data()
147  << "\n");
148 
149  StubOffset = Section.getStubOffset();
150  Stubs[OriginalRelValueRef] = StubOffset;
151  createStubFunction(Section.getAddressWithOffset(StubOffset));
153  } else {
154  DEBUG(dbgs() << " Stub function found for " << TargetName.data() << "\n");
155  StubOffset = Stub->second;
156  }
157 
158  // FIXME: If RelType == COFF::IMAGE_REL_AMD64_ADDR32NB we should be able
159  // to ignore the __ImageBase requirement and just forward to the stub
160  // directly as an offset of this section:
161  // write32BitOffset(Section.getAddressWithOffset(Offset), 0, StubOffset);
162  // .xdata exception handler's aren't having this though.
163 
164  // Resolve original relocation to stub function.
165  const RelocationEntry RE(SectionID, Offset, RelType, Addend);
166  resolveRelocation(RE, Section.getLoadAddressWithOffset(StubOffset));
167 
168  // adjust relocation info so resolution writes to the stub function
169  Addend = 0;
170  Offset = StubOffset + 6;
172 
173  return std::make_tuple(Offset, RelType, Addend);
174  }
175 
177  processRelocationRef(unsigned SectionID,
178  relocation_iterator RelI,
179  const ObjectFile &Obj,
180  ObjSectionToIDMap &ObjSectionToID,
181  StubMap &Stubs) override {
182  // If possible, find the symbol referred to in the relocation,
183  // and the section that contains it.
184  symbol_iterator Symbol = RelI->getSymbol();
185  if (Symbol == Obj.symbol_end())
186  report_fatal_error("Unknown symbol in relocation");
187  auto SectionOrError = Symbol->getSection();
188  if (!SectionOrError)
189  return SectionOrError.takeError();
190  section_iterator SecI = *SectionOrError;
191  // If there is no section, this must be an external reference.
192  const bool IsExtern = SecI == Obj.section_end();
193 
194  // Determine the Addend used to adjust the relocation value.
195  uint64_t RelType = RelI->getType();
196  uint64_t Offset = RelI->getOffset();
197  uint64_t Addend = 0;
198  SectionEntry &Section = Sections[SectionID];
199  uintptr_t ObjTarget = Section.getObjAddress() + Offset;
200 
201  Expected<StringRef> TargetNameOrErr = Symbol->getName();
202  if (!TargetNameOrErr)
203  return TargetNameOrErr.takeError();
204  StringRef TargetName = *TargetNameOrErr;
205 
206  switch (RelType) {
207 
215  uint8_t *Displacement = (uint8_t *)ObjTarget;
216  Addend = readBytesUnaligned(Displacement, 4);
217 
218  if (IsExtern)
219  std::tie(Offset, RelType, Addend) = generateRelocationStub(
220  SectionID, TargetName, Offset, RelType, Addend, Stubs);
221 
222  break;
223  }
224 
226  uint8_t *Displacement = (uint8_t *)ObjTarget;
227  Addend = readBytesUnaligned(Displacement, 8);
228  break;
229  }
230 
231  default:
232  break;
233  }
234 
235  DEBUG(dbgs() << "\t\tIn Section " << SectionID << " Offset " << Offset
236  << " RelType: " << RelType << " TargetName: " << TargetName
237  << " Addend " << Addend << "\n");
238 
239  if (IsExtern) {
240  RelocationEntry RE(SectionID, Offset, RelType, Addend);
241  addRelocationForSymbol(RE, TargetName);
242  } else {
243  bool IsCode = SecI->isText();
244  unsigned TargetSectionID;
245  if (auto TargetSectionIDOrErr =
246  findOrEmitSection(Obj, *SecI, IsCode, ObjSectionToID))
247  TargetSectionID = *TargetSectionIDOrErr;
248  else
249  return TargetSectionIDOrErr.takeError();
250  uint64_t TargetOffset = getSymbolOffset(*Symbol);
251  RelocationEntry RE(SectionID, Offset, RelType, TargetOffset + Addend);
252  addRelocationForSection(RE, TargetSectionID);
253  }
254 
255  return ++RelI;
256  }
257 
258  void registerEHFrames() override {
259  for (auto const &EHFrameSID : UnregisteredEHFrameSections) {
260  uint8_t *EHFrameAddr = Sections[EHFrameSID].getAddress();
261  uint64_t EHFrameLoadAddr = Sections[EHFrameSID].getLoadAddress();
262  size_t EHFrameSize = Sections[EHFrameSID].getSize();
263  MemMgr.registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
264  RegisteredEHFrameSections.push_back(EHFrameSID);
265  }
266  UnregisteredEHFrameSections.clear();
267  }
268 
270  ObjSectionToIDMap &SectionMap) override {
271  // Look for and record the EH frame section IDs.
272  for (const auto &SectionPair : SectionMap) {
273  const SectionRef &Section = SectionPair.first;
274  StringRef Name;
275  if (auto EC = Section.getName(Name))
276  return errorCodeToError(EC);
277 
278  // Note unwind info is stored in .pdata but often points to .xdata
279  // with an IMAGE_REL_AMD64_ADDR32NB relocation. Using a memory manager
280  // that keeps sections ordered in relation to __ImageBase is necessary.
281  if (Name == ".pdata")
282  UnregisteredEHFrameSections.push_back(SectionPair.second);
283  }
284  return Error::success();
285  }
286 };
287 
288 } // end namespace llvm
289 
290 #undef DEBUG_TYPE
291 
292 #endif
RelocationEntry - used to represent relocations internally in the dynamic linker. ...
void push_back(const T &Elt)
Definition: SmallVector.h:212
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
Expected< StringRef > getName() const
Definition: ObjectFile.h:338
uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const
Endian-aware read Read the least significant Size bytes from Src.
uint64_t getLoadAddressWithOffset(unsigned OffsetBytes) const
Return the load address of this section with an offset.
RuntimeDyld::MemoryManager & MemMgr
This class is the base class for all object file types.
Definition: ObjectFile.h:190
uint64_t getSymbolOffset(const SymbolRef &Sym)
Error takeError()
Take ownership of the stored error.
Definition: Error.h:537
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:128
void writeBytesUnaligned(uint64_t Value, uint8_t *Dst, unsigned Size) const
Endian-aware write.
unsigned getStubAlignment() override
unsigned SectionID
SectionID - the section this relocation points to.
std::map< RelocationValueRef, uintptr_t > StubMap
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
RuntimeDyldCOFFX86_64(RuntimeDyld::MemoryManager &MM, JITSymbolResolver &Resolver)
Expected< section_iterator > getSection() const
Get section this symbol is defined in reference to.
Definition: ObjectFile.h:358
void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName)
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:78
void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID)
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:1794
void resolveRelocation(const RelocationEntry &RE, uint64_t Value) override
A object file specific relocation resolver.
Symbol resolution interface.
Definition: JITSymbol.h:289
virtual basic_symbol_iterator symbol_end() const =0
uintptr_t getObjAddress() const
Error finalizeLoad(const ObjectFile &Obj, ObjSectionToIDMap &SectionMap) override
Expected< unsigned > findOrEmitSection(const ObjectFile &Obj, const SectionRef &Section, bool IsCode, ObjSectionToIDMap &LocalSections)
Find Section in LocalSections.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static ErrorSuccess success()
Create a success value.
Definition: Error.h:313
int64_t Addend
Addend - the relocation addend encoded in the instruction itself.
std::error_code getName(StringRef &Result) const
Definition: ObjectFile.h:393
uint32_t RelType
RelType - relocation type.
uint8_t * createStubFunction(uint8_t *Addr, unsigned AbiVariant=0)
Emits long jump instruction to Addr.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Target - Wrapper for Target specific information.
uintptr_t getStubOffset() const
std::tuple< uint64_t, uint64_t, uint64_t > generateRelocationStub(unsigned SectionID, StringRef TargetName, uint64_t Offset, uint64_t RelType, uint64_t Addend, StubMap &Stubs)
Expected< relocation_iterator > processRelocationRef(unsigned SectionID, relocation_iterator RelI, const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID, StubMap &Stubs) override
Parses one or more object file relocations (some object files use relocation pairs) and stores it to ...
uint64_t Offset
Offset - offset into the section.
virtual section_iterator section_end() const =0
std::map< SectionRef, unsigned > ObjSectionToIDMap
uint8_t * getAddressWithOffset(unsigned OffsetBytes) const
Return the address of this section with an offset.
SectionEntry - represents a section emitted into memory by the dynamic linker.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
Definition: Value.h:73
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
#define DEBUG(X)
Definition: Debug.h:118
void advanceStubOffset(unsigned StubSize)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size)=0
Register the EH frames with the runtime so that c++ exceptions work.
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81
unsigned getMaxStubSize() override