LLVM  5.0.0
RuntimeDyldMachO.cpp
Go to the documentation of this file.
1 //===-- RuntimeDyldMachO.cpp - 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 // Implementation of the MC-JIT runtime dynamic linker.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "RuntimeDyldMachO.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 
22 using namespace llvm;
23 using namespace llvm::object;
24 
25 #define DEBUG_TYPE "dyld"
26 
27 namespace {
28 
29 class LoadedMachOObjectInfo final
30  : public LoadedObjectInfoHelper<LoadedMachOObjectInfo,
31  RuntimeDyld::LoadedObjectInfo> {
32 public:
33  LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld,
34  ObjSectionToIDMap ObjSecToIDMap)
35  : LoadedObjectInfoHelper(RTDyld, std::move(ObjSecToIDMap)) {}
36 
38  getObjectForDebug(const ObjectFile &Obj) const override {
39  return OwningBinary<ObjectFile>();
40  }
41 };
42 
43 }
44 
45 namespace llvm {
46 
48  unsigned NumBytes = 1 << RE.Size;
49  uint8_t *Src = Sections[RE.SectionID].getAddress() + RE.Offset;
50 
51  return static_cast<int64_t>(readBytesUnaligned(Src, NumBytes));
52 }
53 
56  unsigned SectionID, relocation_iterator RelI,
57  const ObjectFile &BaseObjT,
58  RuntimeDyldMachO::ObjSectionToIDMap &ObjSectionToID) {
59  const MachOObjectFile &Obj =
60  static_cast<const MachOObjectFile&>(BaseObjT);
62  Obj.getRelocation(RelI->getRawDataRefImpl());
63 
64  SectionEntry &Section = Sections[SectionID];
65  uint32_t RelocType = Obj.getAnyRelocationType(RE);
66  bool IsPCRel = Obj.getAnyRelocationPCRel(RE);
67  unsigned Size = Obj.getAnyRelocationLength(RE);
68  uint64_t Offset = RelI->getOffset();
69  uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
70  unsigned NumBytes = 1 << Size;
71  int64_t Addend = readBytesUnaligned(LocalAddress, NumBytes);
72 
73  unsigned SymbolBaseAddr = Obj.getScatteredRelocationValue(RE);
74  section_iterator TargetSI = getSectionByAddress(Obj, SymbolBaseAddr);
75  assert(TargetSI != Obj.section_end() && "Can't find section for symbol");
76  uint64_t SectionBaseAddr = TargetSI->getAddress();
77  SectionRef TargetSection = *TargetSI;
78  bool IsCode = TargetSection.isText();
79  uint32_t TargetSectionID = ~0U;
80  if (auto TargetSectionIDOrErr =
81  findOrEmitSection(Obj, TargetSection, IsCode, ObjSectionToID))
82  TargetSectionID = *TargetSectionIDOrErr;
83  else
84  return TargetSectionIDOrErr.takeError();
85 
86  Addend -= SectionBaseAddr;
87  RelocationEntry R(SectionID, Offset, RelocType, Addend, IsPCRel, Size);
88 
89  addRelocationForSection(R, TargetSectionID);
90 
91  return ++RelI;
92 }
93 
94 
97  const ObjectFile &BaseTObj, const relocation_iterator &RI,
98  const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID) {
99 
100  const MachOObjectFile &Obj =
101  static_cast<const MachOObjectFile &>(BaseTObj);
103  Obj.getRelocation(RI->getRawDataRefImpl());
105 
106  bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
107  if (IsExternal) {
108  symbol_iterator Symbol = RI->getSymbol();
109  StringRef TargetName;
110  if (auto TargetNameOrErr = Symbol->getName())
111  TargetName = *TargetNameOrErr;
112  else
113  return TargetNameOrErr.takeError();
115  GlobalSymbolTable.find(TargetName.data());
116  if (SI != GlobalSymbolTable.end()) {
117  const auto &SymInfo = SI->second;
118  Value.SectionID = SymInfo.getSectionID();
119  Value.Offset = SymInfo.getOffset() + RE.Addend;
120  } else {
121  Value.SymbolName = TargetName.data();
122  Value.Offset = RE.Addend;
123  }
124  } else {
125  SectionRef Sec = Obj.getAnyRelocationSection(RelInfo);
126  bool IsCode = Sec.isText();
127  if (auto SectionIDOrErr = findOrEmitSection(Obj, Sec, IsCode,
128  ObjSectionToID))
129  Value.SectionID = *SectionIDOrErr;
130  else
131  return SectionIDOrErr.takeError();
132  uint64_t Addr = Sec.getAddress();
133  Value.Offset = RE.Addend - Addr;
134  }
135 
136  return Value;
137 }
138 
140  const relocation_iterator &RI,
141  unsigned OffsetToNextPC) {
142  auto &O = *cast<MachOObjectFile>(RI->getObject());
143  section_iterator SecI = O.getRelocationRelocatedSection(RI);
144  Value.Offset += RI->getOffset() + OffsetToNextPC + SecI->getAddress();
145 }
146 
148  uint64_t Value) const {
149  const SectionEntry &Section = Sections[RE.SectionID];
150  uint8_t *LocalAddress = Section.getAddress() + RE.Offset;
151  uint64_t FinalAddress = Section.getLoadAddress() + RE.Offset;
152 
153  dbgs() << "resolveRelocation Section: " << RE.SectionID
154  << " LocalAddress: " << format("%p", LocalAddress)
155  << " FinalAddress: " << format("0x%016" PRIx64, FinalAddress)
156  << " Value: " << format("0x%016" PRIx64, Value) << " Addend: " << RE.Addend
157  << " isPCRel: " << RE.IsPCRel << " MachoType: " << RE.RelType
158  << " Size: " << (1 << RE.Size) << "\n";
159 }
160 
163  uint64_t Addr) {
165  section_iterator SE = Obj.section_end();
166 
167  for (; SI != SE; ++SI) {
168  uint64_t SAddr = SI->getAddress();
169  uint64_t SSize = SI->getSize();
170  if ((Addr >= SAddr) && (Addr < SAddr + SSize))
171  return SI;
172  }
173 
174  return SE;
175 }
176 
177 
178 // Populate __pointers section.
180  const MachOObjectFile &Obj,
181  const SectionRef &PTSection,
182  unsigned PTSectionID) {
183  assert(!Obj.is64Bit() &&
184  "Pointer table section not supported in 64-bit MachO.");
185 
187  MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
188  uint32_t PTSectionSize = Sec32.size;
189  unsigned FirstIndirectSymbol = Sec32.reserved1;
190  const unsigned PTEntrySize = 4;
191  unsigned NumPTEntries = PTSectionSize / PTEntrySize;
192  unsigned PTEntryOffset = 0;
193 
194  assert((PTSectionSize % PTEntrySize) == 0 &&
195  "Pointers section does not contain a whole number of stubs?");
196 
197  DEBUG(dbgs() << "Populating pointer table section "
198  << Sections[PTSectionID].getName() << ", Section ID "
199  << PTSectionID << ", " << NumPTEntries << " entries, "
200  << PTEntrySize << " bytes each:\n");
201 
202  for (unsigned i = 0; i < NumPTEntries; ++i) {
203  unsigned SymbolIndex =
204  Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
205  symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
206  StringRef IndirectSymbolName;
207  if (auto IndirectSymbolNameOrErr = SI->getName())
208  IndirectSymbolName = *IndirectSymbolNameOrErr;
209  else
210  return IndirectSymbolNameOrErr.takeError();
211  DEBUG(dbgs() << " " << IndirectSymbolName << ": index " << SymbolIndex
212  << ", PT offset: " << PTEntryOffset << "\n");
213  RelocationEntry RE(PTSectionID, PTEntryOffset,
214  MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
215  addRelocationForSymbol(RE, IndirectSymbolName);
216  PTEntryOffset += PTEntrySize;
217  }
218  return Error::success();
219 }
220 
222  return Obj.isMachO();
223 }
224 
225 template <typename Impl>
226 Error
228  ObjSectionToIDMap &SectionMap) {
229  unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
230  unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
231  unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
232 
233  for (const auto &Section : Obj.sections()) {
234  StringRef Name;
235  Section.getName(Name);
236 
237  // Force emission of the __text, __eh_frame, and __gcc_except_tab sections
238  // if they're present. Otherwise call down to the impl to handle other
239  // sections that have already been emitted.
240  if (Name == "__text") {
241  if (auto TextSIDOrErr = findOrEmitSection(Obj, Section, true, SectionMap))
242  TextSID = *TextSIDOrErr;
243  else
244  return TextSIDOrErr.takeError();
245  } else if (Name == "__eh_frame") {
246  if (auto EHFrameSIDOrErr = findOrEmitSection(Obj, Section, false,
247  SectionMap))
248  EHFrameSID = *EHFrameSIDOrErr;
249  else
250  return EHFrameSIDOrErr.takeError();
251  } else if (Name == "__gcc_except_tab") {
252  if (auto ExceptTabSIDOrErr = findOrEmitSection(Obj, Section, true,
253  SectionMap))
254  ExceptTabSID = *ExceptTabSIDOrErr;
255  else
256  return ExceptTabSIDOrErr.takeError();
257  } else {
258  auto I = SectionMap.find(Section);
259  if (I != SectionMap.end())
260  if (auto Err = impl().finalizeSection(Obj, I->second, Section))
261  return Err;
262  }
263  }
264  UnregisteredEHFrameSections.push_back(
265  EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
266 
267  return Error::success();
268 }
269 
270 template <typename Impl>
271 unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(uint8_t *P,
272  int64_t DeltaForText,
273  int64_t DeltaForEH) {
274  typedef typename Impl::TargetPtrT TargetPtrT;
275 
276  DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
277  << ", Delta for EH: " << DeltaForEH << "\n");
278  uint32_t Length = readBytesUnaligned(P, 4);
279  P += 4;
280  uint8_t *Ret = P + Length;
281  uint32_t Offset = readBytesUnaligned(P, 4);
282  if (Offset == 0) // is a CIE
283  return Ret;
284 
285  P += 4;
286  TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
287  TargetPtrT NewLocation = FDELocation - DeltaForText;
288  writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
289 
290  P += sizeof(TargetPtrT);
291 
292  // Skip the FDE address range
293  P += sizeof(TargetPtrT);
294 
295  uint8_t Augmentationsize = *P;
296  P += 1;
297  if (Augmentationsize != 0) {
298  TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
299  TargetPtrT NewLSDA = LSDA - DeltaForEH;
300  writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
301  }
302 
303  return Ret;
304 }
305 
307  int64_t ObjDistance = static_cast<int64_t>(A->getObjAddress()) -
308  static_cast<int64_t>(B->getObjAddress());
309  int64_t MemDistance = A->getLoadAddress() - B->getLoadAddress();
310  return ObjDistance - MemDistance;
311 }
312 
313 template <typename Impl>
315 
316  for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
317  EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
318  if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
319  SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
320  continue;
321  SectionEntry *Text = &Sections[SectionInfo.TextSID];
322  SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
323  SectionEntry *ExceptTab = nullptr;
324  if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
325  ExceptTab = &Sections[SectionInfo.ExceptTabSID];
326 
327  int64_t DeltaForText = computeDelta(Text, EHFrame);
328  int64_t DeltaForEH = 0;
329  if (ExceptTab)
330  DeltaForEH = computeDelta(ExceptTab, EHFrame);
331 
332  uint8_t *P = EHFrame->getAddress();
333  uint8_t *End = P + EHFrame->getSize();
334  while (P != End) {
335  P = processFDE(P, DeltaForText, DeltaForEH);
336  }
337 
338  MemMgr.registerEHFrames(EHFrame->getAddress(), EHFrame->getLoadAddress(),
339  EHFrame->getSize());
340  }
341  UnregisteredEHFrameSections.clear();
342 }
343 
344 std::unique_ptr<RuntimeDyldMachO>
347  JITSymbolResolver &Resolver) {
348  switch (Arch) {
349  default:
350  llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
351  break;
352  case Triple::arm:
353  return make_unique<RuntimeDyldMachOARM>(MemMgr, Resolver);
354  case Triple::aarch64:
355  return make_unique<RuntimeDyldMachOAArch64>(MemMgr, Resolver);
356  case Triple::x86:
357  return make_unique<RuntimeDyldMachOI386>(MemMgr, Resolver);
358  case Triple::x86_64:
359  return make_unique<RuntimeDyldMachOX86_64>(MemMgr, Resolver);
360  }
361 }
362 
363 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
365  if (auto ObjSectionToIDOrErr = loadObjectImpl(O))
366  return llvm::make_unique<LoadedMachOObjectInfo>(*this,
367  *ObjSectionToIDOrErr);
368  else {
369  HasError = true;
370  raw_string_ostream ErrStream(ErrorStr);
371  logAllUnhandledErrors(ObjSectionToIDOrErr.takeError(), ErrStream, "");
372  return nullptr;
373  }
374 }
375 
376 } // end namespace llvm
RelocationEntry - used to represent relocations internally in the dynamic linker. ...
bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const
size_t getSize() const
Error finalizeLoad(const ObjectFile &Obj, ObjSectionToIDMap &SectionMap) override
Expected< StringRef > getName() const
Definition: ObjectFile.h:339
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner)
Log all errors (if any) in E to OS.
Definition: Error.cpp:57
unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const
uintptr_t getObjAddress() const
uint32_t reserved1
Definition: MachO.h:561
uint8_t * getAddress() const
This class is the base class for all object file types.
Definition: ObjectFile.h:189
uint32_t size
Definition: MachO.h:555
DataRefImpl getRawDataRefImpl() const
Definition: ObjectFile.h:454
uint32_t getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC, unsigned Index) const
bool isCompatibleFile(const object::ObjectFile &Obj) const override
bool IsPCRel
True if this is a PCRel relocation (MachO specific).
unsigned SectionID
SectionID - the section this relocation points to.
static StringRef getName(Value *V)
int64_t memcpyAddend(const RelocationEntry &RE) const
This convenience method uses memcpy to extract a contiguous addend (the addend size and offset are ta...
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
uint32_t getScatteredRelocationValue(const MachO::any_relocation_info &RE) const
static std::unique_ptr< RuntimeDyldMachO > create(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver)
Create a RuntimeDyldMachO instance for the given target architecture.
place backedge safepoints impl
const char * Name
format_object< Ts...> format(const char *Fmt, const Ts &...Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
void dumpRelocationToResolve(const RelocationEntry &RE, uint64_t Value) const
Dump information about the relocation entry (RE) and resolved value.
RuntimeDyldMachOTarget - Templated base class for generic MachO linker algorithms and data structures...
#define P(N)
Expected< RelocationValueRef > getRelocationValueRef(const ObjectFile &BaseTObj, const relocation_iterator &RI, const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID)
Construct a RelocationValueRef representing the relocation target.
uint8_t * getAddressWithOffset(unsigned OffsetBytes) const
Return the address of this section with an offset.
MachO::any_relocation_info getRelocation(DataRefImpl Rel) const
MachO::section getSection(DataRefImpl DRI) const
static int64_t computeDelta(SectionEntry *A, SectionEntry *B)
#define A
Definition: LargeTest.cpp:12
bool isText() const
Definition: ObjectFile.h:422
unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const
Symbol resolution.
Definition: JITSymbol.h:223
static const unsigned End
Expected< relocation_iterator > processScatteredVANILLA(unsigned SectionID, relocation_iterator RelI, const ObjectFile &BaseObjT, RuntimeDyldMachO::ObjSectionToIDMap &ObjSectionToID)
Process a scattered vanilla relocation.
section_iterator_range sections() const
Definition: ObjectFile.h:272
uint64_t getAddress() const
Definition: ObjectFile.h:398
static section_iterator getSectionByAddress(const MachOObjectFile &Obj, uint64_t Addr)
static ErrorSuccess success()
Create a success value.
Definition: Error.h:311
unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const
#define B
Definition: LargeTest.cpp:24
bool isMachO() const
Definition: Binary.h:112
int64_t Addend
Addend - the relocation addend encoded in the instruction itself.
uint32_t RelType
RelType - relocation type.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
llvm_unreachable("Unknown RegBank!")
#define RTDYLD_INVALID_SECTION_ID
uint64_t Offset
Offset - offset into the section.
std::map< SectionRef, unsigned > ObjSectionToIDMap
#define I(x, y, z)
Definition: MD5.cpp:58
basic_symbol_iterator getSymbolByIndex(unsigned Index) const
section_iterator section_begin() const override
std::unique_ptr< RuntimeDyld::LoadedObjectInfo > loadObject(const object::ObjectFile &O) override
MachO::dysymtab_command getDysymtabLoadCommand() const
uint64_t getLoadAddress() const
SymInfo contains information about symbol: it's address and section index which is -1LL for absolute ...
SectionEntry - represents a section emitted into memory by the dynamic linker.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:463
LLVM Value Representation.
Definition: Value.h:73
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
unsigned Size
The size of this relocation (MachO specific).
section_iterator section_end() const override
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
#define DEBUG(X)
Definition: Debug.h:118
Error populateIndirectSymbolPointersSection(const MachOObjectFile &Obj, const SectionRef &PTSection, unsigned PTSectionID)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
void makeValueAddendPCRel(RelocationValueRef &Value, const relocation_iterator &RI, unsigned OffsetToNextPC)
Make the RelocationValueRef addend PC-relative.
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81