[RuntimeDyld] clang-format files.
[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 #define DEBUG_TYPE "dyld"
15 #include "RuntimeDyldMachO.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringRef.h"
18 using namespace llvm;
19 using namespace llvm::object;
20
21 namespace llvm {
22
23 static unsigned char *processFDE(unsigned char *P, intptr_t DeltaForText,
24                                  intptr_t DeltaForEH) {
25   uint32_t Length = *((uint32_t *)P);
26   P += 4;
27   unsigned char *Ret = P + Length;
28   uint32_t Offset = *((uint32_t *)P);
29   if (Offset == 0) // is a CIE
30     return Ret;
31
32   P += 4;
33   intptr_t FDELocation = *((intptr_t *)P);
34   intptr_t NewLocation = FDELocation - DeltaForText;
35   *((intptr_t *)P) = NewLocation;
36   P += sizeof(intptr_t);
37
38   // Skip the FDE address range
39   P += sizeof(intptr_t);
40
41   uint8_t Augmentationsize = *P;
42   P += 1;
43   if (Augmentationsize != 0) {
44     intptr_t LSDA = *((intptr_t *)P);
45     intptr_t NewLSDA = LSDA - DeltaForEH;
46     *((intptr_t *)P) = NewLSDA;
47   }
48
49   return Ret;
50 }
51
52 static intptr_t computeDelta(SectionEntry *A, SectionEntry *B) {
53   intptr_t ObjDistance = A->ObjAddress - B->ObjAddress;
54   intptr_t MemDistance = A->LoadAddress - B->LoadAddress;
55   return ObjDistance - MemDistance;
56 }
57
58 void RuntimeDyldMachO::registerEHFrames() {
59
60   if (!MemMgr)
61     return;
62   for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
63     EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
64     if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
65         SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
66       continue;
67     SectionEntry *Text = &Sections[SectionInfo.TextSID];
68     SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
69     SectionEntry *ExceptTab = NULL;
70     if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
71       ExceptTab = &Sections[SectionInfo.ExceptTabSID];
72
73     intptr_t DeltaForText = computeDelta(Text, EHFrame);
74     intptr_t DeltaForEH = 0;
75     if (ExceptTab)
76       DeltaForEH = computeDelta(ExceptTab, EHFrame);
77
78     unsigned char *P = EHFrame->Address;
79     unsigned char *End = P + EHFrame->Size;
80     do {
81       P = processFDE(P, DeltaForText, DeltaForEH);
82     } while (P != End);
83
84     MemMgr->registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
85                              EHFrame->Size);
86   }
87   UnregisteredEHFrameSections.clear();
88 }
89
90 void RuntimeDyldMachO::finalizeLoad(ObjSectionToIDMap &SectionMap) {
91   unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
92   unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
93   unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
94   ObjSectionToIDMap::iterator i, e;
95   for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
96     const SectionRef &Section = i->first;
97     StringRef Name;
98     Section.getName(Name);
99     if (Name == "__eh_frame")
100       EHFrameSID = i->second;
101     else if (Name == "__text")
102       TextSID = i->second;
103     else if (Name == "__gcc_except_tab")
104       ExceptTabSID = i->second;
105   }
106   UnregisteredEHFrameSections.push_back(
107       EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
108 }
109
110 // The target location for the relocation is described by RE.SectionID and
111 // RE.Offset.  RE.SectionID can be used to find the SectionEntry.  Each
112 // SectionEntry has three members describing its location.
113 // SectionEntry::Address is the address at which the section has been loaded
114 // into memory in the current (host) process.  SectionEntry::LoadAddress is the
115 // address that the section will have in the target process.
116 // SectionEntry::ObjAddress is the address of the bits for this section in the
117 // original emitted object image (also in the current address space).
118 //
119 // Relocations will be applied as if the section were loaded at
120 // SectionEntry::LoadAddress, but they will be applied at an address based
121 // on SectionEntry::Address.  SectionEntry::ObjAddress will be used to refer to
122 // Target memory contents if they are required for value calculations.
123 //
124 // The Value parameter here is the load address of the symbol for the
125 // relocation to be applied.  For relocations which refer to symbols in the
126 // current object Value will be the LoadAddress of the section in which
127 // the symbol resides (RE.Addend provides additional information about the
128 // symbol location).  For external symbols, Value will be the address of the
129 // symbol in the target address space.
130 void RuntimeDyldMachO::resolveRelocation(const RelocationEntry &RE,
131                                          uint64_t Value) {
132   const SectionEntry &Section = Sections[RE.SectionID];
133   return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
134                            RE.IsPCRel, RE.Size);
135 }
136
137 void RuntimeDyldMachO::resolveRelocation(const SectionEntry &Section,
138                                          uint64_t Offset, uint64_t Value,
139                                          uint32_t Type, int64_t Addend,
140                                          bool isPCRel, unsigned LogSize) {
141   uint8_t *LocalAddress = Section.Address + Offset;
142   uint64_t FinalAddress = Section.LoadAddress + Offset;
143   unsigned MachoType = Type;
144   unsigned Size = 1 << LogSize;
145
146   DEBUG(dbgs() << "resolveRelocation LocalAddress: "
147                << format("%p", LocalAddress)
148                << " FinalAddress: " << format("%p", FinalAddress)
149                << " Value: " << format("%p", Value) << " Addend: " << Addend
150                << " isPCRel: " << isPCRel << " MachoType: " << MachoType
151                << " Size: " << Size << "\n");
152
153   // This just dispatches to the proper target specific routine.
154   switch (Arch) {
155   default:
156     llvm_unreachable("Unsupported CPU type!");
157   case Triple::x86_64:
158     resolveX86_64Relocation(LocalAddress, FinalAddress, (uintptr_t)Value,
159                             isPCRel, MachoType, Size, Addend);
160     break;
161   case Triple::x86:
162     resolveI386Relocation(LocalAddress, FinalAddress, (uintptr_t)Value, isPCRel,
163                           MachoType, Size, Addend);
164     break;
165   case Triple::arm: // Fall through.
166   case Triple::thumb:
167     resolveARMRelocation(LocalAddress, FinalAddress, (uintptr_t)Value, isPCRel,
168                          MachoType, Size, Addend);
169     break;
170   }
171 }
172
173 bool RuntimeDyldMachO::resolveI386Relocation(uint8_t *LocalAddress,
174                                              uint64_t FinalAddress,
175                                              uint64_t Value, bool isPCRel,
176                                              unsigned Type, unsigned Size,
177                                              int64_t Addend) {
178   if (isPCRel)
179     Value -= FinalAddress + 4; // see resolveX86_64Relocation
180
181   switch (Type) {
182   default:
183     llvm_unreachable("Invalid relocation type!");
184   case MachO::GENERIC_RELOC_VANILLA: {
185     uint8_t *p = LocalAddress;
186     uint64_t ValueToWrite = Value + Addend;
187     for (unsigned i = 0; i < Size; ++i) {
188       *p++ = (uint8_t)(ValueToWrite & 0xff);
189       ValueToWrite >>= 8;
190     }
191     return false;
192   }
193   case MachO::GENERIC_RELOC_SECTDIFF:
194   case MachO::GENERIC_RELOC_LOCAL_SECTDIFF:
195   case MachO::GENERIC_RELOC_PB_LA_PTR:
196     return Error("Relocation type not implemented yet!");
197   }
198 }
199
200 bool RuntimeDyldMachO::resolveX86_64Relocation(uint8_t *LocalAddress,
201                                                uint64_t FinalAddress,
202                                                uint64_t Value, bool isPCRel,
203                                                unsigned Type, unsigned Size,
204                                                int64_t Addend) {
205   // If the relocation is PC-relative, the value to be encoded is the
206   // pointer difference.
207   if (isPCRel)
208     // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
209     // address. Is that expected? Only for branches, perhaps?
210     Value -= FinalAddress + 4;
211
212   switch (Type) {
213   default:
214     llvm_unreachable("Invalid relocation type!");
215   case MachO::X86_64_RELOC_SIGNED_1:
216   case MachO::X86_64_RELOC_SIGNED_2:
217   case MachO::X86_64_RELOC_SIGNED_4:
218   case MachO::X86_64_RELOC_SIGNED:
219   case MachO::X86_64_RELOC_UNSIGNED:
220   case MachO::X86_64_RELOC_BRANCH: {
221     Value += Addend;
222     // Mask in the target value a byte at a time (we don't have an alignment
223     // guarantee for the target address, so this is safest).
224     uint8_t *p = (uint8_t *)LocalAddress;
225     for (unsigned i = 0; i < Size; ++i) {
226       *p++ = (uint8_t)Value;
227       Value >>= 8;
228     }
229     return false;
230   }
231   case MachO::X86_64_RELOC_GOT_LOAD:
232   case MachO::X86_64_RELOC_GOT:
233   case MachO::X86_64_RELOC_SUBTRACTOR:
234   case MachO::X86_64_RELOC_TLV:
235     return Error("Relocation type not implemented yet!");
236   }
237 }
238
239 bool RuntimeDyldMachO::resolveARMRelocation(uint8_t *LocalAddress,
240                                             uint64_t FinalAddress,
241                                             uint64_t Value, bool isPCRel,
242                                             unsigned Type, unsigned Size,
243                                             int64_t Addend) {
244   // If the relocation is PC-relative, the value to be encoded is the
245   // pointer difference.
246   if (isPCRel) {
247     Value -= FinalAddress;
248     // ARM PCRel relocations have an effective-PC offset of two instructions
249     // (four bytes in Thumb mode, 8 bytes in ARM mode).
250     // FIXME: For now, assume ARM mode.
251     Value -= 8;
252   }
253
254   switch (Type) {
255   default:
256     llvm_unreachable("Invalid relocation type!");
257   case MachO::ARM_RELOC_VANILLA: {
258     // Mask in the target value a byte at a time (we don't have an alignment
259     // guarantee for the target address, so this is safest).
260     uint8_t *p = (uint8_t *)LocalAddress;
261     for (unsigned i = 0; i < Size; ++i) {
262       *p++ = (uint8_t)Value;
263       Value >>= 8;
264     }
265     break;
266   }
267   case MachO::ARM_RELOC_BR24: {
268     // Mask the value into the target address. We know instructions are
269     // 32-bit aligned, so we can do it all at once.
270     uint32_t *p = (uint32_t *)LocalAddress;
271     // The low two bits of the value are not encoded.
272     Value >>= 2;
273     // Mask the value to 24 bits.
274     Value &= 0xffffff;
275     // FIXME: If the destination is a Thumb function (and the instruction
276     // is a non-predicated BL instruction), we need to change it to a BLX
277     // instruction instead.
278
279     // Insert the value into the instruction.
280     *p = (*p & ~0xffffff) | Value;
281     break;
282   }
283   case MachO::ARM_THUMB_RELOC_BR22:
284   case MachO::ARM_THUMB_32BIT_BRANCH:
285   case MachO::ARM_RELOC_HALF:
286   case MachO::ARM_RELOC_HALF_SECTDIFF:
287   case MachO::ARM_RELOC_PAIR:
288   case MachO::ARM_RELOC_SECTDIFF:
289   case MachO::ARM_RELOC_LOCAL_SECTDIFF:
290   case MachO::ARM_RELOC_PB_LA_PTR:
291     return Error("Relocation type not implemented yet!");
292   }
293   return false;
294 }
295
296 relocation_iterator RuntimeDyldMachO::processRelocationRef(
297     unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
298     ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
299     StubMap &Stubs) {
300   const ObjectFile *OF = Obj.getObjectFile();
301   const MachOObjectFile *MachO = static_cast<const MachOObjectFile *>(OF);
302   MachO::any_relocation_info RE =
303       MachO->getRelocation(RelI->getRawDataRefImpl());
304
305   uint32_t RelType = MachO->getAnyRelocationType(RE);
306
307   // FIXME: Properly handle scattered relocations.
308   //        For now, optimistically skip these: they can often be ignored, as
309   //        the static linker will already have applied the relocation, and it
310   //        only needs to be reapplied if symbols move relative to one another.
311   //        Note: This will fail horribly where the relocations *do* need to be
312   //        applied, but that was already the case.
313   if (MachO->isRelocationScattered(RE))
314     return ++RelI;
315
316   RelocationValueRef Value;
317   SectionEntry &Section = Sections[SectionID];
318
319   bool isExtern = MachO->getPlainRelocationExternal(RE);
320   bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
321   unsigned Size = MachO->getAnyRelocationLength(RE);
322   uint64_t Offset;
323   RelI->getOffset(Offset);
324   uint8_t *LocalAddress = Section.Address + Offset;
325   unsigned NumBytes = 1 << Size;
326   uint64_t Addend = 0;
327   memcpy(&Addend, LocalAddress, NumBytes);
328
329   if (isExtern) {
330     // Obtain the symbol name which is referenced in the relocation
331     symbol_iterator Symbol = RelI->getSymbol();
332     StringRef TargetName;
333     Symbol->getName(TargetName);
334     // First search for the symbol in the local symbol table
335     SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
336     if (lsi != Symbols.end()) {
337       Value.SectionID = lsi->second.first;
338       Value.Addend = lsi->second.second + Addend;
339     } else {
340       // Search for the symbol in the global symbol table
341       SymbolTableMap::const_iterator gsi =
342           GlobalSymbolTable.find(TargetName.data());
343       if (gsi != GlobalSymbolTable.end()) {
344         Value.SectionID = gsi->second.first;
345         Value.Addend = gsi->second.second + Addend;
346       } else {
347         Value.SymbolName = TargetName.data();
348         Value.Addend = Addend;
349       }
350     }
351   } else {
352     SectionRef Sec = MachO->getRelocationSection(RE);
353     bool IsCode = false;
354     Sec.isText(IsCode);
355     Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
356     uint64_t Addr;
357     Sec.getAddress(Addr);
358     Value.Addend = Addend - Addr;
359     if (IsPCRel)
360       Value.Addend += Offset + NumBytes;
361   }
362
363   if (Arch == Triple::x86_64 && (RelType == MachO::X86_64_RELOC_GOT ||
364                                  RelType == MachO::X86_64_RELOC_GOT_LOAD)) {
365     assert(IsPCRel);
366     assert(Size == 2);
367     StubMap::const_iterator i = Stubs.find(Value);
368     uint8_t *Addr;
369     if (i != Stubs.end()) {
370       Addr = Section.Address + i->second;
371     } else {
372       Stubs[Value] = Section.StubOffset;
373       uint8_t *GOTEntry = Section.Address + Section.StubOffset;
374       RelocationEntry RE(SectionID, Section.StubOffset,
375                          MachO::X86_64_RELOC_UNSIGNED, 0, false, 3);
376       if (Value.SymbolName)
377         addRelocationForSymbol(RE, Value.SymbolName);
378       else
379         addRelocationForSection(RE, Value.SectionID);
380       Section.StubOffset += 8;
381       Addr = GOTEntry;
382     }
383     resolveRelocation(Section, Offset, (uint64_t)Addr,
384                       MachO::X86_64_RELOC_UNSIGNED, Value.Addend, true, 2);
385   } else if (Arch == Triple::arm && (RelType & 0xf) == MachO::ARM_RELOC_BR24) {
386     // This is an ARM branch relocation, need to use a stub function.
387
388     //  Look up for existing stub.
389     StubMap::const_iterator i = Stubs.find(Value);
390     if (i != Stubs.end())
391       resolveRelocation(Section, Offset, (uint64_t)Section.Address + i->second,
392                         RelType, 0, IsPCRel, Size);
393     else {
394       // Create a new stub function.
395       Stubs[Value] = Section.StubOffset;
396       uint8_t *StubTargetAddr =
397           createStubFunction(Section.Address + Section.StubOffset);
398       RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
399                          MachO::GENERIC_RELOC_VANILLA, Value.Addend);
400       if (Value.SymbolName)
401         addRelocationForSymbol(RE, Value.SymbolName);
402       else
403         addRelocationForSection(RE, Value.SectionID);
404       resolveRelocation(Section, Offset,
405                         (uint64_t)Section.Address + Section.StubOffset, RelType,
406                         0, IsPCRel, Size);
407       Section.StubOffset += getMaxStubSize();
408     }
409   } else {
410     RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, IsPCRel, Size);
411     if (Value.SymbolName)
412       addRelocationForSymbol(RE, Value.SymbolName);
413     else
414       addRelocationForSection(RE, Value.SectionID);
415   }
416   return ++RelI;
417 }
418
419 bool
420 RuntimeDyldMachO::isCompatibleFormat(const ObjectBuffer *InputBuffer) const {
421   if (InputBuffer->getBufferSize() < 4)
422     return false;
423   StringRef Magic(InputBuffer->getBufferStart(), 4);
424   if (Magic == "\xFE\xED\xFA\xCE")
425     return true;
426   if (Magic == "\xCE\xFA\xED\xFE")
427     return true;
428   if (Magic == "\xFE\xED\xFA\xCF")
429     return true;
430   if (Magic == "\xCF\xFA\xED\xFE")
431     return true;
432   return false;
433 }
434
435 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile *Obj) const {
436   return Obj->isMachO();
437 }
438
439 } // end namespace llvm