796a69cc836e03a4782f3545e0d035be9a0e44d3
[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 : public RuntimeDyld::LoadedObjectInfo {
30 public:
31   LoadedMachOObjectInfo(RuntimeDyldImpl &RTDyld, unsigned BeginIdx,
32                         unsigned EndIdx)
33     : RuntimeDyld::LoadedObjectInfo(RTDyld, BeginIdx, EndIdx) {}
34
35   OwningBinary<ObjectFile>
36   getObjectForDebug(const ObjectFile &Obj) const override {
37     return OwningBinary<ObjectFile>();
38   }
39
40   RuntimeDyld::LoadedObjectInfo *clone() const { return new LoadedMachOObjectInfo(*this); }
41 };
42
43 }
44
45 namespace llvm {
46
47 int64_t RuntimeDyldMachO::memcpyAddend(const RelocationEntry &RE) const {
48   unsigned NumBytes = 1 << RE.Size;
49   uint8_t *Src = Sections[RE.SectionID].Address + RE.Offset;
50
51   return static_cast<int64_t>(readBytesUnaligned(Src, NumBytes));
52 }
53
54 RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
55     const ObjectFile &BaseTObj, const relocation_iterator &RI,
56     const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID) {
57
58   const MachOObjectFile &Obj =
59       static_cast<const MachOObjectFile &>(BaseTObj);
60   MachO::any_relocation_info RelInfo =
61       Obj.getRelocation(RI->getRawDataRefImpl());
62   RelocationValueRef Value;
63
64   bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
65   if (IsExternal) {
66     symbol_iterator Symbol = RI->getSymbol();
67     StringRef TargetName;
68     Symbol->getName(TargetName);
69     RTDyldSymbolTable::const_iterator SI =
70       GlobalSymbolTable.find(TargetName.data());
71     if (SI != GlobalSymbolTable.end()) {
72       const auto &SymInfo = SI->second;
73       Value.SectionID = SymInfo.getSectionID();
74       Value.Offset = SymInfo.getOffset() + RE.Addend;
75     } else {
76       Value.SymbolName = TargetName.data();
77       Value.Offset = RE.Addend;
78     }
79   } else {
80     SectionRef Sec = Obj.getAnyRelocationSection(RelInfo);
81     bool IsCode = Sec.isText();
82     Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
83     uint64_t Addr = Sec.getAddress();
84     Value.Offset = RE.Addend - Addr;
85   }
86
87   return Value;
88 }
89
90 void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
91                                             const ObjectFile &BaseTObj,
92                                             const relocation_iterator &RI,
93                                             unsigned OffsetToNextPC) {
94   const MachOObjectFile &Obj =
95       static_cast<const MachOObjectFile &>(BaseTObj);
96   MachO::any_relocation_info RelInfo =
97       Obj.getRelocation(RI->getRawDataRefImpl());
98
99   bool IsPCRel = Obj.getAnyRelocationPCRel(RelInfo);
100   if (IsPCRel) {
101     uint64_t RelocAddr = 0;
102     RI->getAddress(RelocAddr);
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     StringRef IndirectSymbolName;
168     SI->getName(IndirectSymbolName);
169     DEBUG(dbgs() << "  " << IndirectSymbolName << ": index " << SymbolIndex
170           << ", PT offset: " << PTEntryOffset << "\n");
171     RelocationEntry RE(PTSectionID, PTEntryOffset,
172                        MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
173     addRelocationForSymbol(RE, IndirectSymbolName);
174     PTEntryOffset += PTEntrySize;
175   }
176 }
177
178 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile &Obj) const {
179   return Obj.isMachO();
180 }
181
182 template <typename Impl>
183 void RuntimeDyldMachOCRTPBase<Impl>::finalizeLoad(const ObjectFile &Obj,
184                                                   ObjSectionToIDMap &SectionMap) {
185   unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
186   unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
187   unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
188
189   for (const auto &Section : Obj.sections()) {
190     StringRef Name;
191     Section.getName(Name);
192
193     // Force emission of the __text, __eh_frame, and __gcc_except_tab sections
194     // if they're present. Otherwise call down to the impl to handle other
195     // sections that have already been emitted.
196     if (Name == "__text")
197       TextSID = findOrEmitSection(Obj, Section, true, SectionMap);
198     else if (Name == "__eh_frame")
199       EHFrameSID = findOrEmitSection(Obj, Section, false, SectionMap);
200     else if (Name == "__gcc_except_tab")
201       ExceptTabSID = findOrEmitSection(Obj, Section, true, SectionMap);
202     else {
203       auto I = SectionMap.find(Section);
204       if (I != SectionMap.end())
205         impl().finalizeSection(Obj, I->second, Section);
206     }
207   }
208   UnregisteredEHFrameSections.push_back(
209     EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
210 }
211
212 template <typename Impl>
213 unsigned char *RuntimeDyldMachOCRTPBase<Impl>::processFDE(unsigned char *P,
214                                                           int64_t DeltaForText,
215                                                           int64_t DeltaForEH) {
216   typedef typename Impl::TargetPtrT TargetPtrT;
217
218   DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
219                << ", Delta for EH: " << DeltaForEH << "\n");
220   uint32_t Length = readBytesUnaligned(P, 4);
221   P += 4;
222   unsigned char *Ret = P + Length;
223   uint32_t Offset = readBytesUnaligned(P, 4);
224   if (Offset == 0) // is a CIE
225     return Ret;
226
227   P += 4;
228   TargetPtrT FDELocation = readBytesUnaligned(P, sizeof(TargetPtrT));
229   TargetPtrT NewLocation = FDELocation - DeltaForText;
230   writeBytesUnaligned(NewLocation, P, sizeof(TargetPtrT));
231
232   P += sizeof(TargetPtrT);
233
234   // Skip the FDE address range
235   P += sizeof(TargetPtrT);
236
237   uint8_t Augmentationsize = *P;
238   P += 1;
239   if (Augmentationsize != 0) {
240     TargetPtrT LSDA = readBytesUnaligned(P, sizeof(TargetPtrT));
241     TargetPtrT NewLSDA = LSDA - DeltaForEH;
242     writeBytesUnaligned(NewLSDA, P, sizeof(TargetPtrT));
243   }
244
245   return Ret;
246 }
247
248 static int64_t computeDelta(SectionEntry *A, SectionEntry *B) {
249   int64_t ObjDistance =
250     static_cast<int64_t>(A->ObjAddress) - static_cast<int64_t>(B->ObjAddress);
251   int64_t MemDistance = A->LoadAddress - B->LoadAddress;
252   return ObjDistance - MemDistance;
253 }
254
255 template <typename Impl>
256 void RuntimeDyldMachOCRTPBase<Impl>::registerEHFrames() {
257
258   for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
259     EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
260     if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
261         SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
262       continue;
263     SectionEntry *Text = &Sections[SectionInfo.TextSID];
264     SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
265     SectionEntry *ExceptTab = nullptr;
266     if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
267       ExceptTab = &Sections[SectionInfo.ExceptTabSID];
268
269     int64_t DeltaForText = computeDelta(Text, EHFrame);
270     int64_t DeltaForEH = 0;
271     if (ExceptTab)
272       DeltaForEH = computeDelta(ExceptTab, EHFrame);
273
274     unsigned char *P = EHFrame->Address;
275     unsigned char *End = P + EHFrame->Size;
276     do {
277       P = processFDE(P, DeltaForText, DeltaForEH);
278     } while (P != End);
279
280     MemMgr.registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
281                             EHFrame->Size);
282   }
283   UnregisteredEHFrameSections.clear();
284 }
285
286 std::unique_ptr<RuntimeDyldMachO>
287 RuntimeDyldMachO::create(Triple::ArchType Arch,
288                          RuntimeDyld::MemoryManager &MemMgr,
289                          RuntimeDyld::SymbolResolver &Resolver) {
290   switch (Arch) {
291   default:
292     llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
293     break;
294   case Triple::arm:
295     return make_unique<RuntimeDyldMachOARM>(MemMgr, Resolver);
296   case Triple::aarch64:
297     return make_unique<RuntimeDyldMachOAArch64>(MemMgr, Resolver);
298   case Triple::x86:
299     return make_unique<RuntimeDyldMachOI386>(MemMgr, Resolver);
300   case Triple::x86_64:
301     return make_unique<RuntimeDyldMachOX86_64>(MemMgr, Resolver);
302   }
303 }
304
305 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
306 RuntimeDyldMachO::loadObject(const object::ObjectFile &O) {
307   unsigned SectionStartIdx, SectionEndIdx;
308   std::tie(SectionStartIdx, SectionEndIdx) = loadObjectImpl(O);
309   return llvm::make_unique<LoadedMachOObjectInfo>(*this, SectionStartIdx,
310                                                   SectionEndIdx);
311 }
312
313 } // end namespace llvm