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