[MCJIT] Significantly refactor the RuntimeDyldMachO class.
[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 "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringRef.h"
17
18 #include "Targets/RuntimeDyldMachOARM.h"
19 #include "Targets/RuntimeDyldMachOAArch64.h"
20 #include "Targets/RuntimeDyldMachOI386.h"
21 #include "Targets/RuntimeDyldMachOX86_64.h"
22
23 using namespace llvm;
24 using namespace llvm::object;
25
26 #define DEBUG_TYPE "dyld"
27
28 namespace llvm {
29
30 RelocationEntry
31 RuntimeDyldMachO::getBasicRelocationEntry(unsigned SectionID,
32                                           ObjectImage &ObjImg,
33                                           const relocation_iterator &RI) const {
34
35   const MachOObjectFile &Obj =
36       static_cast<const MachOObjectFile &>(*ObjImg.getObjectFile());
37   MachO::any_relocation_info RelInfo =
38       Obj.getRelocation(RI->getRawDataRefImpl());
39
40   const SectionEntry &Section = Sections[SectionID];
41   bool IsPCRel = Obj.getAnyRelocationPCRel(RelInfo);
42   unsigned Size = Obj.getAnyRelocationLength(RelInfo);
43   uint64_t Offset;
44   RI->getOffset(Offset);
45   uint8_t *LocalAddress = Section.Address + Offset;
46   unsigned NumBytes = 1 << Size;
47   uint64_t Addend = 0;
48   memcpy(&Addend, LocalAddress, NumBytes);
49   uint32_t RelType = Obj.getAnyRelocationType(RelInfo);
50
51   return RelocationEntry(SectionID, Offset, RelType, Addend, IsPCRel, Size);
52 }
53
54 RelocationValueRef RuntimeDyldMachO::getRelocationValueRef(
55     ObjectImage &ObjImg, const relocation_iterator &RI,
56     const RelocationEntry &RE, ObjSectionToIDMap &ObjSectionToID,
57     const SymbolTableMap &Symbols) {
58
59   const MachOObjectFile &Obj =
60       static_cast<const MachOObjectFile &>(*ObjImg.getObjectFile());
61   MachO::any_relocation_info RelInfo =
62       Obj.getRelocation(RI->getRawDataRefImpl());
63   RelocationValueRef Value;
64
65   bool IsExternal = Obj.getPlainRelocationExternal(RelInfo);
66   if (IsExternal) {
67     symbol_iterator Symbol = RI->getSymbol();
68     StringRef TargetName;
69     Symbol->getName(TargetName);
70     SymbolTableMap::const_iterator SI = Symbols.find(TargetName.data());
71     if (SI != Symbols.end()) {
72       Value.SectionID = SI->second.first;
73       Value.Addend = SI->second.second + RE.Addend;
74     } else {
75       SI = GlobalSymbolTable.find(TargetName.data());
76       if (SI != GlobalSymbolTable.end()) {
77         Value.SectionID = SI->second.first;
78         Value.Addend = SI->second.second + RE.Addend;
79       } else {
80         Value.SymbolName = TargetName.data();
81         Value.Addend = RE.Addend;
82       }
83     }
84   } else {
85     SectionRef Sec = Obj.getRelocationSection(RelInfo);
86     bool IsCode = false;
87     Sec.isText(IsCode);
88     Value.SectionID = findOrEmitSection(ObjImg, Sec, IsCode, ObjSectionToID);
89     uint64_t Addr;
90     Sec.getAddress(Addr);
91     Value.Addend = RE.Addend - Addr;
92   }
93
94   return Value;
95 }
96
97 void RuntimeDyldMachO::makeValueAddendPCRel(RelocationValueRef &Value,
98                                             ObjectImage &ObjImg,
99                                             const relocation_iterator &RI) {
100   const MachOObjectFile &Obj =
101       static_cast<const MachOObjectFile &>(*ObjImg.getObjectFile());
102   MachO::any_relocation_info RelInfo =
103       Obj.getRelocation(RI->getRawDataRefImpl());
104
105   bool IsPCRel = Obj.getAnyRelocationPCRel(RelInfo);
106   if (IsPCRel) {
107     uint64_t RelocAddr = 0;
108     RI->getAddress(RelocAddr);
109     unsigned RelocSize = Obj.getAnyRelocationLength(RelInfo);
110     Value.Addend += RelocAddr + (1 << RelocSize);
111   }
112 }
113
114 void RuntimeDyldMachO::dumpRelocationToResolve(const RelocationEntry &RE,
115                                                uint64_t Value) const {
116   const SectionEntry &Section = Sections[RE.SectionID];
117   uint8_t *LocalAddress = Section.Address + RE.Offset;
118   uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
119
120   dbgs() << "resolveRelocation Section: " << RE.SectionID
121          << " LocalAddress: " << format("%p", LocalAddress)
122          << " FinalAddress: " << format("%p", FinalAddress)
123          << " Value: " << format("%p", Value) << " Addend: " << RE.Addend
124          << " isPCRel: " << RE.IsPCRel << " MachoType: " << RE.RelType
125          << " Size: " << (1 << RE.Size) << "\n";
126 }
127
128 bool RuntimeDyldMachO::writeBytesUnaligned(uint8_t *Addr, uint64_t Value,
129                                            unsigned Size) {
130   for (unsigned i = 0; i < Size; ++i) {
131     *Addr++ = (uint8_t)Value;
132     Value >>= 8;
133   }
134
135   return false;
136 }
137
138 bool
139 RuntimeDyldMachO::isCompatibleFormat(const ObjectBuffer *InputBuffer) const {
140   if (InputBuffer->getBufferSize() < 4)
141     return false;
142   StringRef Magic(InputBuffer->getBufferStart(), 4);
143   if (Magic == "\xFE\xED\xFA\xCE")
144     return true;
145   if (Magic == "\xCE\xFA\xED\xFE")
146     return true;
147   if (Magic == "\xFE\xED\xFA\xCF")
148     return true;
149   if (Magic == "\xCF\xFA\xED\xFE")
150     return true;
151   return false;
152 }
153
154 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile *Obj) const {
155   return Obj->isMachO();
156 }
157
158 static unsigned char *processFDE(unsigned char *P, intptr_t DeltaForText,
159                                  intptr_t DeltaForEH) {
160   DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
161                << ", Delta for EH: " << DeltaForEH << "\n");
162   uint32_t Length = *((uint32_t *)P);
163   P += 4;
164   unsigned char *Ret = P + Length;
165   uint32_t Offset = *((uint32_t *)P);
166   if (Offset == 0) // is a CIE
167     return Ret;
168
169   P += 4;
170   intptr_t FDELocation = *((intptr_t *)P);
171   intptr_t NewLocation = FDELocation - DeltaForText;
172   *((intptr_t *)P) = NewLocation;
173   P += sizeof(intptr_t);
174
175   // Skip the FDE address range
176   P += sizeof(intptr_t);
177
178   uint8_t Augmentationsize = *P;
179   P += 1;
180   if (Augmentationsize != 0) {
181     intptr_t LSDA = *((intptr_t *)P);
182     intptr_t NewLSDA = LSDA - DeltaForEH;
183     *((intptr_t *)P) = NewLSDA;
184   }
185
186   return Ret;
187 }
188
189 static intptr_t computeDelta(SectionEntry *A, SectionEntry *B) {
190   intptr_t ObjDistance = A->ObjAddress - B->ObjAddress;
191   intptr_t MemDistance = A->LoadAddress - B->LoadAddress;
192   return ObjDistance - MemDistance;
193 }
194
195 void RuntimeDyldMachO::registerEHFrames() {
196
197   if (!MemMgr)
198     return;
199   for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
200     EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
201     if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
202         SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
203       continue;
204     SectionEntry *Text = &Sections[SectionInfo.TextSID];
205     SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
206     SectionEntry *ExceptTab = nullptr;
207     if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
208       ExceptTab = &Sections[SectionInfo.ExceptTabSID];
209
210     intptr_t DeltaForText = computeDelta(Text, EHFrame);
211     intptr_t DeltaForEH = 0;
212     if (ExceptTab)
213       DeltaForEH = computeDelta(ExceptTab, EHFrame);
214
215     unsigned char *P = EHFrame->Address;
216     unsigned char *End = P + EHFrame->Size;
217     do {
218       P = processFDE(P, DeltaForText, DeltaForEH);
219     } while (P != End);
220
221     MemMgr->registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
222                              EHFrame->Size);
223   }
224   UnregisteredEHFrameSections.clear();
225 }
226
227 std::unique_ptr<RuntimeDyldMachO>
228 llvm::RuntimeDyldMachO::create(Triple::ArchType Arch, RTDyldMemoryManager *MM) {
229   switch (Arch) {
230   default:
231     llvm_unreachable("Unsupported target for RuntimeDyldMachO.");
232     break;
233   case Triple::arm: return make_unique<RuntimeDyldMachOARM>(MM);
234   case Triple::arm64: return make_unique<RuntimeDyldMachOAArch64>(MM);
235   case Triple::x86: return make_unique<RuntimeDyldMachOI386>(MM);
236   case Triple::x86_64: return make_unique<RuntimeDyldMachOX86_64>(MM);
237   }
238 }
239
240 } // end namespace llvm