Return ErrorOr from SymbolRef::getName.
[oota-llvm.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyldMachO.cpp
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"
15 #include "Targets/RuntimeDyldMachOAArch64.h"
16 #include "Targets/RuntimeDyldMachOARM.h"
17 #include "Targets/RuntimeDyldMachOI386.h"
18 #include "Targets/RuntimeDyldMachOX86_64.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
30     : public RuntimeDyld::LoadedObjectInfoHelper<LoadedMachOObjectInfo> {
31 public:
32   LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
33                         unsigned EndIdx)
34       : LoadedObjectInfoHelper(RTDyld, BeginIdx, EndIdx) {}
35
36   OwningBinary<ObjectFile>
37   getObjectForDebug(const ObjectFile &Obj) const override {
38     return OwningBinary<ObjectFile>();
39   }
40 };
41
42 }
43
44 namespace llvm {
45
46 int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
47   unsigned NumBytes = 1 << RE.Size;
48   uint8_t *Src = Sections[RE.SectionID].Address + RE.Offset;
49
50   return static_cast<int64_t>(readBytesUnaligned(Src, NumBytes));
51 }
52
53 RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
54     const ObjectFile &BaseTObj, const relocation_iterator &RI,
55     const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID) {
56
57   const MachOObjectFile &Obj =
58       static_cast<const MachOObjectFile &>(BaseTObj);
59   MachO::any_relocation_info RelInfo =
60       Obj.getRelocation(RI->getRawDataRefImpl());
61   RelocationValueRef Value;
62
63   bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
64   if (IsExternal) {
65     symbol_iterator Symbol = RI->getSymbol();
66     ErrorOr<StringRef> TargetNameOrErr = Symbol->getName();
67     if (std::error_code EC = TargetNameOrErr.getError())
68       report_fatal_error(EC.message());
69     StringRef TargetName = *TargetNameOrErr;
70     RTDyldSymbolTable::const_iterator SI =
71       GlobalSymbolTable.find(TargetName.data());
72     if (SI != GlobalSymbolTable.end()) {
73       const auto &SymInfo = SI->second;
74       Value.SectionID = SymInfo.getSectionID();
75       Value.Offset = SymInfo.getOffset() + RE.Addend;
76     } else {
77       Value.SymbolName = TargetName.data();
78       Value.Offset = RE.Addend;
79     }
80   } else {
81     SectionRef Sec = Obj.getAnyRelocationSection(RelInfo);
82     bool IsCode = Sec.isText();
83     Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
84     uint64_t Addr = Sec.getAddress();
85     Value.Offset = RE.Addend - Addr;
86   }
87
88   return Value;
89 }
90
91 void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
92                                             const ObjectFile &BaseTObj,
93                                             const relocation_iterator &RI,
94                                             unsigned OffsetToNextPC) {
95   const MachOObjectFile &Obj =
96       static_cast<const MachOObjectFile &>(BaseTObj);
97   MachO::any_relocation_info RelInfo =
98       Obj.getRelocation(RI->getRawDataRefImpl());
99
100   bool IsPCRel = Obj.getAnyRelocationPCRel(RelInfo);
101   if (IsPCRel) {
102     ErrorOr<uint64_t> RelocAddr = RI->getAddress();
103     Value.Offset += *RelocAddr + OffsetToNextPC;
104   }
105 }
106
107 void RuntimeDyldMachO::dumpRelocationToResolve(const RelocationEntry &RE,
108                                                uint64_t Value) const {
109   const SectionEntry &Section = Sections[RE.SectionID];
110   uint8_t *LocalAddress = Section.Address + RE.Offset;
111   uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
112
113   dbgs() << "resolveRelocation Section: " << RE.SectionID
114          << " LocalAddress: " << format("%p", LocalAddress)
115          << " FinalAddress: " << format("0x%016" PRIx64, FinalAddress)
116          << " Value: " << format("0x%016" PRIx64, Value) << " Addend: " << RE.Addend
117          << " isPCRel: " << RE.IsPCRel << " MachoType: " << RE.RelType
118          << " Size: " << (1 << RE.Size) << "\n";
119 }
120
121 section_iterator
122 RuntimeDyldMachO::getSectionByAddress(const MachOObjectFile &Obj,
123                                       uint64_t Addr) {
124   section_iterator SI = Obj.section_begin();
125   section_iterator SE = Obj.section_end();
126
127   for (; SI != SE; ++SI) {
128     uint64_t SAddr = SI->getAddress();
129     uint64_t SSize = SI->getSize();
130     if ((Addr >= SAddr) && (Addr < SAddr + SSize))
131       return SI;
132   }
133
134   return SE;
135 }
136
137
138 // Populate __pointers section.
139 void RuntimeDyldMachO::populateIndirectSymbolPointersSection(
140                                                     const MachOObjectFile &Obj,
141                                                     const SectionRef &PTSection,
142                                                     unsigned PTSectionID) {
143   assert(!Obj.is64Bit() &&
144          "Pointer table section not supported in 64-bit MachO.");
145
146   MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
147   MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
148   uint32_t PTSectionSize = Sec32.size;
149   unsigned FirstIndirectSymbol = Sec32.reserved1;
150   const unsigned PTEntrySize = 4;
151   unsigned NumPTEntries = PTSectionSize / PTEntrySize;
152   unsigned PTEntryOffset = 0;
153
154   assert((PTSectionSize % PTEntrySize) == 0 &&
155          "Pointers section does not contain a whole number of stubs?");
156
157   DEBUG(dbgs() << "Populating pointer table section "
158                << Sections[PTSectionID].Name
159                << ", Section ID " << PTSectionID << ", "
160                << NumPTEntries << " entries, " << PTEntrySize
161                << " bytes each:\n");
162
163   for (unsigned i = 0; i < NumPTEntries; ++i) {
164     unsigned SymbolIndex =
165       Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
166     symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
167     ErrorOr<StringRef> IndirectSymbolNameOrErr = SI->getName();
168     if (std::error_code EC = IndirectSymbolNameOrErr.getError())
169       report_fatal_error(EC.message());
170     StringRef IndirectSymbolName = *IndirectSymbolNameOrErr;
171     DEBUG(dbgs() << "  " << IndirectSymbolName << ": index " << SymbolIndex
172           << ", PT offset: " << PTEntryOffset << "\n");
173     RelocationEntry RE(PTSectionID, PTEntryOffset,
174                        MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
175     addRelocationForSymbol(RE, IndirectSymbolName);
176     PTEntryOffset += PTEntrySize;
177   }
178 }
179
180 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
181   return Obj.isMachO();
182 }
183
184 template <typename Impl>
185 void RuntimeDyldMachOCRTPBase<Impl>::finalizeLoad(const ObjectFile &Obj,
186                                                   ObjSectionToIDMap &SectionMap) {
187   unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
188   unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
189   unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
190
191   for (const auto &Section : Obj.sections()) {
192     StringRef Name;
193     Section.getName(Name);
194
195     // Force emission of the __text, __eh_frame, and __gcc_except_tab sections
196     // if they're present. Otherwise call down to the impl to handle other
197     // sections that have already been emitted.
198     if (Name == "__text")
199       TextSID = findOrEmitSection(Obj, Section, true, SectionMap);
200     else if (Name == "__eh_frame")
201       EHFrameSID = findOrEmitSection(Obj, Section, false, SectionMap);
202     else if (Name == "__gcc_except_tab")
203       ExceptTabSID = findOrEmitSection(Obj, Section, true, SectionMap);
204     else {
205       auto I = SectionMap.find(Section);
206       if (I != SectionMap.end())
207         impl().finalizeSection(Obj, I->second, Section);
208     }
209   }
210   UnregisteredEHFrameSections.push_back(
211     EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
212 }
213
214 template <typename Impl>
215 unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(unsigned char *P,
216                                                           int64_t DeltaForText,
217                                                           int64_t DeltaForEH) {
218   typedef typename Impl::TargetPtrT TargetPtrT;
219
220   DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
221                << ", Delta for EH: " << DeltaForEH << "\n");
222   uint32_t Length = readBytesUnaligned(P, 4);
223   P += 4;
224   unsigned char *Ret = P + Length;
225   uint32_t Offset = readBytesUnaligned(P, 4);
226   if (Offset == 0) // is a CIE
227     return Ret;
228
229   P += 4;
230   TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
231   TargetPtrT NewLocation = FDELocation - DeltaForText;
232   writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
233
234   P += sizeof(TargetPtrT);
235
236   // Skip the FDE address range
237   P += sizeof(TargetPtrT);
238
239   uint8_t Augmentationsize = *P;
240   P += 1;
241   if (Augmentationsize != 0) {
242     TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
243     TargetPtrT NewLSDA = LSDA - DeltaForEH;
244     writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
245   }
246
247   return Ret;
248 }
249
250 static int64_t computeDelta(SectionEntry *A, SectionEntry *B) {
251   int64_t ObjDistance =
252     static_cast<int64_t>(A->ObjAddress) - static_cast<int64_t>(B->ObjAddress);
253   int64_t MemDistance = A->LoadAddress - B->LoadAddress;
254   return ObjDistance - MemDistance;
255 }
256
257 template <typename Impl>
258 void RuntimeDyldMachOCRTPBase<Impl>::registerEHFrames() {
259
260   for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
261     EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
262     if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
263         SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
264       continue;
265     SectionEntry *Text = &Sections[SectionInfo.TextSID];
266     SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
267     SectionEntry *ExceptTab = nullptr;
268     if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
269       ExceptTab = &Sections[SectionInfo.ExceptTabSID];
270
271     int64_t DeltaForText = computeDelta(Text, EHFrame);
272     int64_t DeltaForEH = 0;
273     if (ExceptTab)
274       DeltaForEH = computeDelta(ExceptTab, EHFrame);
275
276     unsigned char *P = EHFrame->Address;
277     unsigned char *End = P + EHFrame->Size;
278     do {
279       P = processFDE(P, DeltaForText, DeltaForEH);
280     } while (P != End);
281
282     MemMgr.registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
283                             EHFrame->Size);
284   }
285   UnregisteredEHFrameSections.clear();
286 }
287
288 std::unique_ptr<RuntimeDyldMachO>
289 RuntimeDyldMachO::create(Triple::ArchType Arch,
290                          RuntimeDyld::MemoryManager &MemMgr,
291                          RuntimeDyld::SymbolResolver &Resolver) {
292   switch (Arch) {
293   default:
294     llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
295     break;
296   case Triple::arm:
297     return make_unique<RuntimeDyldMachOARM>(MemMgr, Resolver);
298   case Triple::aarch64:
299     return make_unique<RuntimeDyldMachOAArch64>(MemMgr, Resolver);
300   case Triple::x86:
301     return make_unique<RuntimeDyldMachOI386>(MemMgr, Resolver);
302   case Triple::x86_64:
303     return make_unique<RuntimeDyldMachOX86_64>(MemMgr, Resolver);
304   }
305 }
306
307 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
308 RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
309   unsigned SectionStartIdx, SectionEndIdx;
310   std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
311   return llvm::make_unique<LoadedMachOObjectInfo>(*this, SectionStartIdx,
312                                                   SectionEndIdx);
313 }
314
315 } // end namespace llvm