Fix the build bot break introduced by r320791.
[llvm-core.git] / lib / ExecutionEngine / RuntimeDyld / RuntimeDyldELF.cpp
blobc0047d0cde6a95579172a546eb43823bdae131d5
1 //===-- RuntimeDyldELF.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 ELF support for the MC-JIT runtime dynamic linker.
12 //===----------------------------------------------------------------------===//
14 #include "RuntimeDyldELF.h"
15 #include "RuntimeDyldCheckerImpl.h"
16 #include "Targets/RuntimeDyldELFMips.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/BinaryFormat/ELF.h"
21 #include "llvm/Object/ELFObjectFile.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/MemoryBuffer.h"
26 using namespace llvm;
27 using namespace llvm::object;
28 using namespace llvm::support::endian;
30 #define DEBUG_TYPE "dyld"
32 static void or32le(void *P, int32_t V) { write32le(P, read32le(P) | V); }
34 static void or32AArch64Imm(void *L, uint64_t Imm) {
35 or32le(L, (Imm & 0xFFF) << 10);
38 template <class T> static void write(bool isBE, void *P, T V) {
39 isBE ? write<T, support::big>(P, V) : write<T, support::little>(P, V);
42 static void write32AArch64Addr(void *L, uint64_t Imm) {
43 uint32_t ImmLo = (Imm & 0x3) << 29;
44 uint32_t ImmHi = (Imm & 0x1FFFFC) << 3;
45 uint64_t Mask = (0x3 << 29) | (0x1FFFFC << 3);
46 write32le(L, (read32le(L) & ~Mask) | ImmLo | ImmHi);
49 // Return the bits [Start, End] from Val shifted Start bits.
50 // For instance, getBits(0xF0, 4, 8) returns 0xF.
51 static uint64_t getBits(uint64_t Val, int Start, int End) {
52 uint64_t Mask = ((uint64_t)1 << (End + 1 - Start)) - 1;
53 return (Val >> Start) & Mask;
56 namespace {
58 template <class ELFT> class DyldELFObject : public ELFObjectFile<ELFT> {
59 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
61 typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
62 typedef Elf_Sym_Impl<ELFT> Elf_Sym;
63 typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
64 typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
66 typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
68 typedef typename ELFDataTypeTypedefHelper<ELFT>::value_type addr_type;
70 DyldELFObject(ELFObjectFile<ELFT> &&Obj);
72 public:
73 static Expected<std::unique_ptr<DyldELFObject>>
74 create(MemoryBufferRef Wrapper);
76 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
78 void updateSymbolAddress(const SymbolRef &SymRef, uint64_t Addr);
80 // Methods for type inquiry through isa, cast and dyn_cast
81 static bool classof(const Binary *v) {
82 return (isa<ELFObjectFile<ELFT>>(v) &&
83 classof(cast<ELFObjectFile<ELFT>>(v)));
85 static bool classof(const ELFObjectFile<ELFT> *v) {
86 return v->isDyldType();
92 // The MemoryBuffer passed into this constructor is just a wrapper around the
93 // actual memory. Ultimately, the Binary parent class will take ownership of
94 // this MemoryBuffer object but not the underlying memory.
95 template <class ELFT>
96 DyldELFObject<ELFT>::DyldELFObject(ELFObjectFile<ELFT> &&Obj)
97 : ELFObjectFile<ELFT>(std::move(Obj)) {
98 this->isDyldELFObject = true;
101 template <class ELFT>
102 Expected<std::unique_ptr<DyldELFObject<ELFT>>>
103 DyldELFObject<ELFT>::create(MemoryBufferRef Wrapper) {
104 auto Obj = ELFObjectFile<ELFT>::create(Wrapper);
105 if (auto E = Obj.takeError())
106 return std::move(E);
107 std::unique_ptr<DyldELFObject<ELFT>> Ret(
108 new DyldELFObject<ELFT>(std::move(*Obj)));
109 return std::move(Ret);
112 template <class ELFT>
113 void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
114 uint64_t Addr) {
115 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
116 Elf_Shdr *shdr =
117 const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
119 // This assumes the address passed in matches the target address bitness
120 // The template-based type cast handles everything else.
121 shdr->sh_addr = static_cast<addr_type>(Addr);
124 template <class ELFT>
125 void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
126 uint64_t Addr) {
128 Elf_Sym *sym = const_cast<Elf_Sym *>(
129 ELFObjectFile<ELFT>::getSymbol(SymRef.getRawDataRefImpl()));
131 // This assumes the address passed in matches the target address bitness
132 // The template-based type cast handles everything else.
133 sym->st_value = static_cast<addr_type>(Addr);
136 class LoadedELFObjectInfo final
137 : public LoadedObjectInfoHelper<LoadedELFObjectInfo,
138 RuntimeDyld::LoadedObjectInfo> {
139 public:
140 LoadedELFObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
141 : LoadedObjectInfoHelper(RTDyld, std::move(ObjSecToIDMap)) {}
143 OwningBinary<ObjectFile>
144 getObjectForDebug(const ObjectFile &Obj) const override;
147 template <typename ELFT>
148 static Expected<std::unique_ptr<DyldELFObject<ELFT>>>
149 createRTDyldELFObject(MemoryBufferRef Buffer, const ObjectFile &SourceObject,
150 const LoadedELFObjectInfo &L) {
151 typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
152 typedef typename ELFDataTypeTypedefHelper<ELFT>::value_type addr_type;
154 Expected<std::unique_ptr<DyldELFObject<ELFT>>> ObjOrErr =
155 DyldELFObject<ELFT>::create(Buffer);
156 if (Error E = ObjOrErr.takeError())
157 return std::move(E);
159 std::unique_ptr<DyldELFObject<ELFT>> Obj = std::move(*ObjOrErr);
161 // Iterate over all sections in the object.
162 auto SI = SourceObject.section_begin();
163 for (const auto &Sec : Obj->sections()) {
164 StringRef SectionName;
165 Sec.getName(SectionName);
166 if (SectionName != "") {
167 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
168 Elf_Shdr *shdr = const_cast<Elf_Shdr *>(
169 reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
171 if (uint64_t SecLoadAddr = L.getSectionLoadAddress(*SI)) {
172 // This assumes that the address passed in matches the target address
173 // bitness. The template-based type cast handles everything else.
174 shdr->sh_addr = static_cast<addr_type>(SecLoadAddr);
177 ++SI;
180 return std::move(Obj);
183 static OwningBinary<ObjectFile>
184 createELFDebugObject(const ObjectFile &Obj, const LoadedELFObjectInfo &L) {
185 assert(Obj.isELF() && "Not an ELF object file.");
187 std::unique_ptr<MemoryBuffer> Buffer =
188 MemoryBuffer::getMemBufferCopy(Obj.getData(), Obj.getFileName());
190 Expected<std::unique_ptr<ObjectFile>> DebugObj(nullptr);
191 handleAllErrors(DebugObj.takeError());
192 if (Obj.getBytesInAddress() == 4 && Obj.isLittleEndian())
193 DebugObj =
194 createRTDyldELFObject<ELF32LE>(Buffer->getMemBufferRef(), Obj, L);
195 else if (Obj.getBytesInAddress() == 4 && !Obj.isLittleEndian())
196 DebugObj =
197 createRTDyldELFObject<ELF32BE>(Buffer->getMemBufferRef(), Obj, L);
198 else if (Obj.getBytesInAddress() == 8 && !Obj.isLittleEndian())
199 DebugObj =
200 createRTDyldELFObject<ELF64BE>(Buffer->getMemBufferRef(), Obj, L);
201 else if (Obj.getBytesInAddress() == 8 && Obj.isLittleEndian())
202 DebugObj =
203 createRTDyldELFObject<ELF64LE>(Buffer->getMemBufferRef(), Obj, L);
204 else
205 llvm_unreachable("Unexpected ELF format");
207 handleAllErrors(DebugObj.takeError());
208 return OwningBinary<ObjectFile>(std::move(*DebugObj), std::move(Buffer));
211 OwningBinary<ObjectFile>
212 LoadedELFObjectInfo::getObjectForDebug(const ObjectFile &Obj) const {
213 return createELFDebugObject(Obj, *this);
216 } // anonymous namespace
218 namespace llvm {
220 RuntimeDyldELF::RuntimeDyldELF(RuntimeDyld::MemoryManager &MemMgr,
221 JITSymbolResolver &Resolver)
222 : RuntimeDyldImpl(MemMgr, Resolver), GOTSectionID(0), CurrentGOTIndex(0) {}
223 RuntimeDyldELF::~RuntimeDyldELF() {}
225 void RuntimeDyldELF::registerEHFrames() {
226 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
227 SID EHFrameSID = UnregisteredEHFrameSections[i];
228 uint8_t *EHFrameAddr = Sections[EHFrameSID].getAddress();
229 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].getLoadAddress();
230 size_t EHFrameSize = Sections[EHFrameSID].getSize();
231 MemMgr.registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
233 UnregisteredEHFrameSections.clear();
236 std::unique_ptr<RuntimeDyldELF>
237 llvm::RuntimeDyldELF::create(Triple::ArchType Arch,
238 RuntimeDyld::MemoryManager &MemMgr,
239 JITSymbolResolver &Resolver) {
240 switch (Arch) {
241 default:
242 return make_unique<RuntimeDyldELF>(MemMgr, Resolver);
243 case Triple::mips:
244 case Triple::mipsel:
245 case Triple::mips64:
246 case Triple::mips64el:
247 return make_unique<RuntimeDyldELFMips>(MemMgr, Resolver);
251 std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
252 RuntimeDyldELF::loadObject(const object::ObjectFile &O) {
253 if (auto ObjSectionToIDOrErr = loadObjectImpl(O))
254 return llvm::make_unique<LoadedELFObjectInfo>(*this, *ObjSectionToIDOrErr);
255 else {
256 HasError = true;
257 raw_string_ostream ErrStream(ErrorStr);
258 logAllUnhandledErrors(ObjSectionToIDOrErr.takeError(), ErrStream, "");
259 return nullptr;
263 void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
264 uint64_t Offset, uint64_t Value,
265 uint32_t Type, int64_t Addend,
266 uint64_t SymOffset) {
267 switch (Type) {
268 default:
269 llvm_unreachable("Relocation type not implemented yet!");
270 break;
271 case ELF::R_X86_64_NONE:
272 break;
273 case ELF::R_X86_64_64: {
274 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
275 Value + Addend;
276 DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
277 << format("%p\n", Section.getAddressWithOffset(Offset)));
278 break;
280 case ELF::R_X86_64_32:
281 case ELF::R_X86_64_32S: {
282 Value += Addend;
283 assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
284 (Type == ELF::R_X86_64_32S &&
285 ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
286 uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
287 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
288 TruncatedAddr;
289 DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
290 << format("%p\n", Section.getAddressWithOffset(Offset)));
291 break;
293 case ELF::R_X86_64_PC8: {
294 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
295 int64_t RealOffset = Value + Addend - FinalAddress;
296 assert(isInt<8>(RealOffset));
297 int8_t TruncOffset = (RealOffset & 0xFF);
298 Section.getAddress()[Offset] = TruncOffset;
299 break;
301 case ELF::R_X86_64_PC32: {
302 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
303 int64_t RealOffset = Value + Addend - FinalAddress;
304 assert(isInt<32>(RealOffset));
305 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
306 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
307 TruncOffset;
308 break;
310 case ELF::R_X86_64_PC64: {
311 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
312 int64_t RealOffset = Value + Addend - FinalAddress;
313 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
314 RealOffset;
315 break;
320 void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
321 uint64_t Offset, uint32_t Value,
322 uint32_t Type, int32_t Addend) {
323 switch (Type) {
324 case ELF::R_386_32: {
325 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
326 Value + Addend;
327 break;
329 case ELF::R_386_PC32: {
330 uint32_t FinalAddress =
331 Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
332 uint32_t RealOffset = Value + Addend - FinalAddress;
333 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
334 RealOffset;
335 break;
337 default:
338 // There are other relocation types, but it appears these are the
339 // only ones currently used by the LLVM ELF object writer
340 llvm_unreachable("Relocation type not implemented yet!");
341 break;
345 void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
346 uint64_t Offset, uint64_t Value,
347 uint32_t Type, int64_t Addend) {
348 uint32_t *TargetPtr =
349 reinterpret_cast<uint32_t *>(Section.getAddressWithOffset(Offset));
350 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
351 // Data should use target endian. Code should always use little endian.
352 bool isBE = Arch == Triple::aarch64_be;
354 DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
355 << format("%llx", Section.getAddressWithOffset(Offset))
356 << " FinalAddress: 0x" << format("%llx", FinalAddress)
357 << " Value: 0x" << format("%llx", Value) << " Type: 0x"
358 << format("%x", Type) << " Addend: 0x" << format("%llx", Addend)
359 << "\n");
361 switch (Type) {
362 default:
363 llvm_unreachable("Relocation type not implemented yet!");
364 break;
365 case ELF::R_AARCH64_ABS16: {
366 uint64_t Result = Value + Addend;
367 assert(static_cast<int64_t>(Result) >= INT16_MIN && Result < UINT16_MAX);
368 write(isBE, TargetPtr, static_cast<uint16_t>(Result & 0xffffU));
369 break;
371 case ELF::R_AARCH64_ABS32: {
372 uint64_t Result = Value + Addend;
373 assert(static_cast<int64_t>(Result) >= INT32_MIN && Result < UINT32_MAX);
374 write(isBE, TargetPtr, static_cast<uint32_t>(Result & 0xffffffffU));
375 break;
377 case ELF::R_AARCH64_ABS64:
378 write(isBE, TargetPtr, Value + Addend);
379 break;
380 case ELF::R_AARCH64_PREL32: {
381 uint64_t Result = Value + Addend - FinalAddress;
382 assert(static_cast<int64_t>(Result) >= INT32_MIN &&
383 static_cast<int64_t>(Result) <= UINT32_MAX);
384 write(isBE, TargetPtr, static_cast<uint32_t>(Result & 0xffffffffU));
385 break;
387 case ELF::R_AARCH64_PREL64:
388 write(isBE, TargetPtr, Value + Addend - FinalAddress);
389 break;
390 case ELF::R_AARCH64_CALL26: // fallthrough
391 case ELF::R_AARCH64_JUMP26: {
392 // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
393 // calculation.
394 uint64_t BranchImm = Value + Addend - FinalAddress;
396 // "Check that -2^27 <= result < 2^27".
397 assert(isInt<28>(BranchImm));
398 or32le(TargetPtr, (BranchImm & 0x0FFFFFFC) >> 2);
399 break;
401 case ELF::R_AARCH64_MOVW_UABS_G3:
402 or32le(TargetPtr, ((Value + Addend) & 0xFFFF000000000000) >> 43);
403 break;
404 case ELF::R_AARCH64_MOVW_UABS_G2_NC:
405 or32le(TargetPtr, ((Value + Addend) & 0xFFFF00000000) >> 27);
406 break;
407 case ELF::R_AARCH64_MOVW_UABS_G1_NC:
408 or32le(TargetPtr, ((Value + Addend) & 0xFFFF0000) >> 11);
409 break;
410 case ELF::R_AARCH64_MOVW_UABS_G0_NC:
411 or32le(TargetPtr, ((Value + Addend) & 0xFFFF) << 5);
412 break;
413 case ELF::R_AARCH64_ADR_PREL_PG_HI21: {
414 // Operation: Page(S+A) - Page(P)
415 uint64_t Result =
416 ((Value + Addend) & ~0xfffULL) - (FinalAddress & ~0xfffULL);
418 // Check that -2^32 <= X < 2^32
419 assert(isInt<33>(Result) && "overflow check failed for relocation");
421 // Immediate goes in bits 30:29 + 5:23 of ADRP instruction, taken
422 // from bits 32:12 of X.
423 write32AArch64Addr(TargetPtr, Result >> 12);
424 break;
426 case ELF::R_AARCH64_ADD_ABS_LO12_NC:
427 // Operation: S + A
428 // Immediate goes in bits 21:10 of LD/ST instruction, taken
429 // from bits 11:0 of X
430 or32AArch64Imm(TargetPtr, Value + Addend);
431 break;
432 case ELF::R_AARCH64_LDST8_ABS_LO12_NC:
433 // Operation: S + A
434 // Immediate goes in bits 21:10 of LD/ST instruction, taken
435 // from bits 11:0 of X
436 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 0, 11));
437 break;
438 case ELF::R_AARCH64_LDST16_ABS_LO12_NC:
439 // Operation: S + A
440 // Immediate goes in bits 21:10 of LD/ST instruction, taken
441 // from bits 11:1 of X
442 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 1, 11));
443 break;
444 case ELF::R_AARCH64_LDST32_ABS_LO12_NC:
445 // Operation: S + A
446 // Immediate goes in bits 21:10 of LD/ST instruction, taken
447 // from bits 11:2 of X
448 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 2, 11));
449 break;
450 case ELF::R_AARCH64_LDST64_ABS_LO12_NC:
451 // Operation: S + A
452 // Immediate goes in bits 21:10 of LD/ST instruction, taken
453 // from bits 11:3 of X
454 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 3, 11));
455 break;
456 case ELF::R_AARCH64_LDST128_ABS_LO12_NC:
457 // Operation: S + A
458 // Immediate goes in bits 21:10 of LD/ST instruction, taken
459 // from bits 11:4 of X
460 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 4, 11));
461 break;
465 void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
466 uint64_t Offset, uint32_t Value,
467 uint32_t Type, int32_t Addend) {
468 // TODO: Add Thumb relocations.
469 uint32_t *TargetPtr =
470 reinterpret_cast<uint32_t *>(Section.getAddressWithOffset(Offset));
471 uint32_t FinalAddress = Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
472 Value += Addend;
474 DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
475 << Section.getAddressWithOffset(Offset)
476 << " FinalAddress: " << format("%p", FinalAddress) << " Value: "
477 << format("%x", Value) << " Type: " << format("%x", Type)
478 << " Addend: " << format("%x", Addend) << "\n");
480 switch (Type) {
481 default:
482 llvm_unreachable("Not implemented relocation type!");
484 case ELF::R_ARM_NONE:
485 break;
486 // Write a 31bit signed offset
487 case ELF::R_ARM_PREL31:
488 support::ulittle32_t::ref{TargetPtr} =
489 (support::ulittle32_t::ref{TargetPtr} & 0x80000000) |
490 ((Value - FinalAddress) & ~0x80000000);
491 break;
492 case ELF::R_ARM_TARGET1:
493 case ELF::R_ARM_ABS32:
494 support::ulittle32_t::ref{TargetPtr} = Value;
495 break;
496 // Write first 16 bit of 32 bit value to the mov instruction.
497 // Last 4 bit should be shifted.
498 case ELF::R_ARM_MOVW_ABS_NC:
499 case ELF::R_ARM_MOVT_ABS:
500 if (Type == ELF::R_ARM_MOVW_ABS_NC)
501 Value = Value & 0xFFFF;
502 else if (Type == ELF::R_ARM_MOVT_ABS)
503 Value = (Value >> 16) & 0xFFFF;
504 support::ulittle32_t::ref{TargetPtr} =
505 (support::ulittle32_t::ref{TargetPtr} & ~0x000F0FFF) | (Value & 0xFFF) |
506 (((Value >> 12) & 0xF) << 16);
507 break;
508 // Write 24 bit relative value to the branch instruction.
509 case ELF::R_ARM_PC24: // Fall through.
510 case ELF::R_ARM_CALL: // Fall through.
511 case ELF::R_ARM_JUMP24:
512 int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
513 RelValue = (RelValue & 0x03FFFFFC) >> 2;
514 assert((support::ulittle32_t::ref{TargetPtr} & 0xFFFFFF) == 0xFFFFFE);
515 support::ulittle32_t::ref{TargetPtr} =
516 (support::ulittle32_t::ref{TargetPtr} & 0xFF000000) | RelValue;
517 break;
521 void RuntimeDyldELF::setMipsABI(const ObjectFile &Obj) {
522 if (Arch == Triple::UnknownArch ||
523 !StringRef(Triple::getArchTypePrefix(Arch)).equals("mips")) {
524 IsMipsO32ABI = false;
525 IsMipsN32ABI = false;
526 IsMipsN64ABI = false;
527 return;
529 unsigned AbiVariant;
530 Obj.getPlatformFlags(AbiVariant);
531 IsMipsO32ABI = AbiVariant & ELF::EF_MIPS_ABI_O32;
532 IsMipsN32ABI = AbiVariant & ELF::EF_MIPS_ABI2;
533 IsMipsN64ABI = Obj.getFileFormatName().equals("ELF64-mips");
536 // Return the .TOC. section and offset.
537 Error RuntimeDyldELF::findPPC64TOCSection(const ELFObjectFileBase &Obj,
538 ObjSectionToIDMap &LocalSections,
539 RelocationValueRef &Rel) {
540 // Set a default SectionID in case we do not find a TOC section below.
541 // This may happen for references to TOC base base (sym@toc, .odp
542 // relocation) without a .toc directive. In this case just use the
543 // first section (which is usually the .odp) since the code won't
544 // reference the .toc base directly.
545 Rel.SymbolName = nullptr;
546 Rel.SectionID = 0;
548 // The TOC consists of sections .got, .toc, .tocbss, .plt in that
549 // order. The TOC starts where the first of these sections starts.
550 for (auto &Section: Obj.sections()) {
551 StringRef SectionName;
552 if (auto EC = Section.getName(SectionName))
553 return errorCodeToError(EC);
555 if (SectionName == ".got"
556 || SectionName == ".toc"
557 || SectionName == ".tocbss"
558 || SectionName == ".plt") {
559 if (auto SectionIDOrErr =
560 findOrEmitSection(Obj, Section, false, LocalSections))
561 Rel.SectionID = *SectionIDOrErr;
562 else
563 return SectionIDOrErr.takeError();
564 break;
568 // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
569 // thus permitting a full 64 Kbytes segment.
570 Rel.Addend = 0x8000;
572 return Error::success();
575 // Returns the sections and offset associated with the ODP entry referenced
576 // by Symbol.
577 Error RuntimeDyldELF::findOPDEntrySection(const ELFObjectFileBase &Obj,
578 ObjSectionToIDMap &LocalSections,
579 RelocationValueRef &Rel) {
580 // Get the ELF symbol value (st_value) to compare with Relocation offset in
581 // .opd entries
582 for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
583 si != se; ++si) {
584 section_iterator RelSecI = si->getRelocatedSection();
585 if (RelSecI == Obj.section_end())
586 continue;
588 StringRef RelSectionName;
589 if (auto EC = RelSecI->getName(RelSectionName))
590 return errorCodeToError(EC);
592 if (RelSectionName != ".opd")
593 continue;
595 for (elf_relocation_iterator i = si->relocation_begin(),
596 e = si->relocation_end();
597 i != e;) {
598 // The R_PPC64_ADDR64 relocation indicates the first field
599 // of a .opd entry
600 uint64_t TypeFunc = i->getType();
601 if (TypeFunc != ELF::R_PPC64_ADDR64) {
602 ++i;
603 continue;
606 uint64_t TargetSymbolOffset = i->getOffset();
607 symbol_iterator TargetSymbol = i->getSymbol();
608 int64_t Addend;
609 if (auto AddendOrErr = i->getAddend())
610 Addend = *AddendOrErr;
611 else
612 return AddendOrErr.takeError();
614 ++i;
615 if (i == e)
616 break;
618 // Just check if following relocation is a R_PPC64_TOC
619 uint64_t TypeTOC = i->getType();
620 if (TypeTOC != ELF::R_PPC64_TOC)
621 continue;
623 // Finally compares the Symbol value and the target symbol offset
624 // to check if this .opd entry refers to the symbol the relocation
625 // points to.
626 if (Rel.Addend != (int64_t)TargetSymbolOffset)
627 continue;
629 section_iterator TSI = Obj.section_end();
630 if (auto TSIOrErr = TargetSymbol->getSection())
631 TSI = *TSIOrErr;
632 else
633 return TSIOrErr.takeError();
634 assert(TSI != Obj.section_end() && "TSI should refer to a valid section");
636 bool IsCode = TSI->isText();
637 if (auto SectionIDOrErr = findOrEmitSection(Obj, *TSI, IsCode,
638 LocalSections))
639 Rel.SectionID = *SectionIDOrErr;
640 else
641 return SectionIDOrErr.takeError();
642 Rel.Addend = (intptr_t)Addend;
643 return Error::success();
646 llvm_unreachable("Attempting to get address of ODP entry!");
649 // Relocation masks following the #lo(value), #hi(value), #ha(value),
650 // #higher(value), #highera(value), #highest(value), and #highesta(value)
651 // macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
652 // document.
654 static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; }
656 static inline uint16_t applyPPChi(uint64_t value) {
657 return (value >> 16) & 0xffff;
660 static inline uint16_t applyPPCha (uint64_t value) {
661 return ((value + 0x8000) >> 16) & 0xffff;
664 static inline uint16_t applyPPChigher(uint64_t value) {
665 return (value >> 32) & 0xffff;
668 static inline uint16_t applyPPChighera (uint64_t value) {
669 return ((value + 0x8000) >> 32) & 0xffff;
672 static inline uint16_t applyPPChighest(uint64_t value) {
673 return (value >> 48) & 0xffff;
676 static inline uint16_t applyPPChighesta (uint64_t value) {
677 return ((value + 0x8000) >> 48) & 0xffff;
680 void RuntimeDyldELF::resolvePPC32Relocation(const SectionEntry &Section,
681 uint64_t Offset, uint64_t Value,
682 uint32_t Type, int64_t Addend) {
683 uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
684 switch (Type) {
685 default:
686 llvm_unreachable("Relocation type not implemented yet!");
687 break;
688 case ELF::R_PPC_ADDR16_LO:
689 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
690 break;
691 case ELF::R_PPC_ADDR16_HI:
692 writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
693 break;
694 case ELF::R_PPC_ADDR16_HA:
695 writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
696 break;
700 void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
701 uint64_t Offset, uint64_t Value,
702 uint32_t Type, int64_t Addend) {
703 uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
704 switch (Type) {
705 default:
706 llvm_unreachable("Relocation type not implemented yet!");
707 break;
708 case ELF::R_PPC64_ADDR16:
709 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
710 break;
711 case ELF::R_PPC64_ADDR16_DS:
712 writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
713 break;
714 case ELF::R_PPC64_ADDR16_LO:
715 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
716 break;
717 case ELF::R_PPC64_ADDR16_LO_DS:
718 writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
719 break;
720 case ELF::R_PPC64_ADDR16_HI:
721 writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
722 break;
723 case ELF::R_PPC64_ADDR16_HA:
724 writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
725 break;
726 case ELF::R_PPC64_ADDR16_HIGHER:
727 writeInt16BE(LocalAddress, applyPPChigher(Value + Addend));
728 break;
729 case ELF::R_PPC64_ADDR16_HIGHERA:
730 writeInt16BE(LocalAddress, applyPPChighera(Value + Addend));
731 break;
732 case ELF::R_PPC64_ADDR16_HIGHEST:
733 writeInt16BE(LocalAddress, applyPPChighest(Value + Addend));
734 break;
735 case ELF::R_PPC64_ADDR16_HIGHESTA:
736 writeInt16BE(LocalAddress, applyPPChighesta(Value + Addend));
737 break;
738 case ELF::R_PPC64_ADDR14: {
739 assert(((Value + Addend) & 3) == 0);
740 // Preserve the AA/LK bits in the branch instruction
741 uint8_t aalk = *(LocalAddress + 3);
742 writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
743 } break;
744 case ELF::R_PPC64_REL16_LO: {
745 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
746 uint64_t Delta = Value - FinalAddress + Addend;
747 writeInt16BE(LocalAddress, applyPPClo(Delta));
748 } break;
749 case ELF::R_PPC64_REL16_HI: {
750 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
751 uint64_t Delta = Value - FinalAddress + Addend;
752 writeInt16BE(LocalAddress, applyPPChi(Delta));
753 } break;
754 case ELF::R_PPC64_REL16_HA: {
755 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
756 uint64_t Delta = Value - FinalAddress + Addend;
757 writeInt16BE(LocalAddress, applyPPCha(Delta));
758 } break;
759 case ELF::R_PPC64_ADDR32: {
760 int64_t Result = static_cast<int64_t>(Value + Addend);
761 if (SignExtend64<32>(Result) != Result)
762 llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
763 writeInt32BE(LocalAddress, Result);
764 } break;
765 case ELF::R_PPC64_REL24: {
766 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
767 int64_t delta = static_cast<int64_t>(Value - FinalAddress + Addend);
768 if (SignExtend64<26>(delta) != delta)
769 llvm_unreachable("Relocation R_PPC64_REL24 overflow");
770 // Generates a 'bl <address>' instruction
771 writeInt32BE(LocalAddress, 0x48000001 | (delta & 0x03FFFFFC));
772 } break;
773 case ELF::R_PPC64_REL32: {
774 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
775 int64_t delta = static_cast<int64_t>(Value - FinalAddress + Addend);
776 if (SignExtend64<32>(delta) != delta)
777 llvm_unreachable("Relocation R_PPC64_REL32 overflow");
778 writeInt32BE(LocalAddress, delta);
779 } break;
780 case ELF::R_PPC64_REL64: {
781 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
782 uint64_t Delta = Value - FinalAddress + Addend;
783 writeInt64BE(LocalAddress, Delta);
784 } break;
785 case ELF::R_PPC64_ADDR64:
786 writeInt64BE(LocalAddress, Value + Addend);
787 break;
791 void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
792 uint64_t Offset, uint64_t Value,
793 uint32_t Type, int64_t Addend) {
794 uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
795 switch (Type) {
796 default:
797 llvm_unreachable("Relocation type not implemented yet!");
798 break;
799 case ELF::R_390_PC16DBL:
800 case ELF::R_390_PLT16DBL: {
801 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
802 assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
803 writeInt16BE(LocalAddress, Delta / 2);
804 break;
806 case ELF::R_390_PC32DBL:
807 case ELF::R_390_PLT32DBL: {
808 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
809 assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
810 writeInt32BE(LocalAddress, Delta / 2);
811 break;
813 case ELF::R_390_PC16: {
814 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
815 assert(int16_t(Delta) == Delta && "R_390_PC16 overflow");
816 writeInt16BE(LocalAddress, Delta);
817 break;
819 case ELF::R_390_PC32: {
820 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
821 assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
822 writeInt32BE(LocalAddress, Delta);
823 break;
825 case ELF::R_390_PC64: {
826 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
827 writeInt64BE(LocalAddress, Delta);
828 break;
830 case ELF::R_390_8:
831 *LocalAddress = (uint8_t)(Value + Addend);
832 break;
833 case ELF::R_390_16:
834 writeInt16BE(LocalAddress, Value + Addend);
835 break;
836 case ELF::R_390_32:
837 writeInt32BE(LocalAddress, Value + Addend);
838 break;
839 case ELF::R_390_64:
840 writeInt64BE(LocalAddress, Value + Addend);
841 break;
845 void RuntimeDyldELF::resolveBPFRelocation(const SectionEntry &Section,
846 uint64_t Offset, uint64_t Value,
847 uint32_t Type, int64_t Addend) {
848 bool isBE = Arch == Triple::bpfeb;
850 switch (Type) {
851 default:
852 llvm_unreachable("Relocation type not implemented yet!");
853 break;
854 case ELF::R_BPF_NONE:
855 break;
856 case ELF::R_BPF_64_64: {
857 write(isBE, Section.getAddressWithOffset(Offset), Value + Addend);
858 DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
859 << format("%p\n", Section.getAddressWithOffset(Offset)));
860 break;
862 case ELF::R_BPF_64_32: {
863 Value += Addend;
864 assert(Value <= UINT32_MAX);
865 write(isBE, Section.getAddressWithOffset(Offset), static_cast<uint32_t>(Value));
866 DEBUG(dbgs() << "Writing " << format("%p", Value) << " at "
867 << format("%p\n", Section.getAddressWithOffset(Offset)));
868 break;
873 // The target location for the relocation is described by RE.SectionID and
874 // RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
875 // SectionEntry has three members describing its location.
876 // SectionEntry::Address is the address at which the section has been loaded
877 // into memory in the current (host) process. SectionEntry::LoadAddress is the
878 // address that the section will have in the target process.
879 // SectionEntry::ObjAddress is the address of the bits for this section in the
880 // original emitted object image (also in the current address space).
882 // Relocations will be applied as if the section were loaded at
883 // SectionEntry::LoadAddress, but they will be applied at an address based
884 // on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
885 // Target memory contents if they are required for value calculations.
887 // The Value parameter here is the load address of the symbol for the
888 // relocation to be applied. For relocations which refer to symbols in the
889 // current object Value will be the LoadAddress of the section in which
890 // the symbol resides (RE.Addend provides additional information about the
891 // symbol location). For external symbols, Value will be the address of the
892 // symbol in the target address space.
893 void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
894 uint64_t Value) {
895 const SectionEntry &Section = Sections[RE.SectionID];
896 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
897 RE.SymOffset, RE.SectionID);
900 void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
901 uint64_t Offset, uint64_t Value,
902 uint32_t Type, int64_t Addend,
903 uint64_t SymOffset, SID SectionID) {
904 switch (Arch) {
905 case Triple::x86_64:
906 resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
907 break;
908 case Triple::x86:
909 resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
910 (uint32_t)(Addend & 0xffffffffL));
911 break;
912 case Triple::aarch64:
913 case Triple::aarch64_be:
914 resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
915 break;
916 case Triple::arm: // Fall through.
917 case Triple::armeb:
918 case Triple::thumb:
919 case Triple::thumbeb:
920 resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
921 (uint32_t)(Addend & 0xffffffffL));
922 break;
923 case Triple::ppc:
924 resolvePPC32Relocation(Section, Offset, Value, Type, Addend);
925 break;
926 case Triple::ppc64: // Fall through.
927 case Triple::ppc64le:
928 resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
929 break;
930 case Triple::systemz:
931 resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
932 break;
933 case Triple::bpfel:
934 case Triple::bpfeb:
935 resolveBPFRelocation(Section, Offset, Value, Type, Addend);
936 break;
937 default:
938 llvm_unreachable("Unsupported CPU type!");
942 void *RuntimeDyldELF::computePlaceholderAddress(unsigned SectionID, uint64_t Offset) const {
943 return (void *)(Sections[SectionID].getObjAddress() + Offset);
946 void RuntimeDyldELF::processSimpleRelocation(unsigned SectionID, uint64_t Offset, unsigned RelType, RelocationValueRef Value) {
947 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
948 if (Value.SymbolName)
949 addRelocationForSymbol(RE, Value.SymbolName);
950 else
951 addRelocationForSection(RE, Value.SectionID);
954 uint32_t RuntimeDyldELF::getMatchingLoRelocation(uint32_t RelType,
955 bool IsLocal) const {
956 switch (RelType) {
957 case ELF::R_MICROMIPS_GOT16:
958 if (IsLocal)
959 return ELF::R_MICROMIPS_LO16;
960 break;
961 case ELF::R_MICROMIPS_HI16:
962 return ELF::R_MICROMIPS_LO16;
963 case ELF::R_MIPS_GOT16:
964 if (IsLocal)
965 return ELF::R_MIPS_LO16;
966 break;
967 case ELF::R_MIPS_HI16:
968 return ELF::R_MIPS_LO16;
969 case ELF::R_MIPS_PCHI16:
970 return ELF::R_MIPS_PCLO16;
971 default:
972 break;
974 return ELF::R_MIPS_NONE;
977 // Sometimes we don't need to create thunk for a branch.
978 // This typically happens when branch target is located
979 // in the same object file. In such case target is either
980 // a weak symbol or symbol in a different executable section.
981 // This function checks if branch target is located in the
982 // same object file and if distance between source and target
983 // fits R_AARCH64_CALL26 relocation. If both conditions are
984 // met, it emits direct jump to the target and returns true.
985 // Otherwise false is returned and thunk is created.
986 bool RuntimeDyldELF::resolveAArch64ShortBranch(
987 unsigned SectionID, relocation_iterator RelI,
988 const RelocationValueRef &Value) {
989 uint64_t Address;
990 if (Value.SymbolName) {
991 auto Loc = GlobalSymbolTable.find(Value.SymbolName);
993 // Don't create direct branch for external symbols.
994 if (Loc == GlobalSymbolTable.end())
995 return false;
997 const auto &SymInfo = Loc->second;
998 Address =
999 uint64_t(Sections[SymInfo.getSectionID()].getLoadAddressWithOffset(
1000 SymInfo.getOffset()));
1001 } else {
1002 Address = uint64_t(Sections[Value.SectionID].getLoadAddress());
1004 uint64_t Offset = RelI->getOffset();
1005 uint64_t SourceAddress = Sections[SectionID].getLoadAddressWithOffset(Offset);
1007 // R_AARCH64_CALL26 requires immediate to be in range -2^27 <= imm < 2^27
1008 // If distance between source and target is out of range then we should
1009 // create thunk.
1010 if (!isInt<28>(Address + Value.Addend - SourceAddress))
1011 return false;
1013 resolveRelocation(Sections[SectionID], Offset, Address, RelI->getType(),
1014 Value.Addend);
1016 return true;
1019 void RuntimeDyldELF::resolveAArch64Branch(unsigned SectionID,
1020 const RelocationValueRef &Value,
1021 relocation_iterator RelI,
1022 StubMap &Stubs) {
1024 DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
1025 SectionEntry &Section = Sections[SectionID];
1027 uint64_t Offset = RelI->getOffset();
1028 unsigned RelType = RelI->getType();
1029 // Look for an existing stub.
1030 StubMap::const_iterator i = Stubs.find(Value);
1031 if (i != Stubs.end()) {
1032 resolveRelocation(Section, Offset,
1033 (uint64_t)Section.getAddressWithOffset(i->second),
1034 RelType, 0);
1035 DEBUG(dbgs() << " Stub function found\n");
1036 } else if (!resolveAArch64ShortBranch(SectionID, RelI, Value)) {
1037 // Create a new stub function.
1038 DEBUG(dbgs() << " Create a new stub function\n");
1039 Stubs[Value] = Section.getStubOffset();
1040 uint8_t *StubTargetAddr = createStubFunction(
1041 Section.getAddressWithOffset(Section.getStubOffset()));
1043 RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.getAddress(),
1044 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
1045 RelocationEntry REmovk_g2(SectionID,
1046 StubTargetAddr - Section.getAddress() + 4,
1047 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
1048 RelocationEntry REmovk_g1(SectionID,
1049 StubTargetAddr - Section.getAddress() + 8,
1050 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
1051 RelocationEntry REmovk_g0(SectionID,
1052 StubTargetAddr - Section.getAddress() + 12,
1053 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
1055 if (Value.SymbolName) {
1056 addRelocationForSymbol(REmovz_g3, Value.SymbolName);
1057 addRelocationForSymbol(REmovk_g2, Value.SymbolName);
1058 addRelocationForSymbol(REmovk_g1, Value.SymbolName);
1059 addRelocationForSymbol(REmovk_g0, Value.SymbolName);
1060 } else {
1061 addRelocationForSection(REmovz_g3, Value.SectionID);
1062 addRelocationForSection(REmovk_g2, Value.SectionID);
1063 addRelocationForSection(REmovk_g1, Value.SectionID);
1064 addRelocationForSection(REmovk_g0, Value.SectionID);
1066 resolveRelocation(Section, Offset,
1067 reinterpret_cast<uint64_t>(Section.getAddressWithOffset(
1068 Section.getStubOffset())),
1069 RelType, 0);
1070 Section.advanceStubOffset(getMaxStubSize());
1074 Expected<relocation_iterator>
1075 RuntimeDyldELF::processRelocationRef(
1076 unsigned SectionID, relocation_iterator RelI, const ObjectFile &O,
1077 ObjSectionToIDMap &ObjSectionToID, StubMap &Stubs) {
1078 const auto &Obj = cast<ELFObjectFileBase>(O);
1079 uint64_t RelType = RelI->getType();
1080 int64_t Addend = 0;
1081 if (Expected<int64_t> AddendOrErr = ELFRelocationRef(*RelI).getAddend())
1082 Addend = *AddendOrErr;
1083 else
1084 consumeError(AddendOrErr.takeError());
1085 elf_symbol_iterator Symbol = RelI->getSymbol();
1087 // Obtain the symbol name which is referenced in the relocation
1088 StringRef TargetName;
1089 if (Symbol != Obj.symbol_end()) {
1090 if (auto TargetNameOrErr = Symbol->getName())
1091 TargetName = *TargetNameOrErr;
1092 else
1093 return TargetNameOrErr.takeError();
1095 DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
1096 << " TargetName: " << TargetName << "\n");
1097 RelocationValueRef Value;
1098 // First search for the symbol in the local symbol table
1099 SymbolRef::Type SymType = SymbolRef::ST_Unknown;
1101 // Search for the symbol in the global symbol table
1102 RTDyldSymbolTable::const_iterator gsi = GlobalSymbolTable.end();
1103 if (Symbol != Obj.symbol_end()) {
1104 gsi = GlobalSymbolTable.find(TargetName.data());
1105 Expected<SymbolRef::Type> SymTypeOrErr = Symbol->getType();
1106 if (!SymTypeOrErr) {
1107 std::string Buf;
1108 raw_string_ostream OS(Buf);
1109 logAllUnhandledErrors(SymTypeOrErr.takeError(), OS, "");
1110 OS.flush();
1111 report_fatal_error(Buf);
1113 SymType = *SymTypeOrErr;
1115 if (gsi != GlobalSymbolTable.end()) {
1116 const auto &SymInfo = gsi->second;
1117 Value.SectionID = SymInfo.getSectionID();
1118 Value.Offset = SymInfo.getOffset();
1119 Value.Addend = SymInfo.getOffset() + Addend;
1120 } else {
1121 switch (SymType) {
1122 case SymbolRef::ST_Debug: {
1123 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
1124 // and can be changed by another developers. Maybe best way is add
1125 // a new symbol type ST_Section to SymbolRef and use it.
1126 auto SectionOrErr = Symbol->getSection();
1127 if (!SectionOrErr) {
1128 std::string Buf;
1129 raw_string_ostream OS(Buf);
1130 logAllUnhandledErrors(SectionOrErr.takeError(), OS, "");
1131 OS.flush();
1132 report_fatal_error(Buf);
1134 section_iterator si = *SectionOrErr;
1135 if (si == Obj.section_end())
1136 llvm_unreachable("Symbol section not found, bad object file format!");
1137 DEBUG(dbgs() << "\t\tThis is section symbol\n");
1138 bool isCode = si->isText();
1139 if (auto SectionIDOrErr = findOrEmitSection(Obj, (*si), isCode,
1140 ObjSectionToID))
1141 Value.SectionID = *SectionIDOrErr;
1142 else
1143 return SectionIDOrErr.takeError();
1144 Value.Addend = Addend;
1145 break;
1147 case SymbolRef::ST_Data:
1148 case SymbolRef::ST_Function:
1149 case SymbolRef::ST_Unknown: {
1150 Value.SymbolName = TargetName.data();
1151 Value.Addend = Addend;
1153 // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
1154 // will manifest here as a NULL symbol name.
1155 // We can set this as a valid (but empty) symbol name, and rely
1156 // on addRelocationForSymbol to handle this.
1157 if (!Value.SymbolName)
1158 Value.SymbolName = "";
1159 break;
1161 default:
1162 llvm_unreachable("Unresolved symbol type!");
1163 break;
1167 uint64_t Offset = RelI->getOffset();
1169 DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset
1170 << "\n");
1171 if ((Arch == Triple::aarch64 || Arch == Triple::aarch64_be)) {
1172 if (RelType == ELF::R_AARCH64_CALL26 || RelType == ELF::R_AARCH64_JUMP26) {
1173 resolveAArch64Branch(SectionID, Value, RelI, Stubs);
1174 } else if (RelType == ELF::R_AARCH64_ADR_GOT_PAGE) {
1175 // Craete new GOT entry or find existing one. If GOT entry is
1176 // to be created, then we also emit ABS64 relocation for it.
1177 uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_AARCH64_ABS64);
1178 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1179 ELF::R_AARCH64_ADR_PREL_PG_HI21);
1181 } else if (RelType == ELF::R_AARCH64_LD64_GOT_LO12_NC) {
1182 uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_AARCH64_ABS64);
1183 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1184 ELF::R_AARCH64_LDST64_ABS_LO12_NC);
1185 } else {
1186 processSimpleRelocation(SectionID, Offset, RelType, Value);
1188 } else if (Arch == Triple::arm) {
1189 if (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL ||
1190 RelType == ELF::R_ARM_JUMP24) {
1191 // This is an ARM branch relocation, need to use a stub function.
1192 DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.\n");
1193 SectionEntry &Section = Sections[SectionID];
1195 // Look for an existing stub.
1196 StubMap::const_iterator i = Stubs.find(Value);
1197 if (i != Stubs.end()) {
1198 resolveRelocation(
1199 Section, Offset,
1200 reinterpret_cast<uint64_t>(Section.getAddressWithOffset(i->second)),
1201 RelType, 0);
1202 DEBUG(dbgs() << " Stub function found\n");
1203 } else {
1204 // Create a new stub function.
1205 DEBUG(dbgs() << " Create a new stub function\n");
1206 Stubs[Value] = Section.getStubOffset();
1207 uint8_t *StubTargetAddr = createStubFunction(
1208 Section.getAddressWithOffset(Section.getStubOffset()));
1209 RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(),
1210 ELF::R_ARM_ABS32, Value.Addend);
1211 if (Value.SymbolName)
1212 addRelocationForSymbol(RE, Value.SymbolName);
1213 else
1214 addRelocationForSection(RE, Value.SectionID);
1216 resolveRelocation(Section, Offset, reinterpret_cast<uint64_t>(
1217 Section.getAddressWithOffset(
1218 Section.getStubOffset())),
1219 RelType, 0);
1220 Section.advanceStubOffset(getMaxStubSize());
1222 } else {
1223 uint32_t *Placeholder =
1224 reinterpret_cast<uint32_t*>(computePlaceholderAddress(SectionID, Offset));
1225 if (RelType == ELF::R_ARM_PREL31 || RelType == ELF::R_ARM_TARGET1 ||
1226 RelType == ELF::R_ARM_ABS32) {
1227 Value.Addend += *Placeholder;
1228 } else if (RelType == ELF::R_ARM_MOVW_ABS_NC || RelType == ELF::R_ARM_MOVT_ABS) {
1229 // See ELF for ARM documentation
1230 Value.Addend += (int16_t)((*Placeholder & 0xFFF) | (((*Placeholder >> 16) & 0xF) << 12));
1232 processSimpleRelocation(SectionID, Offset, RelType, Value);
1234 } else if (IsMipsO32ABI) {
1235 uint8_t *Placeholder = reinterpret_cast<uint8_t *>(
1236 computePlaceholderAddress(SectionID, Offset));
1237 uint32_t Opcode = readBytesUnaligned(Placeholder, 4);
1238 if (RelType == ELF::R_MIPS_26) {
1239 // This is an Mips branch relocation, need to use a stub function.
1240 DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1241 SectionEntry &Section = Sections[SectionID];
1243 // Extract the addend from the instruction.
1244 // We shift up by two since the Value will be down shifted again
1245 // when applying the relocation.
1246 uint32_t Addend = (Opcode & 0x03ffffff) << 2;
1248 Value.Addend += Addend;
1250 // Look up for existing stub.
1251 StubMap::const_iterator i = Stubs.find(Value);
1252 if (i != Stubs.end()) {
1253 RelocationEntry RE(SectionID, Offset, RelType, i->second);
1254 addRelocationForSection(RE, SectionID);
1255 DEBUG(dbgs() << " Stub function found\n");
1256 } else {
1257 // Create a new stub function.
1258 DEBUG(dbgs() << " Create a new stub function\n");
1259 Stubs[Value] = Section.getStubOffset();
1261 unsigned AbiVariant;
1262 O.getPlatformFlags(AbiVariant);
1264 uint8_t *StubTargetAddr = createStubFunction(
1265 Section.getAddressWithOffset(Section.getStubOffset()), AbiVariant);
1267 // Creating Hi and Lo relocations for the filled stub instructions.
1268 RelocationEntry REHi(SectionID, StubTargetAddr - Section.getAddress(),
1269 ELF::R_MIPS_HI16, Value.Addend);
1270 RelocationEntry RELo(SectionID,
1271 StubTargetAddr - Section.getAddress() + 4,
1272 ELF::R_MIPS_LO16, Value.Addend);
1274 if (Value.SymbolName) {
1275 addRelocationForSymbol(REHi, Value.SymbolName);
1276 addRelocationForSymbol(RELo, Value.SymbolName);
1277 } else {
1278 addRelocationForSection(REHi, Value.SectionID);
1279 addRelocationForSection(RELo, Value.SectionID);
1282 RelocationEntry RE(SectionID, Offset, RelType, Section.getStubOffset());
1283 addRelocationForSection(RE, SectionID);
1284 Section.advanceStubOffset(getMaxStubSize());
1286 } else if (RelType == ELF::R_MIPS_HI16 || RelType == ELF::R_MIPS_PCHI16) {
1287 int64_t Addend = (Opcode & 0x0000ffff) << 16;
1288 RelocationEntry RE(SectionID, Offset, RelType, Addend);
1289 PendingRelocs.push_back(std::make_pair(Value, RE));
1290 } else if (RelType == ELF::R_MIPS_LO16 || RelType == ELF::R_MIPS_PCLO16) {
1291 int64_t Addend = Value.Addend + SignExtend32<16>(Opcode & 0x0000ffff);
1292 for (auto I = PendingRelocs.begin(); I != PendingRelocs.end();) {
1293 const RelocationValueRef &MatchingValue = I->first;
1294 RelocationEntry &Reloc = I->second;
1295 if (MatchingValue == Value &&
1296 RelType == getMatchingLoRelocation(Reloc.RelType) &&
1297 SectionID == Reloc.SectionID) {
1298 Reloc.Addend += Addend;
1299 if (Value.SymbolName)
1300 addRelocationForSymbol(Reloc, Value.SymbolName);
1301 else
1302 addRelocationForSection(Reloc, Value.SectionID);
1303 I = PendingRelocs.erase(I);
1304 } else
1305 ++I;
1307 RelocationEntry RE(SectionID, Offset, RelType, Addend);
1308 if (Value.SymbolName)
1309 addRelocationForSymbol(RE, Value.SymbolName);
1310 else
1311 addRelocationForSection(RE, Value.SectionID);
1312 } else {
1313 if (RelType == ELF::R_MIPS_32)
1314 Value.Addend += Opcode;
1315 else if (RelType == ELF::R_MIPS_PC16)
1316 Value.Addend += SignExtend32<18>((Opcode & 0x0000ffff) << 2);
1317 else if (RelType == ELF::R_MIPS_PC19_S2)
1318 Value.Addend += SignExtend32<21>((Opcode & 0x0007ffff) << 2);
1319 else if (RelType == ELF::R_MIPS_PC21_S2)
1320 Value.Addend += SignExtend32<23>((Opcode & 0x001fffff) << 2);
1321 else if (RelType == ELF::R_MIPS_PC26_S2)
1322 Value.Addend += SignExtend32<28>((Opcode & 0x03ffffff) << 2);
1323 processSimpleRelocation(SectionID, Offset, RelType, Value);
1325 } else if (IsMipsN32ABI || IsMipsN64ABI) {
1326 uint32_t r_type = RelType & 0xff;
1327 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1328 if (r_type == ELF::R_MIPS_CALL16 || r_type == ELF::R_MIPS_GOT_PAGE
1329 || r_type == ELF::R_MIPS_GOT_DISP) {
1330 StringMap<uint64_t>::iterator i = GOTSymbolOffsets.find(TargetName);
1331 if (i != GOTSymbolOffsets.end())
1332 RE.SymOffset = i->second;
1333 else {
1334 RE.SymOffset = allocateGOTEntries(1);
1335 GOTSymbolOffsets[TargetName] = RE.SymOffset;
1337 if (Value.SymbolName)
1338 addRelocationForSymbol(RE, Value.SymbolName);
1339 else
1340 addRelocationForSection(RE, Value.SectionID);
1341 } else if (RelType == ELF::R_MIPS_26) {
1342 // This is an Mips branch relocation, need to use a stub function.
1343 DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1344 SectionEntry &Section = Sections[SectionID];
1346 // Look up for existing stub.
1347 StubMap::const_iterator i = Stubs.find(Value);
1348 if (i != Stubs.end()) {
1349 RelocationEntry RE(SectionID, Offset, RelType, i->second);
1350 addRelocationForSection(RE, SectionID);
1351 DEBUG(dbgs() << " Stub function found\n");
1352 } else {
1353 // Create a new stub function.
1354 DEBUG(dbgs() << " Create a new stub function\n");
1355 Stubs[Value] = Section.getStubOffset();
1357 unsigned AbiVariant;
1358 O.getPlatformFlags(AbiVariant);
1360 uint8_t *StubTargetAddr = createStubFunction(
1361 Section.getAddressWithOffset(Section.getStubOffset()), AbiVariant);
1363 if (IsMipsN32ABI) {
1364 // Creating Hi and Lo relocations for the filled stub instructions.
1365 RelocationEntry REHi(SectionID, StubTargetAddr - Section.getAddress(),
1366 ELF::R_MIPS_HI16, Value.Addend);
1367 RelocationEntry RELo(SectionID,
1368 StubTargetAddr - Section.getAddress() + 4,
1369 ELF::R_MIPS_LO16, Value.Addend);
1370 if (Value.SymbolName) {
1371 addRelocationForSymbol(REHi, Value.SymbolName);
1372 addRelocationForSymbol(RELo, Value.SymbolName);
1373 } else {
1374 addRelocationForSection(REHi, Value.SectionID);
1375 addRelocationForSection(RELo, Value.SectionID);
1377 } else {
1378 // Creating Highest, Higher, Hi and Lo relocations for the filled stub
1379 // instructions.
1380 RelocationEntry REHighest(SectionID,
1381 StubTargetAddr - Section.getAddress(),
1382 ELF::R_MIPS_HIGHEST, Value.Addend);
1383 RelocationEntry REHigher(SectionID,
1384 StubTargetAddr - Section.getAddress() + 4,
1385 ELF::R_MIPS_HIGHER, Value.Addend);
1386 RelocationEntry REHi(SectionID,
1387 StubTargetAddr - Section.getAddress() + 12,
1388 ELF::R_MIPS_HI16, Value.Addend);
1389 RelocationEntry RELo(SectionID,
1390 StubTargetAddr - Section.getAddress() + 20,
1391 ELF::R_MIPS_LO16, Value.Addend);
1392 if (Value.SymbolName) {
1393 addRelocationForSymbol(REHighest, Value.SymbolName);
1394 addRelocationForSymbol(REHigher, Value.SymbolName);
1395 addRelocationForSymbol(REHi, Value.SymbolName);
1396 addRelocationForSymbol(RELo, Value.SymbolName);
1397 } else {
1398 addRelocationForSection(REHighest, Value.SectionID);
1399 addRelocationForSection(REHigher, Value.SectionID);
1400 addRelocationForSection(REHi, Value.SectionID);
1401 addRelocationForSection(RELo, Value.SectionID);
1404 RelocationEntry RE(SectionID, Offset, RelType, Section.getStubOffset());
1405 addRelocationForSection(RE, SectionID);
1406 Section.advanceStubOffset(getMaxStubSize());
1408 } else {
1409 processSimpleRelocation(SectionID, Offset, RelType, Value);
1412 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1413 if (RelType == ELF::R_PPC64_REL24) {
1414 // Determine ABI variant in use for this object.
1415 unsigned AbiVariant;
1416 Obj.getPlatformFlags(AbiVariant);
1417 AbiVariant &= ELF::EF_PPC64_ABI;
1418 // A PPC branch relocation will need a stub function if the target is
1419 // an external symbol (either Value.SymbolName is set, or SymType is
1420 // Symbol::ST_Unknown) or if the target address is not within the
1421 // signed 24-bits branch address.
1422 SectionEntry &Section = Sections[SectionID];
1423 uint8_t *Target = Section.getAddressWithOffset(Offset);
1424 bool RangeOverflow = false;
1425 if (!Value.SymbolName && SymType != SymbolRef::ST_Unknown) {
1426 if (AbiVariant != 2) {
1427 // In the ELFv1 ABI, a function call may point to the .opd entry,
1428 // so the final symbol value is calculated based on the relocation
1429 // values in the .opd section.
1430 if (auto Err = findOPDEntrySection(Obj, ObjSectionToID, Value))
1431 return std::move(Err);
1432 } else {
1433 // In the ELFv2 ABI, a function symbol may provide a local entry
1434 // point, which must be used for direct calls.
1435 uint8_t SymOther = Symbol->getOther();
1436 Value.Addend += ELF::decodePPC64LocalEntryOffset(SymOther);
1438 uint8_t *RelocTarget =
1439 Sections[Value.SectionID].getAddressWithOffset(Value.Addend);
1440 int64_t delta = static_cast<int64_t>(Target - RelocTarget);
1441 // If it is within 26-bits branch range, just set the branch target
1442 if (SignExtend64<26>(delta) == delta) {
1443 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1444 addRelocationForSection(RE, Value.SectionID);
1445 } else {
1446 RangeOverflow = true;
1449 if (Value.SymbolName || SymType == SymbolRef::ST_Unknown ||
1450 RangeOverflow) {
1451 // It is an external symbol (either Value.SymbolName is set, or
1452 // SymType is SymbolRef::ST_Unknown) or out of range.
1453 StubMap::const_iterator i = Stubs.find(Value);
1454 if (i != Stubs.end()) {
1455 // Symbol function stub already created, just relocate to it
1456 resolveRelocation(Section, Offset,
1457 reinterpret_cast<uint64_t>(
1458 Section.getAddressWithOffset(i->second)),
1459 RelType, 0);
1460 DEBUG(dbgs() << " Stub function found\n");
1461 } else {
1462 // Create a new stub function.
1463 DEBUG(dbgs() << " Create a new stub function\n");
1464 Stubs[Value] = Section.getStubOffset();
1465 uint8_t *StubTargetAddr = createStubFunction(
1466 Section.getAddressWithOffset(Section.getStubOffset()),
1467 AbiVariant);
1468 RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(),
1469 ELF::R_PPC64_ADDR64, Value.Addend);
1471 // Generates the 64-bits address loads as exemplified in section
1472 // 4.5.1 in PPC64 ELF ABI. Note that the relocations need to
1473 // apply to the low part of the instructions, so we have to update
1474 // the offset according to the target endianness.
1475 uint64_t StubRelocOffset = StubTargetAddr - Section.getAddress();
1476 if (!IsTargetLittleEndian)
1477 StubRelocOffset += 2;
1479 RelocationEntry REhst(SectionID, StubRelocOffset + 0,
1480 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1481 RelocationEntry REhr(SectionID, StubRelocOffset + 4,
1482 ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1483 RelocationEntry REh(SectionID, StubRelocOffset + 12,
1484 ELF::R_PPC64_ADDR16_HI, Value.Addend);
1485 RelocationEntry REl(SectionID, StubRelocOffset + 16,
1486 ELF::R_PPC64_ADDR16_LO, Value.Addend);
1488 if (Value.SymbolName) {
1489 addRelocationForSymbol(REhst, Value.SymbolName);
1490 addRelocationForSymbol(REhr, Value.SymbolName);
1491 addRelocationForSymbol(REh, Value.SymbolName);
1492 addRelocationForSymbol(REl, Value.SymbolName);
1493 } else {
1494 addRelocationForSection(REhst, Value.SectionID);
1495 addRelocationForSection(REhr, Value.SectionID);
1496 addRelocationForSection(REh, Value.SectionID);
1497 addRelocationForSection(REl, Value.SectionID);
1500 resolveRelocation(Section, Offset, reinterpret_cast<uint64_t>(
1501 Section.getAddressWithOffset(
1502 Section.getStubOffset())),
1503 RelType, 0);
1504 Section.advanceStubOffset(getMaxStubSize());
1506 if (Value.SymbolName || SymType == SymbolRef::ST_Unknown) {
1507 // Restore the TOC for external calls
1508 if (AbiVariant == 2)
1509 writeInt32BE(Target + 4, 0xE8410018); // ld r2,28(r1)
1510 else
1511 writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1)
1514 } else if (RelType == ELF::R_PPC64_TOC16 ||
1515 RelType == ELF::R_PPC64_TOC16_DS ||
1516 RelType == ELF::R_PPC64_TOC16_LO ||
1517 RelType == ELF::R_PPC64_TOC16_LO_DS ||
1518 RelType == ELF::R_PPC64_TOC16_HI ||
1519 RelType == ELF::R_PPC64_TOC16_HA) {
1520 // These relocations are supposed to subtract the TOC address from
1521 // the final value. This does not fit cleanly into the RuntimeDyld
1522 // scheme, since there may be *two* sections involved in determining
1523 // the relocation value (the section of the symbol referred to by the
1524 // relocation, and the TOC section associated with the current module).
1526 // Fortunately, these relocations are currently only ever generated
1527 // referring to symbols that themselves reside in the TOC, which means
1528 // that the two sections are actually the same. Thus they cancel out
1529 // and we can immediately resolve the relocation right now.
1530 switch (RelType) {
1531 case ELF::R_PPC64_TOC16: RelType = ELF::R_PPC64_ADDR16; break;
1532 case ELF::R_PPC64_TOC16_DS: RelType = ELF::R_PPC64_ADDR16_DS; break;
1533 case ELF::R_PPC64_TOC16_LO: RelType = ELF::R_PPC64_ADDR16_LO; break;
1534 case ELF::R_PPC64_TOC16_LO_DS: RelType = ELF::R_PPC64_ADDR16_LO_DS; break;
1535 case ELF::R_PPC64_TOC16_HI: RelType = ELF::R_PPC64_ADDR16_HI; break;
1536 case ELF::R_PPC64_TOC16_HA: RelType = ELF::R_PPC64_ADDR16_HA; break;
1537 default: llvm_unreachable("Wrong relocation type.");
1540 RelocationValueRef TOCValue;
1541 if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, TOCValue))
1542 return std::move(Err);
1543 if (Value.SymbolName || Value.SectionID != TOCValue.SectionID)
1544 llvm_unreachable("Unsupported TOC relocation.");
1545 Value.Addend -= TOCValue.Addend;
1546 resolveRelocation(Sections[SectionID], Offset, Value.Addend, RelType, 0);
1547 } else {
1548 // There are two ways to refer to the TOC address directly: either
1549 // via a ELF::R_PPC64_TOC relocation (where both symbol and addend are
1550 // ignored), or via any relocation that refers to the magic ".TOC."
1551 // symbols (in which case the addend is respected).
1552 if (RelType == ELF::R_PPC64_TOC) {
1553 RelType = ELF::R_PPC64_ADDR64;
1554 if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, Value))
1555 return std::move(Err);
1556 } else if (TargetName == ".TOC.") {
1557 if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, Value))
1558 return std::move(Err);
1559 Value.Addend += Addend;
1562 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1564 if (Value.SymbolName)
1565 addRelocationForSymbol(RE, Value.SymbolName);
1566 else
1567 addRelocationForSection(RE, Value.SectionID);
1569 } else if (Arch == Triple::systemz &&
1570 (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
1571 // Create function stubs for both PLT and GOT references, regardless of
1572 // whether the GOT reference is to data or code. The stub contains the
1573 // full address of the symbol, as needed by GOT references, and the
1574 // executable part only adds an overhead of 8 bytes.
1576 // We could try to conserve space by allocating the code and data
1577 // parts of the stub separately. However, as things stand, we allocate
1578 // a stub for every relocation, so using a GOT in JIT code should be
1579 // no less space efficient than using an explicit constant pool.
1580 DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1581 SectionEntry &Section = Sections[SectionID];
1583 // Look for an existing stub.
1584 StubMap::const_iterator i = Stubs.find(Value);
1585 uintptr_t StubAddress;
1586 if (i != Stubs.end()) {
1587 StubAddress = uintptr_t(Section.getAddressWithOffset(i->second));
1588 DEBUG(dbgs() << " Stub function found\n");
1589 } else {
1590 // Create a new stub function.
1591 DEBUG(dbgs() << " Create a new stub function\n");
1593 uintptr_t BaseAddress = uintptr_t(Section.getAddress());
1594 uintptr_t StubAlignment = getStubAlignment();
1595 StubAddress =
1596 (BaseAddress + Section.getStubOffset() + StubAlignment - 1) &
1597 -StubAlignment;
1598 unsigned StubOffset = StubAddress - BaseAddress;
1600 Stubs[Value] = StubOffset;
1601 createStubFunction((uint8_t *)StubAddress);
1602 RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64,
1603 Value.Offset);
1604 if (Value.SymbolName)
1605 addRelocationForSymbol(RE, Value.SymbolName);
1606 else
1607 addRelocationForSection(RE, Value.SectionID);
1608 Section.advanceStubOffset(getMaxStubSize());
1611 if (RelType == ELF::R_390_GOTENT)
1612 resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL,
1613 Addend);
1614 else
1615 resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1616 } else if (Arch == Triple::x86_64) {
1617 if (RelType == ELF::R_X86_64_PLT32) {
1618 // The way the PLT relocations normally work is that the linker allocates
1619 // the
1620 // PLT and this relocation makes a PC-relative call into the PLT. The PLT
1621 // entry will then jump to an address provided by the GOT. On first call,
1622 // the
1623 // GOT address will point back into PLT code that resolves the symbol. After
1624 // the first call, the GOT entry points to the actual function.
1626 // For local functions we're ignoring all of that here and just replacing
1627 // the PLT32 relocation type with PC32, which will translate the relocation
1628 // into a PC-relative call directly to the function. For external symbols we
1629 // can't be sure the function will be within 2^32 bytes of the call site, so
1630 // we need to create a stub, which calls into the GOT. This case is
1631 // equivalent to the usual PLT implementation except that we use the stub
1632 // mechanism in RuntimeDyld (which puts stubs at the end of the section)
1633 // rather than allocating a PLT section.
1634 if (Value.SymbolName) {
1635 // This is a call to an external function.
1636 // Look for an existing stub.
1637 SectionEntry &Section = Sections[SectionID];
1638 StubMap::const_iterator i = Stubs.find(Value);
1639 uintptr_t StubAddress;
1640 if (i != Stubs.end()) {
1641 StubAddress = uintptr_t(Section.getAddress()) + i->second;
1642 DEBUG(dbgs() << " Stub function found\n");
1643 } else {
1644 // Create a new stub function (equivalent to a PLT entry).
1645 DEBUG(dbgs() << " Create a new stub function\n");
1647 uintptr_t BaseAddress = uintptr_t(Section.getAddress());
1648 uintptr_t StubAlignment = getStubAlignment();
1649 StubAddress =
1650 (BaseAddress + Section.getStubOffset() + StubAlignment - 1) &
1651 -StubAlignment;
1652 unsigned StubOffset = StubAddress - BaseAddress;
1653 Stubs[Value] = StubOffset;
1654 createStubFunction((uint8_t *)StubAddress);
1656 // Bump our stub offset counter
1657 Section.advanceStubOffset(getMaxStubSize());
1659 // Allocate a GOT Entry
1660 uint64_t GOTOffset = allocateGOTEntries(1);
1662 // The load of the GOT address has an addend of -4
1663 resolveGOTOffsetRelocation(SectionID, StubOffset + 2, GOTOffset - 4,
1664 ELF::R_X86_64_PC32);
1666 // Fill in the value of the symbol we're targeting into the GOT
1667 addRelocationForSymbol(
1668 computeGOTOffsetRE(GOTOffset, 0, ELF::R_X86_64_64),
1669 Value.SymbolName);
1672 // Make the target call a call into the stub table.
1673 resolveRelocation(Section, Offset, StubAddress, ELF::R_X86_64_PC32,
1674 Addend);
1675 } else {
1676 RelocationEntry RE(SectionID, Offset, ELF::R_X86_64_PC32, Value.Addend,
1677 Value.Offset);
1678 addRelocationForSection(RE, Value.SectionID);
1680 } else if (RelType == ELF::R_X86_64_GOTPCREL ||
1681 RelType == ELF::R_X86_64_GOTPCRELX ||
1682 RelType == ELF::R_X86_64_REX_GOTPCRELX) {
1683 uint64_t GOTOffset = allocateGOTEntries(1);
1684 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1685 ELF::R_X86_64_PC32);
1687 // Fill in the value of the symbol we're targeting into the GOT
1688 RelocationEntry RE =
1689 computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_64);
1690 if (Value.SymbolName)
1691 addRelocationForSymbol(RE, Value.SymbolName);
1692 else
1693 addRelocationForSection(RE, Value.SectionID);
1694 } else if (RelType == ELF::R_X86_64_PC32) {
1695 Value.Addend += support::ulittle32_t::ref(computePlaceholderAddress(SectionID, Offset));
1696 processSimpleRelocation(SectionID, Offset, RelType, Value);
1697 } else if (RelType == ELF::R_X86_64_PC64) {
1698 Value.Addend += support::ulittle64_t::ref(computePlaceholderAddress(SectionID, Offset));
1699 processSimpleRelocation(SectionID, Offset, RelType, Value);
1700 } else {
1701 processSimpleRelocation(SectionID, Offset, RelType, Value);
1703 } else {
1704 if (Arch == Triple::x86) {
1705 Value.Addend += support::ulittle32_t::ref(computePlaceholderAddress(SectionID, Offset));
1707 processSimpleRelocation(SectionID, Offset, RelType, Value);
1709 return ++RelI;
1712 size_t RuntimeDyldELF::getGOTEntrySize() {
1713 // We don't use the GOT in all of these cases, but it's essentially free
1714 // to put them all here.
1715 size_t Result = 0;
1716 switch (Arch) {
1717 case Triple::x86_64:
1718 case Triple::aarch64:
1719 case Triple::aarch64_be:
1720 case Triple::ppc64:
1721 case Triple::ppc64le:
1722 case Triple::systemz:
1723 Result = sizeof(uint64_t);
1724 break;
1725 case Triple::x86:
1726 case Triple::arm:
1727 case Triple::thumb:
1728 Result = sizeof(uint32_t);
1729 break;
1730 case Triple::mips:
1731 case Triple::mipsel:
1732 case Triple::mips64:
1733 case Triple::mips64el:
1734 if (IsMipsO32ABI || IsMipsN32ABI)
1735 Result = sizeof(uint32_t);
1736 else if (IsMipsN64ABI)
1737 Result = sizeof(uint64_t);
1738 else
1739 llvm_unreachable("Mips ABI not handled");
1740 break;
1741 default:
1742 llvm_unreachable("Unsupported CPU type!");
1744 return Result;
1747 uint64_t RuntimeDyldELF::allocateGOTEntries(unsigned no) {
1748 if (GOTSectionID == 0) {
1749 GOTSectionID = Sections.size();
1750 // Reserve a section id. We'll allocate the section later
1751 // once we know the total size
1752 Sections.push_back(SectionEntry(".got", nullptr, 0, 0, 0));
1754 uint64_t StartOffset = CurrentGOTIndex * getGOTEntrySize();
1755 CurrentGOTIndex += no;
1756 return StartOffset;
1759 uint64_t RuntimeDyldELF::findOrAllocGOTEntry(const RelocationValueRef &Value,
1760 unsigned GOTRelType) {
1761 auto E = GOTOffsetMap.insert({Value, 0});
1762 if (E.second) {
1763 uint64_t GOTOffset = allocateGOTEntries(1);
1765 // Create relocation for newly created GOT entry
1766 RelocationEntry RE =
1767 computeGOTOffsetRE(GOTOffset, Value.Offset, GOTRelType);
1768 if (Value.SymbolName)
1769 addRelocationForSymbol(RE, Value.SymbolName);
1770 else
1771 addRelocationForSection(RE, Value.SectionID);
1773 E.first->second = GOTOffset;
1776 return E.first->second;
1779 void RuntimeDyldELF::resolveGOTOffsetRelocation(unsigned SectionID,
1780 uint64_t Offset,
1781 uint64_t GOTOffset,
1782 uint32_t Type) {
1783 // Fill in the relative address of the GOT Entry into the stub
1784 RelocationEntry GOTRE(SectionID, Offset, Type, GOTOffset);
1785 addRelocationForSection(GOTRE, GOTSectionID);
1788 RelocationEntry RuntimeDyldELF::computeGOTOffsetRE(uint64_t GOTOffset,
1789 uint64_t SymbolOffset,
1790 uint32_t Type) {
1791 return RelocationEntry(GOTSectionID, GOTOffset, Type, SymbolOffset);
1794 Error RuntimeDyldELF::finalizeLoad(const ObjectFile &Obj,
1795 ObjSectionToIDMap &SectionMap) {
1796 if (IsMipsO32ABI)
1797 if (!PendingRelocs.empty())
1798 return make_error<RuntimeDyldError>("Can't find matching LO16 reloc");
1800 // If necessary, allocate the global offset table
1801 if (GOTSectionID != 0) {
1802 // Allocate memory for the section
1803 size_t TotalSize = CurrentGOTIndex * getGOTEntrySize();
1804 uint8_t *Addr = MemMgr.allocateDataSection(TotalSize, getGOTEntrySize(),
1805 GOTSectionID, ".got", false);
1806 if (!Addr)
1807 return make_error<RuntimeDyldError>("Unable to allocate memory for GOT!");
1809 Sections[GOTSectionID] =
1810 SectionEntry(".got", Addr, TotalSize, TotalSize, 0);
1812 if (Checker)
1813 Checker->registerSection(Obj.getFileName(), GOTSectionID);
1815 // For now, initialize all GOT entries to zero. We'll fill them in as
1816 // needed when GOT-based relocations are applied.
1817 memset(Addr, 0, TotalSize);
1818 if (IsMipsN32ABI || IsMipsN64ABI) {
1819 // To correctly resolve Mips GOT relocations, we need a mapping from
1820 // object's sections to GOTs.
1821 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
1822 SI != SE; ++SI) {
1823 if (SI->relocation_begin() != SI->relocation_end()) {
1824 section_iterator RelocatedSection = SI->getRelocatedSection();
1825 ObjSectionToIDMap::iterator i = SectionMap.find(*RelocatedSection);
1826 assert (i != SectionMap.end());
1827 SectionToGOTMap[i->second] = GOTSectionID;
1830 GOTSymbolOffsets.clear();
1834 // Look for and record the EH frame section.
1835 ObjSectionToIDMap::iterator i, e;
1836 for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
1837 const SectionRef &Section = i->first;
1838 StringRef Name;
1839 Section.getName(Name);
1840 if (Name == ".eh_frame") {
1841 UnregisteredEHFrameSections.push_back(i->second);
1842 break;
1846 GOTSectionID = 0;
1847 CurrentGOTIndex = 0;
1849 return Error::success();
1852 bool RuntimeDyldELF::isCompatibleFile(const object::ObjectFile &Obj) const {
1853 return Obj.isELF();
1856 bool RuntimeDyldELF::relocationNeedsGot(const RelocationRef &R) const {
1857 unsigned RelTy = R.getType();
1858 if (Arch == Triple::aarch64 || Arch == Triple::aarch64_be)
1859 return RelTy == ELF::R_AARCH64_ADR_GOT_PAGE ||
1860 RelTy == ELF::R_AARCH64_LD64_GOT_LO12_NC;
1862 if (Arch == Triple::x86_64)
1863 return RelTy == ELF::R_X86_64_GOTPCREL ||
1864 RelTy == ELF::R_X86_64_GOTPCRELX ||
1865 RelTy == ELF::R_X86_64_REX_GOTPCRELX;
1866 return false;
1869 bool RuntimeDyldELF::relocationNeedsStub(const RelocationRef &R) const {
1870 if (Arch != Triple::x86_64)
1871 return true; // Conservative answer
1873 switch (R.getType()) {
1874 default:
1875 return true; // Conservative answer
1878 case ELF::R_X86_64_GOTPCREL:
1879 case ELF::R_X86_64_GOTPCRELX:
1880 case ELF::R_X86_64_REX_GOTPCRELX:
1881 case ELF::R_X86_64_PC32:
1882 case ELF::R_X86_64_PC64:
1883 case ELF::R_X86_64_64:
1884 // We know that these reloation types won't need a stub function. This list
1885 // can be extended as needed.
1886 return false;
1890 } // namespace llvm