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/STLExtras.h"
17 #include "llvm/ADT/StringRef.h"
19 using namespace llvm::object;
23 static unsigned char *processFDE(unsigned char *P, intptr_t DeltaForText, intptr_t DeltaForEH) {
24 uint32_t Length = *((uint32_t*)P);
26 unsigned char *Ret = P + Length;
27 uint32_t Offset = *((uint32_t*)P);
28 if (Offset == 0) // is a CIE
32 intptr_t FDELocation = *((intptr_t*)P);
33 intptr_t NewLocation = FDELocation - DeltaForText;
34 *((intptr_t*)P) = NewLocation;
35 P += sizeof(intptr_t);
37 // Skip the FDE address range
38 P += sizeof(intptr_t);
40 uint8_t Augmentationsize = *P;
42 if (Augmentationsize != 0) {
43 intptr_t LSDA = *((intptr_t*)P);
44 intptr_t NewLSDA = LSDA - DeltaForEH;
45 *((intptr_t*)P) = NewLSDA;
51 static intptr_t computeDelta(SectionEntry *A, SectionEntry *B) {
52 intptr_t ObjDistance = A->ObjAddress - B->ObjAddress;
53 intptr_t MemDistance = A->LoadAddress - B->LoadAddress;
54 return ObjDistance - MemDistance;
57 void RuntimeDyldMachO::registerEHFrames() {
61 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
62 EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
63 if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
64 SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
66 SectionEntry *Text = &Sections[SectionInfo.TextSID];
67 SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
68 SectionEntry *ExceptTab = NULL;
69 if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
70 ExceptTab = &Sections[SectionInfo.ExceptTabSID];
72 intptr_t DeltaForText = computeDelta(Text, EHFrame);
73 intptr_t DeltaForEH = 0;
75 DeltaForEH = computeDelta(ExceptTab, EHFrame);
77 unsigned char *P = EHFrame->Address;
78 unsigned char *End = P + EHFrame->Size;
80 P = processFDE(P, DeltaForText, DeltaForEH);
83 MemMgr->registerEHFrames(EHFrame->Address,
87 UnregisteredEHFrameSections.clear();
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;
98 Section.getName(Name);
99 if (Name == "__eh_frame")
100 EHFrameSID = i->second;
101 else if (Name == "__text")
103 else if (Name == "__gcc_except_tab")
104 ExceptTabSID = i->second;
106 UnregisteredEHFrameSections.push_back(EHFrameRelatedSections(EHFrameSID,
111 // The target location for the relocation is described by RE.SectionID and
112 // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
113 // SectionEntry has three members describing its location.
114 // SectionEntry::Address is the address at which the section has been loaded
115 // into memory in the current (host) process. SectionEntry::LoadAddress is the
116 // address that the section will have in the target process.
117 // SectionEntry::ObjAddress is the address of the bits for this section in the
118 // original emitted object image (also in the current address space).
120 // Relocations will be applied as if the section were loaded at
121 // SectionEntry::LoadAddress, but they will be applied at an address based
122 // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
123 // Target memory contents if they are required for value calculations.
125 // The Value parameter here is the load address of the symbol for the
126 // relocation to be applied. For relocations which refer to symbols in the
127 // current object Value will be the LoadAddress of the section in which
128 // the symbol resides (RE.Addend provides additional information about the
129 // symbol location). For external symbols, Value will be the address of the
130 // symbol in the target address space.
131 void RuntimeDyldMachO::resolveRelocation(const RelocationEntry &RE,
133 const SectionEntry &Section = Sections[RE.SectionID];
134 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
135 RE.IsPCRel, RE.Size);
138 void RuntimeDyldMachO::resolveRelocation(const SectionEntry &Section,
145 uint8_t *LocalAddress = Section.Address + Offset;
146 uint64_t FinalAddress = Section.LoadAddress + Offset;
147 unsigned MachoType = Type;
148 unsigned Size = 1 << LogSize;
150 DEBUG(dbgs() << "resolveRelocation LocalAddress: "
151 << format("%p", LocalAddress)
152 << " FinalAddress: " << format("%p", FinalAddress)
153 << " Value: " << format("%p", Value)
154 << " Addend: " << Addend
155 << " isPCRel: " << isPCRel
156 << " MachoType: " << MachoType
160 // This just dispatches to the proper target specific routine.
162 default: llvm_unreachable("Unsupported CPU type!");
164 resolveX86_64Relocation(LocalAddress,
173 resolveI386Relocation(LocalAddress,
181 case Triple::arm: // Fall through.
183 resolveARMRelocation(LocalAddress,
194 bool RuntimeDyldMachO::resolveI386Relocation(uint8_t *LocalAddress,
195 uint64_t FinalAddress,
202 Value -= FinalAddress + 4; // see resolveX86_64Relocation
206 llvm_unreachable("Invalid relocation type!");
207 case MachO::GENERIC_RELOC_VANILLA: {
208 uint8_t *p = LocalAddress;
209 uint64_t ValueToWrite = Value + Addend;
210 for (unsigned i = 0; i < Size; ++i) {
211 *p++ = (uint8_t)(ValueToWrite & 0xff);
216 case MachO::GENERIC_RELOC_SECTDIFF:
217 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF:
218 case MachO::GENERIC_RELOC_PB_LA_PTR:
219 return Error("Relocation type not implemented yet!");
223 bool RuntimeDyldMachO::resolveX86_64Relocation(uint8_t *LocalAddress,
224 uint64_t FinalAddress,
230 // If the relocation is PC-relative, the value to be encoded is the
231 // pointer difference.
233 // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
234 // address. Is that expected? Only for branches, perhaps?
235 Value -= FinalAddress + 4;
239 llvm_unreachable("Invalid relocation type!");
240 case MachO::X86_64_RELOC_SIGNED_1:
241 case MachO::X86_64_RELOC_SIGNED_2:
242 case MachO::X86_64_RELOC_SIGNED_4:
243 case MachO::X86_64_RELOC_SIGNED:
244 case MachO::X86_64_RELOC_UNSIGNED:
245 case MachO::X86_64_RELOC_BRANCH: {
247 // Mask in the target value a byte at a time (we don't have an alignment
248 // guarantee for the target address, so this is safest).
249 uint8_t *p = (uint8_t*)LocalAddress;
250 for (unsigned i = 0; i < Size; ++i) {
251 *p++ = (uint8_t)Value;
256 case MachO::X86_64_RELOC_GOT_LOAD:
257 case MachO::X86_64_RELOC_GOT:
258 case MachO::X86_64_RELOC_SUBTRACTOR:
259 case MachO::X86_64_RELOC_TLV:
260 return Error("Relocation type not implemented yet!");
264 bool RuntimeDyldMachO::resolveARMRelocation(uint8_t *LocalAddress,
265 uint64_t FinalAddress,
271 // If the relocation is PC-relative, the value to be encoded is the
272 // pointer difference.
274 Value -= FinalAddress;
275 // ARM PCRel relocations have an effective-PC offset of two instructions
276 // (four bytes in Thumb mode, 8 bytes in ARM mode).
277 // FIXME: For now, assume ARM mode.
283 llvm_unreachable("Invalid relocation type!");
284 case MachO::ARM_RELOC_VANILLA: {
285 // Mask in the target value a byte at a time (we don't have an alignment
286 // guarantee for the target address, so this is safest).
287 uint8_t *p = (uint8_t*)LocalAddress;
288 for (unsigned i = 0; i < Size; ++i) {
289 *p++ = (uint8_t)Value;
294 case MachO::ARM_RELOC_BR24: {
295 // Mask the value into the target address. We know instructions are
296 // 32-bit aligned, so we can do it all at once.
297 uint32_t *p = (uint32_t*)LocalAddress;
298 // The low two bits of the value are not encoded.
300 // Mask the value to 24 bits.
302 // FIXME: If the destination is a Thumb function (and the instruction
303 // is a non-predicated BL instruction), we need to change it to a BLX
304 // instruction instead.
306 // Insert the value into the instruction.
307 *p = (*p & ~0xffffff) | Value;
310 case MachO::ARM_THUMB_RELOC_BR22:
311 case MachO::ARM_THUMB_32BIT_BRANCH:
312 case MachO::ARM_RELOC_HALF:
313 case MachO::ARM_RELOC_HALF_SECTDIFF:
314 case MachO::ARM_RELOC_PAIR:
315 case MachO::ARM_RELOC_SECTDIFF:
316 case MachO::ARM_RELOC_LOCAL_SECTDIFF:
317 case MachO::ARM_RELOC_PB_LA_PTR:
318 return Error("Relocation type not implemented yet!");
323 void RuntimeDyldMachO::processRelocationRef(unsigned SectionID,
326 ObjSectionToIDMap &ObjSectionToID,
327 const SymbolTableMap &Symbols,
329 const ObjectFile *OF = Obj.getObjectFile();
330 const MachOObjectFile *MachO = static_cast<const MachOObjectFile*>(OF);
331 MachO::any_relocation_info RE= MachO->getRelocation(RelI.getRawDataRefImpl());
333 uint32_t RelType = MachO->getAnyRelocationType(RE);
335 // FIXME: Properly handle scattered relocations.
336 // For now, optimistically skip these: they can often be ignored, as
337 // the static linker will already have applied the relocation, and it
338 // only needs to be reapplied if symbols move relative to one another.
339 // Note: This will fail horribly where the relocations *do* need to be
340 // applied, but that was already the case.
341 if (MachO->isRelocationScattered(RE))
344 RelocationValueRef Value;
345 SectionEntry &Section = Sections[SectionID];
347 bool isExtern = MachO->getPlainRelocationExternal(RE);
348 bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
349 unsigned Size = MachO->getAnyRelocationLength(RE);
351 RelI.getOffset(Offset);
352 uint8_t *LocalAddress = Section.Address + Offset;
353 unsigned NumBytes = 1 << Size;
355 memcpy(&Addend, LocalAddress, NumBytes);
358 // Obtain the symbol name which is referenced in the relocation
359 symbol_iterator Symbol = RelI.getSymbol();
360 StringRef TargetName;
361 Symbol->getName(TargetName);
362 // First search for the symbol in the local symbol table
363 SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
364 if (lsi != Symbols.end()) {
365 Value.SectionID = lsi->second.first;
366 Value.Addend = lsi->second.second + Addend;
368 // Search for the symbol in the global symbol table
369 SymbolTableMap::const_iterator gsi = GlobalSymbolTable.find(TargetName.data());
370 if (gsi != GlobalSymbolTable.end()) {
371 Value.SectionID = gsi->second.first;
372 Value.Addend = gsi->second.second + Addend;
374 Value.SymbolName = TargetName.data();
375 Value.Addend = Addend;
379 SectionRef Sec = MachO->getRelocationSection(RE);
382 Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
384 Sec.getAddress(Addr);
385 Value.Addend = Addend - Addr;
387 Value.Addend += Offset + NumBytes;
390 if (Arch == Triple::x86_64 && (RelType == MachO::X86_64_RELOC_GOT ||
391 RelType == MachO::X86_64_RELOC_GOT_LOAD)) {
394 StubMap::const_iterator i = Stubs.find(Value);
396 if (i != Stubs.end()) {
397 Addr = Section.Address + i->second;
399 Stubs[Value] = Section.StubOffset;
400 uint8_t *GOTEntry = Section.Address + Section.StubOffset;
401 RelocationEntry RE(SectionID, Section.StubOffset,
402 MachO::X86_64_RELOC_UNSIGNED, 0, false, 3);
403 if (Value.SymbolName)
404 addRelocationForSymbol(RE, Value.SymbolName);
406 addRelocationForSection(RE, Value.SectionID);
407 Section.StubOffset += 8;
410 resolveRelocation(Section, Offset, (uint64_t)Addr,
411 MachO::X86_64_RELOC_UNSIGNED, Value.Addend, true, 2);
412 } else if (Arch == Triple::arm &&
413 (RelType & 0xf) == MachO::ARM_RELOC_BR24) {
414 // This is an ARM branch relocation, need to use a stub function.
416 // Look up for existing stub.
417 StubMap::const_iterator i = Stubs.find(Value);
418 if (i != Stubs.end())
419 resolveRelocation(Section, Offset,
420 (uint64_t)Section.Address + i->second,
421 RelType, 0, IsPCRel, Size);
423 // Create a new stub function.
424 Stubs[Value] = Section.StubOffset;
425 uint8_t *StubTargetAddr = createStubFunction(Section.Address +
427 RelocationEntry RE(SectionID, StubTargetAddr - Section.Address,
428 MachO::GENERIC_RELOC_VANILLA, Value.Addend);
429 if (Value.SymbolName)
430 addRelocationForSymbol(RE, Value.SymbolName);
432 addRelocationForSection(RE, Value.SectionID);
433 resolveRelocation(Section, Offset,
434 (uint64_t)Section.Address + Section.StubOffset,
435 RelType, 0, IsPCRel, Size);
436 Section.StubOffset += getMaxStubSize();
439 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend,
441 if (Value.SymbolName)
442 addRelocationForSymbol(RE, Value.SymbolName);
444 addRelocationForSection(RE, Value.SectionID);
449 bool RuntimeDyldMachO::isCompatibleFormat(
450 const ObjectBuffer *InputBuffer) const {
451 if (InputBuffer->getBufferSize() < 4)
453 StringRef Magic(InputBuffer->getBufferStart(), 4);
454 if (Magic == "\xFE\xED\xFA\xCE") return true;
455 if (Magic == "\xCE\xFA\xED\xFE") return true;
456 if (Magic == "\xFE\xED\xFA\xCF") return true;
457 if (Magic == "\xCF\xFA\xED\xFE") return true;
461 bool RuntimeDyldMachO::isCompatibleFile(
462 const object::ObjectFile *Obj) const {
463 return Obj->isMachO();
466 } // end namespace llvm