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 #include "RuntimeDyldMachO.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringRef.h"
18 using namespace llvm::object;
20 #define DEBUG_TYPE "dyld"
24 static unsigned char *processFDE(unsigned char *P, intptr_t DeltaForText,
25 intptr_t DeltaForEH) {
26 DEBUG(dbgs() << "Processing FDE: Delta for text: " << DeltaForText
27 << ", Delta for EH: " << DeltaForEH << "\n");
28 uint32_t Length = *((uint32_t *)P);
30 unsigned char *Ret = P + Length;
31 uint32_t Offset = *((uint32_t *)P);
32 if (Offset == 0) // is a CIE
36 intptr_t FDELocation = *((intptr_t *)P);
37 intptr_t NewLocation = FDELocation - DeltaForText;
38 *((intptr_t *)P) = NewLocation;
39 P += sizeof(intptr_t);
41 // Skip the FDE address range
42 P += sizeof(intptr_t);
44 uint8_t Augmentationsize = *P;
46 if (Augmentationsize != 0) {
47 intptr_t LSDA = *((intptr_t *)P);
48 intptr_t NewLSDA = LSDA - DeltaForEH;
49 *((intptr_t *)P) = NewLSDA;
55 static intptr_t computeDelta(SectionEntry *A, SectionEntry *B) {
56 intptr_t ObjDistance = A->ObjAddress - B->ObjAddress;
57 intptr_t MemDistance = A->LoadAddress - B->LoadAddress;
58 return ObjDistance - MemDistance;
61 void RuntimeDyldMachO::registerEHFrames() {
65 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
66 EHFrameRelatedSections &SectionInfo = UnregisteredEHFrameSections[i];
67 if (SectionInfo.EHFrameSID == RTDYLD_INVALID_SECTION_ID ||
68 SectionInfo.TextSID == RTDYLD_INVALID_SECTION_ID)
70 SectionEntry *Text = &Sections[SectionInfo.TextSID];
71 SectionEntry *EHFrame = &Sections[SectionInfo.EHFrameSID];
72 SectionEntry *ExceptTab = nullptr;
73 if (SectionInfo.ExceptTabSID != RTDYLD_INVALID_SECTION_ID)
74 ExceptTab = &Sections[SectionInfo.ExceptTabSID];
76 intptr_t DeltaForText = computeDelta(Text, EHFrame);
77 intptr_t DeltaForEH = 0;
79 DeltaForEH = computeDelta(ExceptTab, EHFrame);
81 unsigned char *P = EHFrame->Address;
82 unsigned char *End = P + EHFrame->Size;
84 P = processFDE(P, DeltaForText, DeltaForEH);
87 MemMgr->registerEHFrames(EHFrame->Address, EHFrame->LoadAddress,
90 UnregisteredEHFrameSections.clear();
93 void RuntimeDyldMachO::finalizeLoad(ObjectImage &ObjImg,
94 ObjSectionToIDMap &SectionMap) {
95 unsigned EHFrameSID = RTDYLD_INVALID_SECTION_ID;
96 unsigned TextSID = RTDYLD_INVALID_SECTION_ID;
97 unsigned ExceptTabSID = RTDYLD_INVALID_SECTION_ID;
98 ObjSectionToIDMap::iterator i, e;
99 for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
100 const SectionRef &Section = i->first;
102 Section.getName(Name);
103 if (Name == "__eh_frame")
104 EHFrameSID = i->second;
105 else if (Name == "__text")
107 else if (Name == "__gcc_except_tab")
108 ExceptTabSID = i->second;
109 else if (Name == "__jump_table")
110 populateJumpTable(cast<MachOObjectFile>(*ObjImg.getObjectFile()),
112 else if (Name == "__pointers")
113 populatePointersSection(cast<MachOObjectFile>(*ObjImg.getObjectFile()),
116 UnregisteredEHFrameSections.push_back(
117 EHFrameRelatedSections(EHFrameSID, TextSID, ExceptTabSID));
120 // The target location for the relocation is described by RE.SectionID and
121 // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
122 // SectionEntry has three members describing its location.
123 // SectionEntry::Address is the address at which the section has been loaded
124 // into memory in the current (host) process. SectionEntry::LoadAddress is the
125 // address that the section will have in the target process.
126 // SectionEntry::ObjAddress is the address of the bits for this section in the
127 // original emitted object image (also in the current address space).
129 // Relocations will be applied as if the section were loaded at
130 // SectionEntry::LoadAddress, but they will be applied at an address based
131 // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
132 // Target memory contents if they are required for value calculations.
134 // The Value parameter here is the load address of the symbol for the
135 // relocation to be applied. For relocations which refer to symbols in the
136 // current object Value will be the LoadAddress of the section in which
137 // the symbol resides (RE.Addend provides additional information about the
138 // symbol location). For external symbols, Value will be the address of the
139 // symbol in the target address space.
140 void RuntimeDyldMachO::resolveRelocation(const RelocationEntry &RE,
143 const SectionEntry &Section = Sections[RE.SectionID];
144 uint8_t* LocalAddress = Section.Address + RE.Offset;
145 uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
147 dbgs() << "resolveRelocation Section: " << RE.SectionID
148 << " LocalAddress: " << format("%p", LocalAddress)
149 << " FinalAddress: " << format("%p", FinalAddress)
150 << " Value: " << format("%p", Value)
151 << " Addend: " << RE.Addend
152 << " isPCRel: " << RE.IsPCRel
153 << " MachoType: " << RE.RelType
154 << " Size: " << (1 << RE.Size) << "\n";
157 // This just dispatches to the proper target specific routine.
160 llvm_unreachable("Unsupported CPU type!");
162 resolveX86_64Relocation(RE, Value);
165 resolveI386Relocation(RE, Value);
167 case Triple::arm: // Fall through.
169 resolveARMRelocation(RE, Value);
171 case Triple::aarch64:
173 resolveAArch64Relocation(RE, Value);
178 bool RuntimeDyldMachO::resolveI386Relocation(const RelocationEntry &RE,
180 const SectionEntry &Section = Sections[RE.SectionID];
181 uint8_t* LocalAddress = Section.Address + RE.Offset;
184 uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
185 Value -= FinalAddress + 4; // see MachOX86_64::resolveRelocation.
188 switch (RE.RelType) {
190 llvm_unreachable("Invalid relocation type!");
191 case MachO::GENERIC_RELOC_VANILLA:
192 return applyRelocationValue(LocalAddress, Value + RE.Addend,
194 case MachO::GENERIC_RELOC_SECTDIFF:
195 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
196 uint64_t SectionABase = Sections[RE.Sections.SectionA].LoadAddress;
197 uint64_t SectionBBase = Sections[RE.Sections.SectionB].LoadAddress;
198 assert((Value == SectionABase || Value == SectionBBase) &&
199 "Unexpected SECTDIFF relocation value.");
200 Value = SectionABase - SectionBBase + RE.Addend;
201 return applyRelocationValue(LocalAddress, Value, 1 << RE.Size);
203 case MachO::GENERIC_RELOC_PB_LA_PTR:
204 return Error("Relocation type not implemented yet!");
208 bool RuntimeDyldMachO::resolveX86_64Relocation(const RelocationEntry &RE,
210 const SectionEntry &Section = Sections[RE.SectionID];
211 uint8_t* LocalAddress = Section.Address + RE.Offset;
213 // If the relocation is PC-relative, the value to be encoded is the
214 // pointer difference.
216 // FIXME: It seems this value needs to be adjusted by 4 for an effective PC
217 // address. Is that expected? Only for branches, perhaps?
218 uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
219 Value -= FinalAddress + 4; // see MachOX86_64::resolveRelocation.
222 switch (RE.RelType) {
224 llvm_unreachable("Invalid relocation type!");
225 case MachO::X86_64_RELOC_SIGNED_1:
226 case MachO::X86_64_RELOC_SIGNED_2:
227 case MachO::X86_64_RELOC_SIGNED_4:
228 case MachO::X86_64_RELOC_SIGNED:
229 case MachO::X86_64_RELOC_UNSIGNED:
230 case MachO::X86_64_RELOC_BRANCH:
231 return applyRelocationValue(LocalAddress, Value + RE.Addend, 1 << RE.Size);
232 case MachO::X86_64_RELOC_GOT_LOAD:
233 case MachO::X86_64_RELOC_GOT:
234 case MachO::X86_64_RELOC_SUBTRACTOR:
235 case MachO::X86_64_RELOC_TLV:
236 return Error("Relocation type not implemented yet!");
240 bool RuntimeDyldMachO::resolveARMRelocation(const RelocationEntry &RE,
242 const SectionEntry &Section = Sections[RE.SectionID];
243 uint8_t* LocalAddress = Section.Address + RE.Offset;
245 // If the relocation is PC-relative, the value to be encoded is the
246 // pointer difference.
248 uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
249 Value -= FinalAddress;
250 // ARM PCRel relocations have an effective-PC offset of two instructions
251 // (four bytes in Thumb mode, 8 bytes in ARM mode).
252 // FIXME: For now, assume ARM mode.
256 switch (RE.RelType) {
258 llvm_unreachable("Invalid relocation type!");
259 case MachO::ARM_RELOC_VANILLA:
260 return applyRelocationValue(LocalAddress, Value, 1 << RE.Size);
261 case MachO::ARM_RELOC_BR24: {
262 // Mask the value into the target address. We know instructions are
263 // 32-bit aligned, so we can do it all at once.
264 uint32_t *p = (uint32_t *)LocalAddress;
265 // The low two bits of the value are not encoded.
267 // Mask the value to 24 bits.
268 uint64_t FinalValue = Value & 0xffffff;
269 // Check for overflow.
270 if (Value != FinalValue)
271 return Error("ARM BR24 relocation out of range.");
272 // FIXME: If the destination is a Thumb function (and the instruction
273 // is a non-predicated BL instruction), we need to change it to a BLX
274 // instruction instead.
276 // Insert the value into the instruction.
277 *p = (*p & ~0xffffff) | FinalValue;
280 case MachO::ARM_THUMB_RELOC_BR22:
281 case MachO::ARM_THUMB_32BIT_BRANCH:
282 case MachO::ARM_RELOC_HALF:
283 case MachO::ARM_RELOC_HALF_SECTDIFF:
284 case MachO::ARM_RELOC_PAIR:
285 case MachO::ARM_RELOC_SECTDIFF:
286 case MachO::ARM_RELOC_LOCAL_SECTDIFF:
287 case MachO::ARM_RELOC_PB_LA_PTR:
288 return Error("Relocation type not implemented yet!");
293 bool RuntimeDyldMachO::resolveAArch64Relocation(const RelocationEntry &RE,
295 const SectionEntry &Section = Sections[RE.SectionID];
296 uint8_t* LocalAddress = Section.Address + RE.Offset;
298 switch (RE.RelType) {
300 llvm_unreachable("Invalid relocation type!");
301 case MachO::ARM64_RELOC_UNSIGNED: {
302 assert(!RE.IsPCRel && "PCRel and ARM64_RELOC_UNSIGNED not supported");
303 // Mask in the target value a byte at a time (we don't have an alignment
304 // guarantee for the target address, so this is safest).
306 llvm_unreachable("Invalid size for ARM64_RELOC_UNSIGNED");
308 applyRelocationValue(LocalAddress, Value + RE.Addend, 1 << RE.Size);
311 case MachO::ARM64_RELOC_BRANCH26: {
312 assert(RE.IsPCRel && "not PCRel and ARM64_RELOC_BRANCH26 not supported");
313 // Mask the value into the target address. We know instructions are
314 // 32-bit aligned, so we can do it all at once.
315 uint32_t *p = (uint32_t*)LocalAddress;
316 // Check if the addend is encoded in the instruction.
317 uint32_t EncodedAddend = *p & 0x03FFFFFF;
318 if (EncodedAddend != 0 ) {
320 llvm_unreachable("branch26 instruction has embedded addend.");
322 llvm_unreachable("branch26 instruction has embedded addend and" \
323 "ARM64_RELOC_ADDEND.");
325 // Check if branch is in range.
326 uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
327 uint64_t PCRelVal = Value - FinalAddress + RE.Addend;
328 assert(isInt<26>(PCRelVal) && "Branch target out of range!");
329 // Insert the value into the instruction.
330 *p = (*p & 0xFC000000) | ((uint32_t)(PCRelVal >> 2) & 0x03FFFFFF);
333 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
334 case MachO::ARM64_RELOC_PAGE21: {
335 assert(RE.IsPCRel && "not PCRel and ARM64_RELOC_PAGE21 not supported");
336 // Mask the value into the target address. We know instructions are
337 // 32-bit aligned, so we can do it all at once.
338 uint32_t *p = (uint32_t*)LocalAddress;
339 // Check if the addend is encoded in the instruction.
340 uint32_t EncodedAddend = ((*p & 0x60000000) >> 29) |
341 ((*p & 0x01FFFFE0) >> 3);
342 if (EncodedAddend != 0) {
344 llvm_unreachable("adrp instruction has embedded addend.");
346 llvm_unreachable("adrp instruction has embedded addend and" \
347 "ARM64_RELOC_ADDEND.");
349 // Adjust for PC-relative relocation and offset.
350 uint64_t FinalAddress = Section.LoadAddress + RE.Offset;
351 uint64_t PCRelVal = ((Value + RE.Addend) & (-4096)) -
352 (FinalAddress & (-4096));
353 // Check that the value fits into 21 bits (+ 12 lower bits).
354 assert(isInt<33>(PCRelVal) && "Invalid page reloc value!");
355 // Insert the value into the instruction.
356 uint32_t ImmLoValue = (uint32_t)(PCRelVal << 17) & 0x60000000;
357 uint32_t ImmHiValue = (uint32_t)(PCRelVal >> 9) & 0x00FFFFE0;
358 *p = (*p & 0x9F00001F) | ImmHiValue | ImmLoValue;
361 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
362 case MachO::ARM64_RELOC_PAGEOFF12: {
363 assert(!RE.IsPCRel && "PCRel and ARM64_RELOC_PAGEOFF21 not supported");
364 // Mask the value into the target address. We know instructions are
365 // 32-bit aligned, so we can do it all at once.
366 uint32_t *p = (uint32_t*)LocalAddress;
367 // Check if the addend is encoded in the instruction.
368 uint32_t EncodedAddend = *p & 0x003FFC00;
369 if (EncodedAddend != 0) {
371 llvm_unreachable("adrp instruction has embedded addend.");
373 llvm_unreachable("adrp instruction has embedded addend and" \
374 "ARM64_RELOC_ADDEND.");
376 // Add the offset from the symbol.
378 // Mask out the page address and only use the lower 12 bits.
380 // Check which instruction we are updating to obtain the implicit shift
381 // factor from LDR/STR instructions.
382 if (*p & 0x08000000) {
383 uint32_t ImplicitShift = ((*p >> 30) & 0x3);
384 switch (ImplicitShift) {
386 // Check if this a vector op.
387 if ((*p & 0x04800000) == 0x04800000) {
389 assert(((Value & 0xF) == 0) &&
390 "128-bit LDR/STR not 16-byte aligned.");
394 assert(((Value & 0x1) == 0) && "16-bit LDR/STR not 2-byte aligned.");
396 assert(((Value & 0x3) == 0) && "32-bit LDR/STR not 4-byte aligned.");
398 assert(((Value & 0x7) == 0) && "64-bit LDR/STR not 8-byte aligned.");
400 // Compensate for implicit shift.
401 Value >>= ImplicitShift;
403 // Insert the value into the instruction.
404 *p = (*p & 0xFFC003FF) | ((uint32_t)(Value << 10) & 0x003FFC00);
407 case MachO::ARM64_RELOC_SUBTRACTOR:
408 case MachO::ARM64_RELOC_POINTER_TO_GOT:
409 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
410 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
411 llvm_unreachable("Relocation type not implemented yet!");
412 return Error("Relocation type not implemented yet!");
413 case MachO::ARM64_RELOC_ADDEND:
414 llvm_unreachable("ARM64_RELOC_ADDEND should have been handeled by " \
415 "processRelocationRef!");
420 void RuntimeDyldMachO::populateJumpTable(MachOObjectFile &Obj,
421 const SectionRef &JTSection,
422 unsigned JTSectionID) {
423 assert(!Obj.is64Bit() &&
424 "__jump_table section not supported in 64-bit MachO.");
426 MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
427 MachO::section Sec32 = Obj.getSection(JTSection.getRawDataRefImpl());
428 uint32_t JTSectionSize = Sec32.size;
429 unsigned FirstIndirectSymbol = Sec32.reserved1;
430 unsigned JTEntrySize = Sec32.reserved2;
431 unsigned NumJTEntries = JTSectionSize / JTEntrySize;
432 uint8_t* JTSectionAddr = getSectionAddress(JTSectionID);
433 unsigned JTEntryOffset = 0;
435 assert((JTSectionSize % JTEntrySize) == 0 &&
436 "Jump-table section does not contain a whole number of stubs?");
438 for (unsigned i = 0; i < NumJTEntries; ++i) {
439 unsigned SymbolIndex =
440 Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
441 symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
442 StringRef IndirectSymbolName;
443 SI->getName(IndirectSymbolName);
444 uint8_t* JTEntryAddr = JTSectionAddr + JTEntryOffset;
445 createStubFunction(JTEntryAddr);
446 RelocationEntry RE(JTSectionID, JTEntryOffset + 1,
447 MachO::GENERIC_RELOC_VANILLA, 0, true, 2);
448 addRelocationForSymbol(RE, IndirectSymbolName);
449 JTEntryOffset += JTEntrySize;
453 void RuntimeDyldMachO::populatePointersSection(MachOObjectFile &Obj,
454 const SectionRef &PTSection,
455 unsigned PTSectionID) {
456 assert(!Obj.is64Bit() &&
457 "__pointers section not supported in 64-bit MachO.");
459 MachO::dysymtab_command DySymTabCmd = Obj.getDysymtabLoadCommand();
460 MachO::section Sec32 = Obj.getSection(PTSection.getRawDataRefImpl());
461 uint32_t PTSectionSize = Sec32.size;
462 unsigned FirstIndirectSymbol = Sec32.reserved1;
463 const unsigned PTEntrySize = 4;
464 unsigned NumPTEntries = PTSectionSize / PTEntrySize;
465 unsigned PTEntryOffset = 0;
467 assert((PTSectionSize % PTEntrySize) == 0 &&
468 "Pointers section does not contain a whole number of stubs?");
470 DEBUG(dbgs() << "Populating __pointers, Section ID " << PTSectionID
471 << ", " << NumPTEntries << " entries, "
472 << PTEntrySize << " bytes each:\n");
474 for (unsigned i = 0; i < NumPTEntries; ++i) {
475 unsigned SymbolIndex =
476 Obj.getIndirectSymbolTableEntry(DySymTabCmd, FirstIndirectSymbol + i);
477 symbol_iterator SI = Obj.getSymbolByIndex(SymbolIndex);
478 StringRef IndirectSymbolName;
479 SI->getName(IndirectSymbolName);
480 DEBUG(dbgs() << " " << IndirectSymbolName << ": index " << SymbolIndex
481 << ", PT offset: " << PTEntryOffset << "\n");
482 RelocationEntry RE(PTSectionID, PTEntryOffset,
483 MachO::GENERIC_RELOC_VANILLA, 0, false, 2);
484 addRelocationForSymbol(RE, IndirectSymbolName);
485 PTEntryOffset += PTEntrySize;
490 section_iterator getSectionByAddress(const MachOObjectFile &Obj,
492 section_iterator SI = Obj.section_begin();
493 section_iterator SE = Obj.section_end();
495 for (; SI != SE; ++SI) {
496 uint64_t SAddr, SSize;
497 SI->getAddress(SAddr);
499 if ((Addr >= SAddr) && (Addr < SAddr + SSize))
506 relocation_iterator RuntimeDyldMachO::processSECTDIFFRelocation(
508 relocation_iterator RelI,
510 ObjSectionToIDMap &ObjSectionToID) {
511 const MachOObjectFile *MachO =
512 static_cast<const MachOObjectFile*>(Obj.getObjectFile());
513 MachO::any_relocation_info RE =
514 MachO->getRelocation(RelI->getRawDataRefImpl());
516 SectionEntry &Section = Sections[SectionID];
517 uint32_t RelocType = MachO->getAnyRelocationType(RE);
518 bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
519 unsigned Size = MachO->getAnyRelocationLength(RE);
521 RelI->getOffset(Offset);
522 uint8_t *LocalAddress = Section.Address + Offset;
523 unsigned NumBytes = 1 << Size;
525 memcpy(&Addend, LocalAddress, NumBytes);
528 MachO::any_relocation_info RE2 =
529 MachO->getRelocation(RelI->getRawDataRefImpl());
531 uint32_t AddrA = MachO->getScatteredRelocationValue(RE);
532 section_iterator SAI = getSectionByAddress(*MachO, AddrA);
533 assert(SAI != MachO->section_end() && "Can't find section for address A");
534 uint64_t SectionABase;
535 SAI->getAddress(SectionABase);
536 uint64_t SectionAOffset = AddrA - SectionABase;
537 SectionRef SectionA = *SAI;
539 SectionA.isText(IsCode);
540 uint32_t SectionAID = findOrEmitSection(Obj, SectionA, IsCode,
543 uint32_t AddrB = MachO->getScatteredRelocationValue(RE2);
544 section_iterator SBI = getSectionByAddress(*MachO, AddrB);
545 assert(SBI != MachO->section_end() && "Can't find section for address B");
546 uint64_t SectionBBase;
547 SBI->getAddress(SectionBBase);
548 uint64_t SectionBOffset = AddrB - SectionBBase;
549 SectionRef SectionB = *SBI;
550 uint32_t SectionBID = findOrEmitSection(Obj, SectionB, IsCode,
553 if (Addend != AddrA - AddrB)
554 Error("Unexpected SECTDIFF relocation addend.");
556 DEBUG(dbgs() << "Found SECTDIFF: AddrA: " << AddrA << ", AddrB: " << AddrB
557 << ", Addend: " << Addend << ", SectionA ID: "
558 << SectionAID << ", SectionAOffset: " << SectionAOffset
559 << ", SectionB ID: " << SectionBID << ", SectionBOffset: "
560 << SectionBOffset << "\n");
561 RelocationEntry R(SectionID, Offset, RelocType, 0,
562 SectionAID, SectionAOffset, SectionBID, SectionBOffset,
565 addRelocationForSection(R, SectionAID);
566 addRelocationForSection(R, SectionBID);
571 relocation_iterator RuntimeDyldMachO::processI386ScatteredVANILLA(
573 relocation_iterator RelI,
575 ObjSectionToIDMap &ObjSectionToID) {
576 const MachOObjectFile *MachO =
577 static_cast<const MachOObjectFile*>(Obj.getObjectFile());
578 MachO::any_relocation_info RE =
579 MachO->getRelocation(RelI->getRawDataRefImpl());
581 SectionEntry &Section = Sections[SectionID];
582 uint32_t RelocType = MachO->getAnyRelocationType(RE);
583 bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
584 unsigned Size = MachO->getAnyRelocationLength(RE);
586 RelI->getOffset(Offset);
587 uint8_t *LocalAddress = Section.Address + Offset;
588 unsigned NumBytes = 1 << Size;
590 memcpy(&Addend, LocalAddress, NumBytes);
592 unsigned SymbolBaseAddr = MachO->getScatteredRelocationValue(RE);
593 section_iterator TargetSI = getSectionByAddress(*MachO, SymbolBaseAddr);
594 assert(TargetSI != MachO->section_end() && "Can't find section for symbol");
595 uint64_t SectionBaseAddr;
596 TargetSI->getAddress(SectionBaseAddr);
597 SectionRef TargetSection = *TargetSI;
599 TargetSection.isText(IsCode);
600 uint32_t TargetSectionID = findOrEmitSection(Obj, TargetSection, IsCode,
603 Addend -= SectionBaseAddr;
604 RelocationEntry R(SectionID, Offset, RelocType, Addend,
607 addRelocationForSection(R, TargetSectionID);
612 relocation_iterator RuntimeDyldMachO::processRelocationRef(
613 unsigned SectionID, relocation_iterator RelI, ObjectImage &Obj,
614 ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols,
616 const ObjectFile *OF = Obj.getObjectFile();
617 const MachOObjectFile *MachO = static_cast<const MachOObjectFile *>(OF);
618 MachO::any_relocation_info RE =
619 MachO->getRelocation(RelI->getRawDataRefImpl());
620 int64_t RelocAddendValue = 0;
621 bool HasRelocAddendValue = false;
623 uint32_t RelType = MachO->getAnyRelocationType(RE);
624 if (Arch == Triple::arm64) {
625 // ARM64_RELOC_ADDEND provides the offset (addend) that will be used by the
626 // next relocation entry. Save the value and advance to the next relocation
628 if (RelType == MachO::ARM64_RELOC_ADDEND) {
629 assert(!MachO->getPlainRelocationExternal(RE));
630 assert(!MachO->getAnyRelocationPCRel(RE));
631 assert(MachO->getAnyRelocationLength(RE) == 2);
632 uint64_t RawAddend = MachO->getPlainRelocationSymbolNum(RE);
633 // Sign-extend the 24-bit to 64-bit.
634 RelocAddendValue = RawAddend << 40;
635 RelocAddendValue >>= 40;
636 HasRelocAddendValue = true;
638 // Get the next entry.
639 RE = MachO->getRelocation((++RelI)->getRawDataRefImpl());
640 RelType = MachO->getAnyRelocationType(RE);
641 assert(RelType == MachO::ARM64_RELOC_BRANCH26 ||
642 RelType == MachO::ARM64_RELOC_PAGE21 ||
643 RelType == MachO::ARM64_RELOC_PAGEOFF12);
645 } else if (RelType == MachO::ARM64_RELOC_BRANCH26 ||
646 RelType == MachO::ARM64_RELOC_PAGE21 ||
647 RelType == MachO::ARM64_RELOC_PAGEOFF12 ||
648 RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGE21 ||
649 RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12) {
650 RelocAddendValue = 0;
651 HasRelocAddendValue = true;
655 // FIXME: Properly handle scattered relocations.
656 // Special case the couple of scattered relocations that we know how
657 // to handle: SECTDIFF relocations, and scattered VANILLA relocations
659 // For all other scattered relocations, just bail out and hope for the
660 // best, since the offsets computed by scattered relocations have often
661 // been optimisticaly filled in by the compiler. This will fail
662 // horribly where the relocations *do* need to be applied, but that was
664 if (MachO->isRelocationScattered(RE)) {
665 if (RelType == MachO::GENERIC_RELOC_SECTDIFF ||
666 RelType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)
667 return processSECTDIFFRelocation(SectionID, RelI, Obj, ObjSectionToID);
668 else if (Arch == Triple::x86 && RelType == MachO::GENERIC_RELOC_VANILLA)
669 return processI386ScatteredVANILLA(SectionID, RelI, Obj, ObjSectionToID);
674 RelocationValueRef Value;
675 SectionEntry &Section = Sections[SectionID];
677 bool IsExtern = MachO->getPlainRelocationExternal(RE);
678 bool IsPCRel = MachO->getAnyRelocationPCRel(RE);
679 unsigned Size = MachO->getAnyRelocationLength(RE);
681 RelI->getOffset(Offset);
682 uint8_t *LocalAddress = Section.Address + Offset;
683 unsigned NumBytes = 1 << Size;
685 if (HasRelocAddendValue)
686 Addend = RelocAddendValue;
688 memcpy(&Addend, LocalAddress, NumBytes);
691 // Obtain the symbol name which is referenced in the relocation
692 symbol_iterator Symbol = RelI->getSymbol();
693 StringRef TargetName;
694 Symbol->getName(TargetName);
695 // First search for the symbol in the local symbol table
696 SymbolTableMap::const_iterator lsi = Symbols.find(TargetName.data());
697 if (lsi != Symbols.end()) {
698 Value.SectionID = lsi->second.first;
699 Value.Addend = lsi->second.second + Addend;
701 // Search for the symbol in the global symbol table
702 SymbolTableMap::const_iterator gsi =
703 GlobalSymbolTable.find(TargetName.data());
704 if (gsi != GlobalSymbolTable.end()) {
705 Value.SectionID = gsi->second.first;
706 Value.Addend = gsi->second.second + Addend;
708 Value.SymbolName = TargetName.data();
709 Value.Addend = Addend;
713 // Addends for external, PC-rel relocations on i386 point back to the zero
714 // offset. Calculate the final offset from the relocation target instead.
715 // This allows us to use the same logic for both external and internal
716 // relocations in resolveI386RelocationRef.
717 if (Arch == Triple::x86 && IsPCRel) {
718 uint64_t RelocAddr = 0;
719 RelI->getAddress(RelocAddr);
720 Value.Addend += RelocAddr + 4;
724 SectionRef Sec = MachO->getRelocationSection(RE);
727 Value.SectionID = findOrEmitSection(Obj, Sec, IsCode, ObjSectionToID);
729 Sec.getAddress(Addr);
730 Value.Addend = Addend - Addr;
732 Value.Addend += Offset + NumBytes;
735 if (Arch == Triple::x86_64 && (RelType == MachO::X86_64_RELOC_GOT ||
736 RelType == MachO::X86_64_RELOC_GOT_LOAD)) {
740 // FIXME: Teach the generic code above not to prematurely conflate
741 // relocation addends and symbol offsets.
742 Value.Addend -= Addend;
743 StubMap::const_iterator i = Stubs.find(Value);
745 if (i != Stubs.end()) {
746 Addr = Section.Address + i->second;
748 Stubs[Value] = Section.StubOffset;
749 uint8_t *GOTEntry = Section.Address + Section.StubOffset;
750 RelocationEntry GOTRE(SectionID, Section.StubOffset,
751 MachO::X86_64_RELOC_UNSIGNED, Value.Addend, false,
753 if (Value.SymbolName)
754 addRelocationForSymbol(GOTRE, Value.SymbolName);
756 addRelocationForSection(GOTRE, Value.SectionID);
757 Section.StubOffset += 8;
760 RelocationEntry TargetRE(SectionID, Offset,
761 MachO::X86_64_RELOC_UNSIGNED, Addend, true,
763 resolveRelocation(TargetRE, (uint64_t)Addr);
764 } else if (Arch == Triple::arm && (RelType & 0xf) == MachO::ARM_RELOC_BR24) {
765 // This is an ARM branch relocation, need to use a stub function.
767 // Look up for existing stub.
768 StubMap::const_iterator i = Stubs.find(Value);
770 if (i != Stubs.end()) {
771 Addr = Section.Address + i->second;
773 // Create a new stub function.
774 Stubs[Value] = Section.StubOffset;
775 uint8_t *StubTargetAddr =
776 createStubFunction(Section.Address + Section.StubOffset);
777 RelocationEntry StubRE(SectionID, StubTargetAddr - Section.Address,
778 MachO::GENERIC_RELOC_VANILLA, Value.Addend);
779 if (Value.SymbolName)
780 addRelocationForSymbol(StubRE, Value.SymbolName);
782 addRelocationForSection(StubRE, Value.SectionID);
783 Addr = Section.Address + Section.StubOffset;
784 Section.StubOffset += getMaxStubSize();
786 RelocationEntry TargetRE(Value.SectionID, Offset, RelType, 0, IsPCRel,
788 resolveRelocation(TargetRE, (uint64_t)Addr);
789 } else if (Arch == Triple::arm64 &&
790 (RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGE21 ||
791 RelType == MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12)) {
793 StubMap::const_iterator i = Stubs.find(Value);
795 if (i != Stubs.end())
796 Addr = Section.Address + i->second;
798 // FIXME: There must be a better way to do this then to check and fix the
799 // alignment every time!!!
800 uintptr_t BaseAddress = uintptr_t(Section.Address);
801 uintptr_t StubAlignment = getStubAlignment();
802 uintptr_t StubAddress
803 = (BaseAddress + Section.StubOffset + StubAlignment - 1) &
805 unsigned StubOffset = StubAddress - BaseAddress;
806 Stubs[Value] = StubOffset;
807 assert(((StubAddress % getStubAlignment()) == 0) &&
808 "GOT entry not aligned");
809 RelocationEntry GOTRE(SectionID, StubOffset, MachO::ARM64_RELOC_UNSIGNED,
810 Value.Addend, /*IsPCRel=*/false, /*Size=*/3);
811 if (Value.SymbolName)
812 addRelocationForSymbol(GOTRE, Value.SymbolName);
814 addRelocationForSection(GOTRE, Value.SectionID);
815 Section.StubOffset = StubOffset + getMaxStubSize();
817 Addr = (uint8_t *)StubAddress;
819 RelocationEntry TargetRE(SectionID, Offset, RelType, /*Addend=*/0, IsPCRel,
821 resolveRelocation(TargetRE, (uint64_t)Addr);
824 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, IsPCRel, Size);
825 if (Value.SymbolName)
826 addRelocationForSymbol(RE, Value.SymbolName);
828 addRelocationForSection(RE, Value.SectionID);
834 RuntimeDyldMachO::isCompatibleFormat(const ObjectBuffer *InputBuffer) const {
835 if (InputBuffer->getBufferSize() < 4)
837 StringRef Magic(InputBuffer->getBufferStart(), 4);
838 if (Magic == "\xFE\xED\xFA\xCE")
840 if (Magic == "\xCE\xFA\xED\xFE")
842 if (Magic == "\xFE\xED\xFA\xCF")
844 if (Magic == "\xCF\xFA\xED\xFE")
849 bool RuntimeDyldMachO::isCompatibleFile(const object::ObjectFile *Obj) const {
850 return Obj->isMachO();
853 } // end namespace llvm