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