1 //===-- RuntimeDyldMachO.cpp - Run-time dynamic linker for MC-JIT -*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implementation of the MC-JIT runtime dynamic linker.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dyld"
15 #include "RuntimeDyldMachO.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
20 using namespace llvm::object;
24 static unsigned char *processFDE(unsigned char *P, intptr_t DeltaForText, intptr_t DeltaForEH) {
25 uint32_t Length = *((uint32_t*)P);
27 unsigned char *Ret = P + Length;
28 uint32_t Offset = *((uint32_t*)P);
29 if (Offset == 0) // is a CIE
33 intptr_t FDELocation = *((intptr_t*)P);
34 intptr_t NewLocation = FDELocation - DeltaForText;
35 *((intptr_t*)P) = NewLocation;
36 P += sizeof(intptr_t);
38 // Skip the FDE address range
39 P += sizeof(intptr_t);
41 uint8_t Augmentationsize = *P;
43 if (Augmentationsize != 0) {
44 intptr_t LSDA = *((intptr_t*)P);
45 intptr_t NewLSDA = LSDA - DeltaForEH;
46 *((intptr_t*)P) = NewLSDA;
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;
58 void RuntimeDyldMachO::registerEHFrames() {
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)
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];
73 intptr_t DeltaForText = computeDelta(Text, EHFrame);
74 intptr_t DeltaForEH = 0;
76 DeltaForEH = computeDelta(ExceptTab, EHFrame);
78 unsigned char *P = EHFrame->Address;
79 unsigned char *End = P + EHFrame->Size;
81 P = processFDE(P, DeltaForText, DeltaForEH);
84 MemMgr->registerEHFrames(EHFrame->Address,
88 UnregisteredEHFrameSections.clear();
91 void RuntimeDyldMachO::finalizeLoad(ObjSectionToIDMap &SectionMap) {
92 unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
93 unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
94 unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
95 ObjSectionToIDMap::iterator i, e;
96 for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
97 const SectionRef &Section = i->first;
99 Section.getName(Name);
100 if (Name == "__eh_frame")
101 EHFrameSID = i->second;
102 else if (Name == "__text")
104 else if (Name == "__gcc_except_tab")
105 ExceptTabSID = i->second;
107 UnregisteredEHFrameSections.push_back(EHFrameRelatedSections(EHFrameSID,
112 // The target location for the relocation is described by RE.SectionID and
113 // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
114 // SectionEntry has three members describing its location.
115 // SectionEntry::Address is the address at which the section has been loaded
116 // into memory in the current (host) process. SectionEntry::LoadAddress is the
117 // address that the section will have in the target process.
118 // SectionEntry::ObjAddress is the address of the bits for this section in the
119 // original emitted object image (also in the current address space).
121 // Relocations will be applied as if the section were loaded at
122 // SectionEntry::LoadAddress, but they will be applied at an address based
123 // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
124 // Target memory contents if they are required for value calculations.
126 // The Value parameter here is the load address of the symbol for the
127 // relocation to be applied. For relocations which refer to symbols in the
128 // current object Value will be the LoadAddress of the section in which
129 // the symbol resides (RE.Addend provides additional information about the
130 // symbol location). For external symbols, Value will be the address of the
131 // symbol in the target address space.
132 void RuntimeDyldMachO::resolveRelocation(const RelocationEntry &RE,
134 const SectionEntry &Section = Sections[RE.SectionID];
135 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
136 RE.IsPCRel, RE.Size);
139 void RuntimeDyldMachO::resolveRelocation(const SectionEntry &Section,
146 uint8_t *LocalAddress = Section.Address + Offset;
147 uint64_t FinalAddress = Section.LoadAddress + Offset;
148 unsigned MachoType = Type;
149 unsigned Size = 1 << LogSize;
151 DEBUG(dbgs() << "resolveRelocation LocalAddress: "
152 << format("%p", LocalAddress)
153 << " FinalAddress: " << format("%p", FinalAddress)
154 << " Value: " << format("%p", Value)
155 << " Addend: " << Addend
156 << " isPCRel: " << isPCRel
157 << " MachoType: " << MachoType
161 // This just dispatches to the proper target specific routine.
163 default: llvm_unreachable("Unsupported CPU type!");
165 resolveX86_64Relocation(LocalAddress,
174 resolveI386Relocation(LocalAddress,
182 case Triple::arm: // Fall through.
184 resolveARMRelocation(LocalAddress,
195 bool RuntimeDyldMachO::resolveI386Relocation(uint8_t *LocalAddress,
196 uint64_t FinalAddress,
203 Value -= FinalAddress + 4; // see resolveX86_64Relocation
207 llvm_unreachable("Invalid relocation type!");
208 case MachO::GENERIC_RELOC_VANILLA: {
209 uint8_t *p = LocalAddress;
210 uint64_t ValueToWrite = Value + Addend;
211 for (unsigned i = 0; i < Size; ++i) {
212 *p++ = (uint8_t)(ValueToWrite & 0xff);
217 case MachO::GENERIC_RELOC_SECTDIFF:
218 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF:
219 case MachO::GENERIC_RELOC_PB_LA_PTR:
220 return Error("Relocation type not implemented yet!");
224 bool RuntimeDyldMachO::resolveX86_64Relocation(uint8_t *LocalAddress,
225 uint64_t FinalAddress,
231 // If the relocation is PC-relative, the value to be encoded is the
232 // pointer difference.
234 // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
235 // address. Is that expected? Only for branches, perhaps?
236 Value -= FinalAddress + 4;
240 llvm_unreachable("Invalid relocation type!");
241 case MachO::X86_64_RELOC_SIGNED_1:
242 case MachO::X86_64_RELOC_SIGNED_2:
243 case MachO::X86_64_RELOC_SIGNED_4:
244 case MachO::X86_64_RELOC_SIGNED:
245 case MachO::X86_64_RELOC_UNSIGNED:
246 case MachO::X86_64_RELOC_BRANCH: {
248 // Mask in the target value a byte at a time (we don't have an alignment
249 // guarantee for the target address, so this is safest).
250 uint8_t *p = (uint8_t*)LocalAddress;
251 for (unsigned i = 0; i < Size; ++i) {
252 *p++ = (uint8_t)Value;
257 case MachO::X86_64_RELOC_GOT_LOAD:
258 case MachO::X86_64_RELOC_GOT:
259 case MachO::X86_64_RELOC_SUBTRACTOR:
260 case MachO::X86_64_RELOC_TLV:
261 return Error("Relocation type not implemented yet!");
265 bool RuntimeDyldMachO::resolveARMRelocation(uint8_t *LocalAddress,
266 uint64_t FinalAddress,
272 // If the relocation is PC-relative, the value to be encoded is the
273 // pointer difference.
275 Value -= FinalAddress;
276 // ARM PCRel relocations have an effective-PC offset of two instructions
277 // (four bytes in Thumb mode, 8 bytes in ARM mode).
278 // FIXME: For now, assume ARM mode.
284 llvm_unreachable("Invalid relocation type!");
285 case MachO::ARM_RELOC_VANILLA: {
286 // Mask in the target value a byte at a time (we don't have an alignment
287 // guarantee for the target address, so this is safest).
288 uint8_t *p = (uint8_t*)LocalAddress;
289 for (unsigned i = 0; i < Size; ++i) {
290 *p++ = (uint8_t)Value;
295 case MachO::ARM_RELOC_BR24: {
296 // Mask the value into the target address. We know instructions are
297 // 32-bit aligned, so we can do it all at once.
298 uint32_t *p = (uint32_t*)LocalAddress;
299 // The low two bits of the value are not encoded.
301 // Mask the value to 24 bits.
303 // FIXME: If the destination is a Thumb function (and the instruction
304 // is a non-predicated BL instruction), we need to change it to a BLX
305 // instruction instead.
307 // Insert the value into the instruction.
308 *p = (*p & ~0xffffff) | Value;
311 case MachO::ARM_THUMB_RELOC_BR22:
312 case MachO::ARM_THUMB_32BIT_BRANCH:
313 case MachO::ARM_RELOC_HALF:
314 case MachO::ARM_RELOC_HALF_SECTDIFF:
315 case MachO::ARM_RELOC_PAIR:
316 case MachO::ARM_RELOC_SECTDIFF:
317 case MachO::ARM_RELOC_LOCAL_SECTDIFF:
318 case MachO::ARM_RELOC_PB_LA_PTR:
319 return Error("Relocation type not implemented yet!");
324 void RuntimeDyldMachO::processRelocationRef(unsigned SectionID,
327 ObjSectionToIDMap &ObjSectionToID,
328 const SymbolTableMap &Symbols,
330 const ObjectFile *OF = Obj.getObjectFile();
331 const MachOObjectFile *MachO = static_cast<const MachOObjectFile*>(OF);
332 MachO::any_relocation_info RE= MachO->getRelocation(RelI.getRawDataRefImpl());
334 uint32_t RelType = MachO->getAnyRelocationType(RE);
336 // FIXME: Properly handle scattered relocations.
337 // For now, optimistically skip these: they can often be ignored, as
338 // the static linker will already have applied the relocation, and it
339 // only needs to be reapplied if symbols move relative to one another.
340 // Note: This will fail horribly where the relocations *do* need to be
341 // applied, but that was already the case.
342 if (MachO->isRelocationScattered(RE))
345 RelocationValueRef Value;
346 SectionEntry &Section = Sections[SectionID];
348 bool isExtern = MachO->getPlainRelocationExternal(RE);
349 bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
350 unsigned Size = MachO->getAnyRelocationLength(RE);
352 RelI.getOffset(Offset);
353 uint8_t *LocalAddress = Section.Address + Offset;
354 unsigned NumBytes = 1 << Size;
356 memcpy(&Addend, LocalAddress, NumBytes);
359 // Obtain the symbol name which is referenced in the relocation
360 symbol_iterator Symbol = RelI.getSymbol();
361 StringRef TargetName;
362 Symbol->getName(TargetName);
363 // First search for the symbol in the local symbol table
364 SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
365 if (lsi != Symbols.end()) {
366 Value.SectionID = lsi->second.first;
367 Value.Addend = lsi->second.second + Addend;
369 // Search for the symbol in the global symbol table
370 SymbolTableMap::const_iterator gsi = GlobalSymbolTable.find(TargetName.data());
371 if (gsi != GlobalSymbolTable.end()) {
372 Value.SectionID = gsi->second.first;
373 Value.Addend = gsi->second.second + Addend;
375 Value.SymbolName = TargetName.data();
376 Value.Addend = Addend;
380 SectionRef Sec = MachO->getRelocationSection(RE);
381 Value.SectionID = findOrEmitSection(Obj, Sec, true, ObjSectionToID);
383 Sec.getAddress(Addr);
384 Value.Addend = Addend - Addr;
387 if (Arch == Triple::x86_64 && (RelType == MachO::X86_64_RELOC_GOT ||
388 RelType == MachO::X86_64_RELOC_GOT_LOAD)) {
391 StubMap::const_iterator i = Stubs.find(Value);
393 if (i != Stubs.end()) {
394 Addr = Section.Address + i->second;
396 Stubs[Value] = Section.StubOffset;
397 uint8_t *GOTEntry = Section.Address + Section.StubOffset;
398 RelocationEntry RE(SectionID, Section.StubOffset,
399 MachO::X86_64_RELOC_UNSIGNED, 0, false, 3);
400 if (Value.SymbolName)
401 addRelocationForSymbol(RE, Value.SymbolName);
403 addRelocationForSection(RE, Value.SectionID);
404 Section.StubOffset += 8;
407 resolveRelocation(Section, Offset, (uint64_t)Addr,
408 MachO::X86_64_RELOC_UNSIGNED, Value.Addend, true, 2);
409 } else if (Arch == Triple::arm &&
410 (RelType & 0xf) == MachO::ARM_RELOC_BR24) {
411 // This is an ARM branch relocation, need to use a stub function.
413 // Look up for existing stub.
414 StubMap::const_iterator i = Stubs.find(Value);
415 if (i != Stubs.end())
416 resolveRelocation(Section, Offset,
417 (uint64_t)Section.Address + i->second,
418 RelType, 0, IsPCRel, Size);
420 // Create a new stub function.
421 Stubs[Value] = Section.StubOffset;
422 uint8_t *StubTargetAddr = createStubFunction(Section.Address +
424 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
425 MachO::GENERIC_RELOC_VANILLA, Value.Addend);
426 if (Value.SymbolName)
427 addRelocationForSymbol(RE, Value.SymbolName);
429 addRelocationForSection(RE, Value.SectionID);
430 resolveRelocation(Section, Offset,
431 (uint64_t)Section.Address + Section.StubOffset,
432 RelType, 0, IsPCRel, Size);
433 Section.StubOffset += getMaxStubSize();
436 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend,
438 if (Value.SymbolName)
439 addRelocationForSymbol(RE, Value.SymbolName);
441 addRelocationForSection(RE, Value.SectionID);
446 bool RuntimeDyldMachO::isCompatibleFormat(
447 const ObjectBuffer *InputBuffer) const {
448 if (InputBuffer->getBufferSize() < 4)
450 StringRef Magic(InputBuffer->getBufferStart(), 4);
451 if (Magic == "\xFE\xED\xFA\xCE") return true;
452 if (Magic == "\xCE\xFA\xED\xFE") return true;
453 if (Magic == "\xFE\xED\xFA\xCF") return true;
454 if (Magic == "\xCF\xFA\xED\xFE") return true;
458 bool RuntimeDyldMachO::isCompatibleFile(
459 const object::ObjectFile *Obj) const {
460 return Obj->isMachO();
463 } // end namespace llvm