LLVM 19.0.0git
RuntimeDyldELF.cpp
Go to the documentation of this file.
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"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/StringRef.h"
21#include "llvm/Support/Endian.h"
24
25using namespace llvm;
26using namespace llvm::object;
27using namespace llvm::support::endian;
28
29#define DEBUG_TYPE "dyld"
30
31static void or32le(void *P, int32_t V) { write32le(P, read32le(P) | V); }
32
33static void or32AArch64Imm(void *L, uint64_t Imm) {
34 or32le(L, (Imm & 0xFFF) << 10);
35}
36
37template <class T> static void write(bool isBE, void *P, T V) {
38 isBE ? write<T, llvm::endianness::big>(P, V)
39 : write<T, llvm::endianness::little>(P, V);
40}
41
42static 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);
47}
48
49// Return the bits [Start, End] from Val shifted Start bits.
50// For instance, getBits(0xF0, 4, 8) returns 0xF.
51static 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;
54}
55
56namespace {
57
58template <class ELFT> class DyldELFObject : public ELFObjectFile<ELFT> {
60
61 typedef typename ELFT::uint addr_type;
62
63 DyldELFObject(ELFObjectFile<ELFT> &&Obj);
64
65public:
68
69 void updateSectionAddress(const SectionRef &Sec, uint64_t Addr);
70
71 void updateSymbolAddress(const SymbolRef &SymRef, uint64_t Addr);
72
73 // Methods for type inquiry through isa, cast and dyn_cast
74 static bool classof(const Binary *v) {
75 return (isa<ELFObjectFile<ELFT>>(v) &&
77 }
78 static bool classof(const ELFObjectFile<ELFT> *v) {
79 return v->isDyldType();
80 }
81};
82
83
84
85// The MemoryBuffer passed into this constructor is just a wrapper around the
86// actual memory. Ultimately, the Binary parent class will take ownership of
87// this MemoryBuffer object but not the underlying memory.
88template <class ELFT>
89DyldELFObject<ELFT>::DyldELFObject(ELFObjectFile<ELFT> &&Obj)
90 : ELFObjectFile<ELFT>(std::move(Obj)) {
91 this->isDyldELFObject = true;
92}
93
94template <class ELFT>
96DyldELFObject<ELFT>::create(MemoryBufferRef Wrapper) {
98 if (auto E = Obj.takeError())
99 return std::move(E);
100 std::unique_ptr<DyldELFObject<ELFT>> Ret(
101 new DyldELFObject<ELFT>(std::move(*Obj)));
102 return std::move(Ret);
103}
104
105template <class ELFT>
106void DyldELFObject<ELFT>::updateSectionAddress(const SectionRef &Sec,
107 uint64_t Addr) {
108 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
109 Elf_Shdr *shdr =
110 const_cast<Elf_Shdr *>(reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
111
112 // This assumes the address passed in matches the target address bitness
113 // The template-based type cast handles everything else.
114 shdr->sh_addr = static_cast<addr_type>(Addr);
115}
116
117template <class ELFT>
118void DyldELFObject<ELFT>::updateSymbolAddress(const SymbolRef &SymRef,
119 uint64_t Addr) {
120
121 Elf_Sym *sym = const_cast<Elf_Sym *>(
123
124 // This assumes the address passed in matches the target address bitness
125 // The template-based type cast handles everything else.
126 sym->st_value = static_cast<addr_type>(Addr);
127}
128
129class LoadedELFObjectInfo final
130 : public LoadedObjectInfoHelper<LoadedELFObjectInfo,
131 RuntimeDyld::LoadedObjectInfo> {
132public:
133 LoadedELFObjectInfo(RuntimeDyldImpl &RTDyld, ObjSectionToIDMap ObjSecToIDMap)
134 : LoadedObjectInfoHelper(RTDyld, std::move(ObjSecToIDMap)) {}
135
137 getObjectForDebug(const ObjectFile &Obj) const override;
138};
139
140template <typename ELFT>
142createRTDyldELFObject(MemoryBufferRef Buffer, const ObjectFile &SourceObject,
143 const LoadedELFObjectInfo &L) {
144 typedef typename ELFT::Shdr Elf_Shdr;
145 typedef typename ELFT::uint addr_type;
146
148 DyldELFObject<ELFT>::create(Buffer);
149 if (Error E = ObjOrErr.takeError())
150 return std::move(E);
151
152 std::unique_ptr<DyldELFObject<ELFT>> Obj = std::move(*ObjOrErr);
153
154 // Iterate over all sections in the object.
155 auto SI = SourceObject.section_begin();
156 for (const auto &Sec : Obj->sections()) {
157 Expected<StringRef> NameOrErr = Sec.getName();
158 if (!NameOrErr) {
159 consumeError(NameOrErr.takeError());
160 continue;
161 }
162
163 if (*NameOrErr != "") {
164 DataRefImpl ShdrRef = Sec.getRawDataRefImpl();
165 Elf_Shdr *shdr = const_cast<Elf_Shdr *>(
166 reinterpret_cast<const Elf_Shdr *>(ShdrRef.p));
167
168 if (uint64_t SecLoadAddr = L.getSectionLoadAddress(*SI)) {
169 // This assumes that the address passed in matches the target address
170 // bitness. The template-based type cast handles everything else.
171 shdr->sh_addr = static_cast<addr_type>(SecLoadAddr);
172 }
173 }
174 ++SI;
175 }
176
177 return std::move(Obj);
178}
179
181createELFDebugObject(const ObjectFile &Obj, const LoadedELFObjectInfo &L) {
182 assert(Obj.isELF() && "Not an ELF object file.");
183
184 std::unique_ptr<MemoryBuffer> Buffer =
186
187 Expected<std::unique_ptr<ObjectFile>> DebugObj(nullptr);
188 handleAllErrors(DebugObj.takeError());
189 if (Obj.getBytesInAddress() == 4 && Obj.isLittleEndian())
190 DebugObj =
191 createRTDyldELFObject<ELF32LE>(Buffer->getMemBufferRef(), Obj, L);
192 else if (Obj.getBytesInAddress() == 4 && !Obj.isLittleEndian())
193 DebugObj =
194 createRTDyldELFObject<ELF32BE>(Buffer->getMemBufferRef(), Obj, L);
195 else if (Obj.getBytesInAddress() == 8 && !Obj.isLittleEndian())
196 DebugObj =
197 createRTDyldELFObject<ELF64BE>(Buffer->getMemBufferRef(), Obj, L);
198 else if (Obj.getBytesInAddress() == 8 && Obj.isLittleEndian())
199 DebugObj =
200 createRTDyldELFObject<ELF64LE>(Buffer->getMemBufferRef(), Obj, L);
201 else
202 llvm_unreachable("Unexpected ELF format");
203
204 handleAllErrors(DebugObj.takeError());
205 return OwningBinary<ObjectFile>(std::move(*DebugObj), std::move(Buffer));
206}
207
209LoadedELFObjectInfo::getObjectForDebug(const ObjectFile &Obj) const {
210 return createELFDebugObject(Obj, *this);
211}
212
213} // anonymous namespace
214
215namespace llvm {
216
219 : RuntimeDyldImpl(MemMgr, Resolver), GOTSectionID(0), CurrentGOTIndex(0) {}
221
223 for (int i = 0, e = UnregisteredEHFrameSections.size(); i != e; ++i) {
224 SID EHFrameSID = UnregisteredEHFrameSections[i];
225 uint8_t *EHFrameAddr = Sections[EHFrameSID].getAddress();
226 uint64_t EHFrameLoadAddr = Sections[EHFrameSID].getLoadAddress();
227 size_t EHFrameSize = Sections[EHFrameSID].getSize();
228 MemMgr.registerEHFrames(EHFrameAddr, EHFrameLoadAddr, EHFrameSize);
229 }
230 UnregisteredEHFrameSections.clear();
231}
232
233std::unique_ptr<RuntimeDyldELF>
237 switch (Arch) {
238 default:
239 return std::make_unique<RuntimeDyldELF>(MemMgr, Resolver);
240 case Triple::mips:
241 case Triple::mipsel:
242 case Triple::mips64:
243 case Triple::mips64el:
244 return std::make_unique<RuntimeDyldELFMips>(MemMgr, Resolver);
245 }
246}
247
248std::unique_ptr<RuntimeDyld::LoadedObjectInfo>
250 if (auto ObjSectionToIDOrErr = loadObjectImpl(O))
251 return std::make_unique<LoadedELFObjectInfo>(*this, *ObjSectionToIDOrErr);
252 else {
253 HasError = true;
254 raw_string_ostream ErrStream(ErrorStr);
255 logAllUnhandledErrors(ObjSectionToIDOrErr.takeError(), ErrStream);
256 return nullptr;
257 }
258}
259
260void RuntimeDyldELF::resolveX86_64Relocation(const SectionEntry &Section,
262 uint32_t Type, int64_t Addend,
263 uint64_t SymOffset) {
264 switch (Type) {
265 default:
266 report_fatal_error("Relocation type not implemented yet!");
267 break;
268 case ELF::R_X86_64_NONE:
269 break;
270 case ELF::R_X86_64_8: {
271 Value += Addend;
272 assert((int64_t)Value <= INT8_MAX && (int64_t)Value >= INT8_MIN);
273 uint8_t TruncatedAddr = (Value & 0xFF);
274 *Section.getAddressWithOffset(Offset) = TruncatedAddr;
275 LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
276 << format("%p\n", Section.getAddressWithOffset(Offset)));
277 break;
278 }
279 case ELF::R_X86_64_16: {
280 Value += Addend;
281 assert((int64_t)Value <= INT16_MAX && (int64_t)Value >= INT16_MIN);
282 uint16_t TruncatedAddr = (Value & 0xFFFF);
283 support::ulittle16_t::ref(Section.getAddressWithOffset(Offset)) =
284 TruncatedAddr;
285 LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
286 << format("%p\n", Section.getAddressWithOffset(Offset)));
287 break;
288 }
289 case ELF::R_X86_64_64: {
290 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
291 Value + Addend;
292 LLVM_DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
293 << format("%p\n", Section.getAddressWithOffset(Offset)));
294 break;
295 }
296 case ELF::R_X86_64_32:
297 case ELF::R_X86_64_32S: {
298 Value += Addend;
299 assert((Type == ELF::R_X86_64_32 && (Value <= UINT32_MAX)) ||
300 (Type == ELF::R_X86_64_32S &&
301 ((int64_t)Value <= INT32_MAX && (int64_t)Value >= INT32_MIN)));
302 uint32_t TruncatedAddr = (Value & 0xFFFFFFFF);
303 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
304 TruncatedAddr;
305 LLVM_DEBUG(dbgs() << "Writing " << format("%p", TruncatedAddr) << " at "
306 << format("%p\n", Section.getAddressWithOffset(Offset)));
307 break;
308 }
309 case ELF::R_X86_64_PC8: {
310 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
311 int64_t RealOffset = Value + Addend - FinalAddress;
312 assert(isInt<8>(RealOffset));
313 int8_t TruncOffset = (RealOffset & 0xFF);
314 Section.getAddress()[Offset] = TruncOffset;
315 break;
316 }
317 case ELF::R_X86_64_PC32: {
318 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
319 int64_t RealOffset = Value + Addend - FinalAddress;
320 assert(isInt<32>(RealOffset));
321 int32_t TruncOffset = (RealOffset & 0xFFFFFFFF);
322 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
323 TruncOffset;
324 break;
325 }
326 case ELF::R_X86_64_PC64: {
327 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
328 int64_t RealOffset = Value + Addend - FinalAddress;
329 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
330 RealOffset;
331 LLVM_DEBUG(dbgs() << "Writing " << format("%p", RealOffset) << " at "
332 << format("%p\n", FinalAddress));
333 break;
334 }
335 case ELF::R_X86_64_GOTOFF64: {
336 // Compute Value - GOTBase.
337 uint64_t GOTBase = 0;
338 for (const auto &Section : Sections) {
339 if (Section.getName() == ".got") {
340 GOTBase = Section.getLoadAddressWithOffset(0);
341 break;
342 }
343 }
344 assert(GOTBase != 0 && "missing GOT");
345 int64_t GOTOffset = Value - GOTBase + Addend;
346 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) = GOTOffset;
347 break;
348 }
349 case ELF::R_X86_64_DTPMOD64: {
350 // We only have one DSO, so the module id is always 1.
351 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) = 1;
352 break;
353 }
354 case ELF::R_X86_64_DTPOFF64:
355 case ELF::R_X86_64_TPOFF64: {
356 // DTPOFF64 should resolve to the offset in the TLS block, TPOFF64 to the
357 // offset in the *initial* TLS block. Since we are statically linking, all
358 // TLS blocks already exist in the initial block, so resolve both
359 // relocations equally.
360 support::ulittle64_t::ref(Section.getAddressWithOffset(Offset)) =
361 Value + Addend;
362 break;
363 }
364 case ELF::R_X86_64_DTPOFF32:
365 case ELF::R_X86_64_TPOFF32: {
366 // As for the (D)TPOFF64 relocations above, both DTPOFF32 and TPOFF32 can
367 // be resolved equally.
368 int64_t RealValue = Value + Addend;
369 assert(RealValue >= INT32_MIN && RealValue <= INT32_MAX);
370 int32_t TruncValue = RealValue;
371 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
372 TruncValue;
373 break;
374 }
375 }
376}
377
378void RuntimeDyldELF::resolveX86Relocation(const SectionEntry &Section,
380 uint32_t Type, int32_t Addend) {
381 switch (Type) {
382 case ELF::R_386_32: {
383 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
384 Value + Addend;
385 break;
386 }
387 // Handle R_386_PLT32 like R_386_PC32 since it should be able to
388 // reach any 32 bit address.
389 case ELF::R_386_PLT32:
390 case ELF::R_386_PC32: {
391 uint32_t FinalAddress =
392 Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
393 uint32_t RealOffset = Value + Addend - FinalAddress;
394 support::ulittle32_t::ref(Section.getAddressWithOffset(Offset)) =
395 RealOffset;
396 break;
397 }
398 default:
399 // There are other relocation types, but it appears these are the
400 // only ones currently used by the LLVM ELF object writer
401 report_fatal_error("Relocation type not implemented yet!");
402 break;
403 }
404}
405
406void RuntimeDyldELF::resolveAArch64Relocation(const SectionEntry &Section,
408 uint32_t Type, int64_t Addend) {
409 uint32_t *TargetPtr =
410 reinterpret_cast<uint32_t *>(Section.getAddressWithOffset(Offset));
411 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
412 // Data should use target endian. Code should always use little endian.
413 bool isBE = Arch == Triple::aarch64_be;
414
415 LLVM_DEBUG(dbgs() << "resolveAArch64Relocation, LocalAddress: 0x"
416 << format("%llx", Section.getAddressWithOffset(Offset))
417 << " FinalAddress: 0x" << format("%llx", FinalAddress)
418 << " Value: 0x" << format("%llx", Value) << " Type: 0x"
419 << format("%x", Type) << " Addend: 0x"
420 << format("%llx", Addend) << "\n");
421
422 switch (Type) {
423 default:
424 report_fatal_error("Relocation type not implemented yet!");
425 break;
426 case ELF::R_AARCH64_NONE:
427 break;
428 case ELF::R_AARCH64_ABS16: {
429 uint64_t Result = Value + Addend;
430 assert(Result == static_cast<uint64_t>(llvm::SignExtend64(Result, 16)) ||
431 (Result >> 16) == 0);
432 write(isBE, TargetPtr, static_cast<uint16_t>(Result & 0xffffU));
433 break;
434 }
435 case ELF::R_AARCH64_ABS32: {
436 uint64_t Result = Value + Addend;
437 assert(Result == static_cast<uint64_t>(llvm::SignExtend64(Result, 32)) ||
438 (Result >> 32) == 0);
439 write(isBE, TargetPtr, static_cast<uint32_t>(Result & 0xffffffffU));
440 break;
441 }
442 case ELF::R_AARCH64_ABS64:
443 write(isBE, TargetPtr, Value + Addend);
444 break;
445 case ELF::R_AARCH64_PLT32: {
446 uint64_t Result = Value + Addend - FinalAddress;
447 assert(static_cast<int64_t>(Result) >= INT32_MIN &&
448 static_cast<int64_t>(Result) <= INT32_MAX);
449 write(isBE, TargetPtr, static_cast<uint32_t>(Result));
450 break;
451 }
452 case ELF::R_AARCH64_PREL16: {
453 uint64_t Result = Value + Addend - FinalAddress;
454 assert(static_cast<int64_t>(Result) >= INT16_MIN &&
455 static_cast<int64_t>(Result) <= UINT16_MAX);
456 write(isBE, TargetPtr, static_cast<uint16_t>(Result & 0xffffU));
457 break;
458 }
459 case ELF::R_AARCH64_PREL32: {
460 uint64_t Result = Value + Addend - FinalAddress;
461 assert(static_cast<int64_t>(Result) >= INT32_MIN &&
462 static_cast<int64_t>(Result) <= UINT32_MAX);
463 write(isBE, TargetPtr, static_cast<uint32_t>(Result & 0xffffffffU));
464 break;
465 }
466 case ELF::R_AARCH64_PREL64:
467 write(isBE, TargetPtr, Value + Addend - FinalAddress);
468 break;
469 case ELF::R_AARCH64_CONDBR19: {
470 uint64_t BranchImm = Value + Addend - FinalAddress;
471
472 assert(isInt<21>(BranchImm));
473 *TargetPtr &= 0xff00001fU;
474 // Immediate:20:2 goes in bits 23:5 of Bcc, CBZ, CBNZ
475 or32le(TargetPtr, (BranchImm & 0x001FFFFC) << 3);
476 break;
477 }
478 case ELF::R_AARCH64_TSTBR14: {
479 uint64_t BranchImm = Value + Addend - FinalAddress;
480
481 assert(isInt<16>(BranchImm));
482
483 uint32_t RawInstr = *(support::little32_t *)TargetPtr;
484 *(support::little32_t *)TargetPtr = RawInstr & 0xfff8001fU;
485
486 // Immediate:15:2 goes in bits 18:5 of TBZ, TBNZ
487 or32le(TargetPtr, (BranchImm & 0x0000FFFC) << 3);
488 break;
489 }
490 case ELF::R_AARCH64_CALL26: // fallthrough
491 case ELF::R_AARCH64_JUMP26: {
492 // Operation: S+A-P. Set Call or B immediate value to bits fff_fffc of the
493 // calculation.
494 uint64_t BranchImm = Value + Addend - FinalAddress;
495
496 // "Check that -2^27 <= result < 2^27".
497 assert(isInt<28>(BranchImm));
498 or32le(TargetPtr, (BranchImm & 0x0FFFFFFC) >> 2);
499 break;
500 }
501 case ELF::R_AARCH64_MOVW_UABS_G3:
502 or32le(TargetPtr, ((Value + Addend) & 0xFFFF000000000000) >> 43);
503 break;
504 case ELF::R_AARCH64_MOVW_UABS_G2_NC:
505 or32le(TargetPtr, ((Value + Addend) & 0xFFFF00000000) >> 27);
506 break;
507 case ELF::R_AARCH64_MOVW_UABS_G1_NC:
508 or32le(TargetPtr, ((Value + Addend) & 0xFFFF0000) >> 11);
509 break;
510 case ELF::R_AARCH64_MOVW_UABS_G0_NC:
511 or32le(TargetPtr, ((Value + Addend) & 0xFFFF) << 5);
512 break;
513 case ELF::R_AARCH64_ADR_PREL_PG_HI21: {
514 // Operation: Page(S+A) - Page(P)
516 ((Value + Addend) & ~0xfffULL) - (FinalAddress & ~0xfffULL);
517
518 // Check that -2^32 <= X < 2^32
519 assert(isInt<33>(Result) && "overflow check failed for relocation");
520
521 // Immediate goes in bits 30:29 + 5:23 of ADRP instruction, taken
522 // from bits 32:12 of X.
523 write32AArch64Addr(TargetPtr, Result >> 12);
524 break;
525 }
526 case ELF::R_AARCH64_ADD_ABS_LO12_NC:
527 // Operation: S + A
528 // Immediate goes in bits 21:10 of LD/ST instruction, taken
529 // from bits 11:0 of X
530 or32AArch64Imm(TargetPtr, Value + Addend);
531 break;
532 case ELF::R_AARCH64_LDST8_ABS_LO12_NC:
533 // Operation: S + A
534 // Immediate goes in bits 21:10 of LD/ST instruction, taken
535 // from bits 11:0 of X
536 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 0, 11));
537 break;
538 case ELF::R_AARCH64_LDST16_ABS_LO12_NC:
539 // Operation: S + A
540 // Immediate goes in bits 21:10 of LD/ST instruction, taken
541 // from bits 11:1 of X
542 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 1, 11));
543 break;
544 case ELF::R_AARCH64_LDST32_ABS_LO12_NC:
545 // Operation: S + A
546 // Immediate goes in bits 21:10 of LD/ST instruction, taken
547 // from bits 11:2 of X
548 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 2, 11));
549 break;
550 case ELF::R_AARCH64_LDST64_ABS_LO12_NC:
551 // Operation: S + A
552 // Immediate goes in bits 21:10 of LD/ST instruction, taken
553 // from bits 11:3 of X
554 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 3, 11));
555 break;
556 case ELF::R_AARCH64_LDST128_ABS_LO12_NC:
557 // Operation: S + A
558 // Immediate goes in bits 21:10 of LD/ST instruction, taken
559 // from bits 11:4 of X
560 or32AArch64Imm(TargetPtr, getBits(Value + Addend, 4, 11));
561 break;
562 case ELF::R_AARCH64_LD_PREL_LO19: {
563 // Operation: S + A - P
564 uint64_t Result = Value + Addend - FinalAddress;
565
566 // "Check that -2^20 <= result < 2^20".
567 assert(isInt<21>(Result));
568
569 *TargetPtr &= 0xff00001fU;
570 // Immediate goes in bits 23:5 of LD imm instruction, taken
571 // from bits 20:2 of X
572 *TargetPtr |= ((Result & 0xffc) << (5 - 2));
573 break;
574 }
575 case ELF::R_AARCH64_ADR_PREL_LO21: {
576 // Operation: S + A - P
577 uint64_t Result = Value + Addend - FinalAddress;
578
579 // "Check that -2^20 <= result < 2^20".
580 assert(isInt<21>(Result));
581
582 *TargetPtr &= 0x9f00001fU;
583 // Immediate goes in bits 23:5, 30:29 of ADR imm instruction, taken
584 // from bits 20:0 of X
585 *TargetPtr |= ((Result & 0xffc) << (5 - 2));
586 *TargetPtr |= (Result & 0x3) << 29;
587 break;
588 }
589 }
590}
591
592void RuntimeDyldELF::resolveARMRelocation(const SectionEntry &Section,
594 uint32_t Type, int32_t Addend) {
595 // TODO: Add Thumb relocations.
596 uint32_t *TargetPtr =
597 reinterpret_cast<uint32_t *>(Section.getAddressWithOffset(Offset));
598 uint32_t FinalAddress = Section.getLoadAddressWithOffset(Offset) & 0xFFFFFFFF;
599 Value += Addend;
600
601 LLVM_DEBUG(dbgs() << "resolveARMRelocation, LocalAddress: "
602 << Section.getAddressWithOffset(Offset)
603 << " FinalAddress: " << format("%p", FinalAddress)
604 << " Value: " << format("%x", Value)
605 << " Type: " << format("%x", Type)
606 << " Addend: " << format("%x", Addend) << "\n");
607
608 switch (Type) {
609 default:
610 llvm_unreachable("Not implemented relocation type!");
611
612 case ELF::R_ARM_NONE:
613 break;
614 // Write a 31bit signed offset
615 case ELF::R_ARM_PREL31:
616 support::ulittle32_t::ref{TargetPtr} =
617 (support::ulittle32_t::ref{TargetPtr} & 0x80000000) |
618 ((Value - FinalAddress) & ~0x80000000);
619 break;
620 case ELF::R_ARM_TARGET1:
621 case ELF::R_ARM_ABS32:
622 support::ulittle32_t::ref{TargetPtr} = Value;
623 break;
624 // Write first 16 bit of 32 bit value to the mov instruction.
625 // Last 4 bit should be shifted.
626 case ELF::R_ARM_MOVW_ABS_NC:
627 case ELF::R_ARM_MOVT_ABS:
628 if (Type == ELF::R_ARM_MOVW_ABS_NC)
629 Value = Value & 0xFFFF;
630 else if (Type == ELF::R_ARM_MOVT_ABS)
631 Value = (Value >> 16) & 0xFFFF;
632 support::ulittle32_t::ref{TargetPtr} =
633 (support::ulittle32_t::ref{TargetPtr} & ~0x000F0FFF) | (Value & 0xFFF) |
634 (((Value >> 12) & 0xF) << 16);
635 break;
636 // Write 24 bit relative value to the branch instruction.
637 case ELF::R_ARM_PC24: // Fall through.
638 case ELF::R_ARM_CALL: // Fall through.
639 case ELF::R_ARM_JUMP24:
640 int32_t RelValue = static_cast<int32_t>(Value - FinalAddress - 8);
641 RelValue = (RelValue & 0x03FFFFFC) >> 2;
642 assert((support::ulittle32_t::ref{TargetPtr} & 0xFFFFFF) == 0xFFFFFE);
643 support::ulittle32_t::ref{TargetPtr} =
644 (support::ulittle32_t::ref{TargetPtr} & 0xFF000000) | RelValue;
645 break;
646 }
647}
648
649void RuntimeDyldELF::setMipsABI(const ObjectFile &Obj) {
650 if (Arch == Triple::UnknownArch ||
651 Triple::getArchTypePrefix(Arch) != "mips") {
652 IsMipsO32ABI = false;
653 IsMipsN32ABI = false;
654 IsMipsN64ABI = false;
655 return;
656 }
657 if (auto *E = dyn_cast<ELFObjectFileBase>(&Obj)) {
658 unsigned AbiVariant = E->getPlatformFlags();
659 IsMipsO32ABI = AbiVariant & ELF::EF_MIPS_ABI_O32;
660 IsMipsN32ABI = AbiVariant & ELF::EF_MIPS_ABI2;
661 }
662 IsMipsN64ABI = Obj.getFileFormatName() == "elf64-mips";
663}
664
665// Return the .TOC. section and offset.
666Error RuntimeDyldELF::findPPC64TOCSection(const ELFObjectFileBase &Obj,
667 ObjSectionToIDMap &LocalSections,
668 RelocationValueRef &Rel) {
669 // Set a default SectionID in case we do not find a TOC section below.
670 // This may happen for references to TOC base base (sym@toc, .odp
671 // relocation) without a .toc directive. In this case just use the
672 // first section (which is usually the .odp) since the code won't
673 // reference the .toc base directly.
674 Rel.SymbolName = nullptr;
675 Rel.SectionID = 0;
676
677 // The TOC consists of sections .got, .toc, .tocbss, .plt in that
678 // order. The TOC starts where the first of these sections starts.
679 for (auto &Section : Obj.sections()) {
680 Expected<StringRef> NameOrErr = Section.getName();
681 if (!NameOrErr)
682 return NameOrErr.takeError();
683 StringRef SectionName = *NameOrErr;
684
685 if (SectionName == ".got"
686 || SectionName == ".toc"
687 || SectionName == ".tocbss"
688 || SectionName == ".plt") {
689 if (auto SectionIDOrErr =
690 findOrEmitSection(Obj, Section, false, LocalSections))
691 Rel.SectionID = *SectionIDOrErr;
692 else
693 return SectionIDOrErr.takeError();
694 break;
695 }
696 }
697
698 // Per the ppc64-elf-linux ABI, The TOC base is TOC value plus 0x8000
699 // thus permitting a full 64 Kbytes segment.
700 Rel.Addend = 0x8000;
701
702 return Error::success();
703}
704
705// Returns the sections and offset associated with the ODP entry referenced
706// by Symbol.
707Error RuntimeDyldELF::findOPDEntrySection(const ELFObjectFileBase &Obj,
708 ObjSectionToIDMap &LocalSections,
709 RelocationValueRef &Rel) {
710 // Get the ELF symbol value (st_value) to compare with Relocation offset in
711 // .opd entries
712 for (section_iterator si = Obj.section_begin(), se = Obj.section_end();
713 si != se; ++si) {
714
715 Expected<section_iterator> RelSecOrErr = si->getRelocatedSection();
716 if (!RelSecOrErr)
718
719 section_iterator RelSecI = *RelSecOrErr;
720 if (RelSecI == Obj.section_end())
721 continue;
722
723 Expected<StringRef> NameOrErr = RelSecI->getName();
724 if (!NameOrErr)
725 return NameOrErr.takeError();
726 StringRef RelSectionName = *NameOrErr;
727
728 if (RelSectionName != ".opd")
729 continue;
730
731 for (elf_relocation_iterator i = si->relocation_begin(),
732 e = si->relocation_end();
733 i != e;) {
734 // The R_PPC64_ADDR64 relocation indicates the first field
735 // of a .opd entry
736 uint64_t TypeFunc = i->getType();
737 if (TypeFunc != ELF::R_PPC64_ADDR64) {
738 ++i;
739 continue;
740 }
741
742 uint64_t TargetSymbolOffset = i->getOffset();
743 symbol_iterator TargetSymbol = i->getSymbol();
744 int64_t Addend;
745 if (auto AddendOrErr = i->getAddend())
746 Addend = *AddendOrErr;
747 else
748 return AddendOrErr.takeError();
749
750 ++i;
751 if (i == e)
752 break;
753
754 // Just check if following relocation is a R_PPC64_TOC
755 uint64_t TypeTOC = i->getType();
756 if (TypeTOC != ELF::R_PPC64_TOC)
757 continue;
758
759 // Finally compares the Symbol value and the target symbol offset
760 // to check if this .opd entry refers to the symbol the relocation
761 // points to.
762 if (Rel.Addend != (int64_t)TargetSymbolOffset)
763 continue;
764
765 section_iterator TSI = Obj.section_end();
766 if (auto TSIOrErr = TargetSymbol->getSection())
767 TSI = *TSIOrErr;
768 else
769 return TSIOrErr.takeError();
770 assert(TSI != Obj.section_end() && "TSI should refer to a valid section");
771
772 bool IsCode = TSI->isText();
773 if (auto SectionIDOrErr = findOrEmitSection(Obj, *TSI, IsCode,
774 LocalSections))
775 Rel.SectionID = *SectionIDOrErr;
776 else
777 return SectionIDOrErr.takeError();
778 Rel.Addend = (intptr_t)Addend;
779 return Error::success();
780 }
781 }
782 llvm_unreachable("Attempting to get address of ODP entry!");
783}
784
785// Relocation masks following the #lo(value), #hi(value), #ha(value),
786// #higher(value), #highera(value), #highest(value), and #highesta(value)
787// macros defined in section 4.5.1. Relocation Types of the PPC-elf64abi
788// document.
789
790static inline uint16_t applyPPClo(uint64_t value) { return value & 0xffff; }
791
793 return (value >> 16) & 0xffff;
794}
795
797 return ((value + 0x8000) >> 16) & 0xffff;
798}
799
801 return (value >> 32) & 0xffff;
802}
803
805 return ((value + 0x8000) >> 32) & 0xffff;
806}
807
809 return (value >> 48) & 0xffff;
810}
811
813 return ((value + 0x8000) >> 48) & 0xffff;
814}
815
816void RuntimeDyldELF::resolvePPC32Relocation(const SectionEntry &Section,
818 uint32_t Type, int64_t Addend) {
819 uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
820 switch (Type) {
821 default:
822 report_fatal_error("Relocation type not implemented yet!");
823 break;
824 case ELF::R_PPC_ADDR16_LO:
825 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
826 break;
827 case ELF::R_PPC_ADDR16_HI:
828 writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
829 break;
830 case ELF::R_PPC_ADDR16_HA:
831 writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
832 break;
833 }
834}
835
836void RuntimeDyldELF::resolvePPC64Relocation(const SectionEntry &Section,
838 uint32_t Type, int64_t Addend) {
839 uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
840 switch (Type) {
841 default:
842 report_fatal_error("Relocation type not implemented yet!");
843 break;
844 case ELF::R_PPC64_ADDR16:
845 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
846 break;
847 case ELF::R_PPC64_ADDR16_DS:
848 writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
849 break;
850 case ELF::R_PPC64_ADDR16_LO:
851 writeInt16BE(LocalAddress, applyPPClo(Value + Addend));
852 break;
853 case ELF::R_PPC64_ADDR16_LO_DS:
854 writeInt16BE(LocalAddress, applyPPClo(Value + Addend) & ~3);
855 break;
856 case ELF::R_PPC64_ADDR16_HI:
857 case ELF::R_PPC64_ADDR16_HIGH:
858 writeInt16BE(LocalAddress, applyPPChi(Value + Addend));
859 break;
860 case ELF::R_PPC64_ADDR16_HA:
861 case ELF::R_PPC64_ADDR16_HIGHA:
862 writeInt16BE(LocalAddress, applyPPCha(Value + Addend));
863 break;
864 case ELF::R_PPC64_ADDR16_HIGHER:
865 writeInt16BE(LocalAddress, applyPPChigher(Value + Addend));
866 break;
867 case ELF::R_PPC64_ADDR16_HIGHERA:
868 writeInt16BE(LocalAddress, applyPPChighera(Value + Addend));
869 break;
870 case ELF::R_PPC64_ADDR16_HIGHEST:
871 writeInt16BE(LocalAddress, applyPPChighest(Value + Addend));
872 break;
873 case ELF::R_PPC64_ADDR16_HIGHESTA:
874 writeInt16BE(LocalAddress, applyPPChighesta(Value + Addend));
875 break;
876 case ELF::R_PPC64_ADDR14: {
877 assert(((Value + Addend) & 3) == 0);
878 // Preserve the AA/LK bits in the branch instruction
879 uint8_t aalk = *(LocalAddress + 3);
880 writeInt16BE(LocalAddress + 2, (aalk & 3) | ((Value + Addend) & 0xfffc));
881 } break;
882 case ELF::R_PPC64_REL16_LO: {
883 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
884 uint64_t Delta = Value - FinalAddress + Addend;
885 writeInt16BE(LocalAddress, applyPPClo(Delta));
886 } break;
887 case ELF::R_PPC64_REL16_HI: {
888 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
889 uint64_t Delta = Value - FinalAddress + Addend;
890 writeInt16BE(LocalAddress, applyPPChi(Delta));
891 } break;
892 case ELF::R_PPC64_REL16_HA: {
893 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
894 uint64_t Delta = Value - FinalAddress + Addend;
895 writeInt16BE(LocalAddress, applyPPCha(Delta));
896 } break;
897 case ELF::R_PPC64_ADDR32: {
898 int64_t Result = static_cast<int64_t>(Value + Addend);
899 if (SignExtend64<32>(Result) != Result)
900 llvm_unreachable("Relocation R_PPC64_ADDR32 overflow");
901 writeInt32BE(LocalAddress, Result);
902 } break;
903 case ELF::R_PPC64_REL24: {
904 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
905 int64_t delta = static_cast<int64_t>(Value - FinalAddress + Addend);
906 if (SignExtend64<26>(delta) != delta)
907 llvm_unreachable("Relocation R_PPC64_REL24 overflow");
908 // We preserve bits other than LI field, i.e. PO and AA/LK fields.
909 uint32_t Inst = readBytesUnaligned(LocalAddress, 4);
910 writeInt32BE(LocalAddress, (Inst & 0xFC000003) | (delta & 0x03FFFFFC));
911 } break;
912 case ELF::R_PPC64_REL32: {
913 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
914 int64_t delta = static_cast<int64_t>(Value - FinalAddress + Addend);
915 if (SignExtend64<32>(delta) != delta)
916 llvm_unreachable("Relocation R_PPC64_REL32 overflow");
917 writeInt32BE(LocalAddress, delta);
918 } break;
919 case ELF::R_PPC64_REL64: {
920 uint64_t FinalAddress = Section.getLoadAddressWithOffset(Offset);
921 uint64_t Delta = Value - FinalAddress + Addend;
922 writeInt64BE(LocalAddress, Delta);
923 } break;
924 case ELF::R_PPC64_ADDR64:
925 writeInt64BE(LocalAddress, Value + Addend);
926 break;
927 }
928}
929
930void RuntimeDyldELF::resolveSystemZRelocation(const SectionEntry &Section,
932 uint32_t Type, int64_t Addend) {
933 uint8_t *LocalAddress = Section.getAddressWithOffset(Offset);
934 switch (Type) {
935 default:
936 report_fatal_error("Relocation type not implemented yet!");
937 break;
938 case ELF::R_390_PC16DBL:
939 case ELF::R_390_PLT16DBL: {
940 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
941 assert(int16_t(Delta / 2) * 2 == Delta && "R_390_PC16DBL overflow");
942 writeInt16BE(LocalAddress, Delta / 2);
943 break;
944 }
945 case ELF::R_390_PC32DBL:
946 case ELF::R_390_PLT32DBL: {
947 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
948 assert(int32_t(Delta / 2) * 2 == Delta && "R_390_PC32DBL overflow");
949 writeInt32BE(LocalAddress, Delta / 2);
950 break;
951 }
952 case ELF::R_390_PC16: {
953 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
954 assert(int16_t(Delta) == Delta && "R_390_PC16 overflow");
955 writeInt16BE(LocalAddress, Delta);
956 break;
957 }
958 case ELF::R_390_PC32: {
959 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
960 assert(int32_t(Delta) == Delta && "R_390_PC32 overflow");
961 writeInt32BE(LocalAddress, Delta);
962 break;
963 }
964 case ELF::R_390_PC64: {
965 int64_t Delta = (Value + Addend) - Section.getLoadAddressWithOffset(Offset);
966 writeInt64BE(LocalAddress, Delta);
967 break;
968 }
969 case ELF::R_390_8:
970 *LocalAddress = (uint8_t)(Value + Addend);
971 break;
972 case ELF::R_390_16:
973 writeInt16BE(LocalAddress, Value + Addend);
974 break;
975 case ELF::R_390_32:
976 writeInt32BE(LocalAddress, Value + Addend);
977 break;
978 case ELF::R_390_64:
979 writeInt64BE(LocalAddress, Value + Addend);
980 break;
981 }
982}
983
984void RuntimeDyldELF::resolveBPFRelocation(const SectionEntry &Section,
986 uint32_t Type, int64_t Addend) {
987 bool isBE = Arch == Triple::bpfeb;
988
989 switch (Type) {
990 default:
991 report_fatal_error("Relocation type not implemented yet!");
992 break;
993 case ELF::R_BPF_NONE:
994 case ELF::R_BPF_64_64:
995 case ELF::R_BPF_64_32:
996 case ELF::R_BPF_64_NODYLD32:
997 break;
998 case ELF::R_BPF_64_ABS64: {
999 write(isBE, Section.getAddressWithOffset(Offset), Value + Addend);
1000 LLVM_DEBUG(dbgs() << "Writing " << format("%p", (Value + Addend)) << " at "
1001 << format("%p\n", Section.getAddressWithOffset(Offset)));
1002 break;
1003 }
1004 case ELF::R_BPF_64_ABS32: {
1005 Value += Addend;
1006 assert(Value <= UINT32_MAX);
1007 write(isBE, Section.getAddressWithOffset(Offset), static_cast<uint32_t>(Value));
1008 LLVM_DEBUG(dbgs() << "Writing " << format("%p", Value) << " at "
1009 << format("%p\n", Section.getAddressWithOffset(Offset)));
1010 break;
1011 }
1012 }
1013}
1014
1015// The target location for the relocation is described by RE.SectionID and
1016// RE.Offset. RE.SectionID can be used to find the SectionEntry. Each
1017// SectionEntry has three members describing its location.
1018// SectionEntry::Address is the address at which the section has been loaded
1019// into memory in the current (host) process. SectionEntry::LoadAddress is the
1020// address that the section will have in the target process.
1021// SectionEntry::ObjAddress is the address of the bits for this section in the
1022// original emitted object image (also in the current address space).
1023//
1024// Relocations will be applied as if the section were loaded at
1025// SectionEntry::LoadAddress, but they will be applied at an address based
1026// on SectionEntry::Address. SectionEntry::ObjAddress will be used to refer to
1027// Target memory contents if they are required for value calculations.
1028//
1029// The Value parameter here is the load address of the symbol for the
1030// relocation to be applied. For relocations which refer to symbols in the
1031// current object Value will be the LoadAddress of the section in which
1032// the symbol resides (RE.Addend provides additional information about the
1033// symbol location). For external symbols, Value will be the address of the
1034// symbol in the target address space.
1035void RuntimeDyldELF::resolveRelocation(const RelocationEntry &RE,
1036 uint64_t Value) {
1037 const SectionEntry &Section = Sections[RE.SectionID];
1038 return resolveRelocation(Section, RE.Offset, Value, RE.RelType, RE.Addend,
1039 RE.SymOffset, RE.SectionID);
1040}
1041
1042void RuntimeDyldELF::resolveRelocation(const SectionEntry &Section,
1044 uint32_t Type, int64_t Addend,
1045 uint64_t SymOffset, SID SectionID) {
1046 switch (Arch) {
1047 case Triple::x86_64:
1048 resolveX86_64Relocation(Section, Offset, Value, Type, Addend, SymOffset);
1049 break;
1050 case Triple::x86:
1051 resolveX86Relocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
1052 (uint32_t)(Addend & 0xffffffffL));
1053 break;
1054 case Triple::aarch64:
1055 case Triple::aarch64_be:
1056 resolveAArch64Relocation(Section, Offset, Value, Type, Addend);
1057 break;
1058 case Triple::arm: // Fall through.
1059 case Triple::armeb:
1060 case Triple::thumb:
1061 case Triple::thumbeb:
1062 resolveARMRelocation(Section, Offset, (uint32_t)(Value & 0xffffffffL), Type,
1063 (uint32_t)(Addend & 0xffffffffL));
1064 break;
1065 case Triple::ppc: // Fall through.
1066 case Triple::ppcle:
1067 resolvePPC32Relocation(Section, Offset, Value, Type, Addend);
1068 break;
1069 case Triple::ppc64: // Fall through.
1070 case Triple::ppc64le:
1071 resolvePPC64Relocation(Section, Offset, Value, Type, Addend);
1072 break;
1073 case Triple::systemz:
1074 resolveSystemZRelocation(Section, Offset, Value, Type, Addend);
1075 break;
1076 case Triple::bpfel:
1077 case Triple::bpfeb:
1078 resolveBPFRelocation(Section, Offset, Value, Type, Addend);
1079 break;
1080 default:
1081 llvm_unreachable("Unsupported CPU type!");
1082 }
1083}
1084
1085void *RuntimeDyldELF::computePlaceholderAddress(unsigned SectionID, uint64_t Offset) const {
1086 return (void *)(Sections[SectionID].getObjAddress() + Offset);
1087}
1088
1089void RuntimeDyldELF::processSimpleRelocation(unsigned SectionID, uint64_t Offset, unsigned RelType, RelocationValueRef Value) {
1090 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend, Value.Offset);
1091 if (Value.SymbolName)
1092 addRelocationForSymbol(RE, Value.SymbolName);
1093 else
1094 addRelocationForSection(RE, Value.SectionID);
1095}
1096
1097uint32_t RuntimeDyldELF::getMatchingLoRelocation(uint32_t RelType,
1098 bool IsLocal) const {
1099 switch (RelType) {
1100 case ELF::R_MICROMIPS_GOT16:
1101 if (IsLocal)
1102 return ELF::R_MICROMIPS_LO16;
1103 break;
1104 case ELF::R_MICROMIPS_HI16:
1105 return ELF::R_MICROMIPS_LO16;
1106 case ELF::R_MIPS_GOT16:
1107 if (IsLocal)
1108 return ELF::R_MIPS_LO16;
1109 break;
1110 case ELF::R_MIPS_HI16:
1111 return ELF::R_MIPS_LO16;
1112 case ELF::R_MIPS_PCHI16:
1113 return ELF::R_MIPS_PCLO16;
1114 default:
1115 break;
1116 }
1117 return ELF::R_MIPS_NONE;
1118}
1119
1120// Sometimes we don't need to create thunk for a branch.
1121// This typically happens when branch target is located
1122// in the same object file. In such case target is either
1123// a weak symbol or symbol in a different executable section.
1124// This function checks if branch target is located in the
1125// same object file and if distance between source and target
1126// fits R_AARCH64_CALL26 relocation. If both conditions are
1127// met, it emits direct jump to the target and returns true.
1128// Otherwise false is returned and thunk is created.
1129bool RuntimeDyldELF::resolveAArch64ShortBranch(
1130 unsigned SectionID, relocation_iterator RelI,
1131 const RelocationValueRef &Value) {
1132 uint64_t TargetOffset;
1133 unsigned TargetSectionID;
1134 if (Value.SymbolName) {
1135 auto Loc = GlobalSymbolTable.find(Value.SymbolName);
1136
1137 // Don't create direct branch for external symbols.
1138 if (Loc == GlobalSymbolTable.end())
1139 return false;
1140
1141 const auto &SymInfo = Loc->second;
1142
1143 TargetSectionID = SymInfo.getSectionID();
1144 TargetOffset = SymInfo.getOffset();
1145 } else {
1146 TargetSectionID = Value.SectionID;
1147 TargetOffset = 0;
1148 }
1149
1150 // We don't actually know the load addresses at this point, so if the
1151 // branch is cross-section, we don't know exactly how far away it is.
1152 if (TargetSectionID != SectionID)
1153 return false;
1154
1155 uint64_t SourceOffset = RelI->getOffset();
1156
1157 // R_AARCH64_CALL26 requires immediate to be in range -2^27 <= imm < 2^27
1158 // If distance between source and target is out of range then we should
1159 // create thunk.
1160 if (!isInt<28>(TargetOffset + Value.Addend - SourceOffset))
1161 return false;
1162
1163 RelocationEntry RE(SectionID, SourceOffset, RelI->getType(), Value.Addend);
1164 if (Value.SymbolName)
1165 addRelocationForSymbol(RE, Value.SymbolName);
1166 else
1167 addRelocationForSection(RE, Value.SectionID);
1168
1169 return true;
1170}
1171
1172void RuntimeDyldELF::resolveAArch64Branch(unsigned SectionID,
1175 StubMap &Stubs) {
1176
1177 LLVM_DEBUG(dbgs() << "\t\tThis is an AArch64 branch relocation.");
1178 SectionEntry &Section = Sections[SectionID];
1179
1180 uint64_t Offset = RelI->getOffset();
1181 unsigned RelType = RelI->getType();
1182 // Look for an existing stub.
1183 StubMap::const_iterator i = Stubs.find(Value);
1184 if (i != Stubs.end()) {
1185 resolveRelocation(Section, Offset,
1186 Section.getLoadAddressWithOffset(i->second), RelType, 0);
1187 LLVM_DEBUG(dbgs() << " Stub function found\n");
1188 } else if (!resolveAArch64ShortBranch(SectionID, RelI, Value)) {
1189 // Create a new stub function.
1190 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1191 Stubs[Value] = Section.getStubOffset();
1192 uint8_t *StubTargetAddr = createStubFunction(
1193 Section.getAddressWithOffset(Section.getStubOffset()));
1194
1195 RelocationEntry REmovz_g3(SectionID, StubTargetAddr - Section.getAddress(),
1196 ELF::R_AARCH64_MOVW_UABS_G3, Value.Addend);
1197 RelocationEntry REmovk_g2(SectionID,
1198 StubTargetAddr - Section.getAddress() + 4,
1199 ELF::R_AARCH64_MOVW_UABS_G2_NC, Value.Addend);
1200 RelocationEntry REmovk_g1(SectionID,
1201 StubTargetAddr - Section.getAddress() + 8,
1202 ELF::R_AARCH64_MOVW_UABS_G1_NC, Value.Addend);
1203 RelocationEntry REmovk_g0(SectionID,
1204 StubTargetAddr - Section.getAddress() + 12,
1205 ELF::R_AARCH64_MOVW_UABS_G0_NC, Value.Addend);
1206
1207 if (Value.SymbolName) {
1208 addRelocationForSymbol(REmovz_g3, Value.SymbolName);
1209 addRelocationForSymbol(REmovk_g2, Value.SymbolName);
1210 addRelocationForSymbol(REmovk_g1, Value.SymbolName);
1211 addRelocationForSymbol(REmovk_g0, Value.SymbolName);
1212 } else {
1213 addRelocationForSection(REmovz_g3, Value.SectionID);
1214 addRelocationForSection(REmovk_g2, Value.SectionID);
1215 addRelocationForSection(REmovk_g1, Value.SectionID);
1216 addRelocationForSection(REmovk_g0, Value.SectionID);
1217 }
1218 resolveRelocation(Section, Offset,
1219 Section.getLoadAddressWithOffset(Section.getStubOffset()),
1220 RelType, 0);
1221 Section.advanceStubOffset(getMaxStubSize());
1222 }
1223}
1224
1227 unsigned SectionID, relocation_iterator RelI, const ObjectFile &O,
1228 ObjSectionToIDMap &ObjSectionToID, StubMap &Stubs) {
1229 const auto &Obj = cast<ELFObjectFileBase>(O);
1230 uint64_t RelType = RelI->getType();
1231 int64_t Addend = 0;
1232 if (Expected<int64_t> AddendOrErr = ELFRelocationRef(*RelI).getAddend())
1233 Addend = *AddendOrErr;
1234 else
1235 consumeError(AddendOrErr.takeError());
1236 elf_symbol_iterator Symbol = RelI->getSymbol();
1237
1238 // Obtain the symbol name which is referenced in the relocation
1239 StringRef TargetName;
1240 if (Symbol != Obj.symbol_end()) {
1241 if (auto TargetNameOrErr = Symbol->getName())
1242 TargetName = *TargetNameOrErr;
1243 else
1244 return TargetNameOrErr.takeError();
1245 }
1246 LLVM_DEBUG(dbgs() << "\t\tRelType: " << RelType << " Addend: " << Addend
1247 << " TargetName: " << TargetName << "\n");
1249 // First search for the symbol in the local symbol table
1251
1252 // Search for the symbol in the global symbol table
1254 if (Symbol != Obj.symbol_end()) {
1255 gsi = GlobalSymbolTable.find(TargetName.data());
1256 Expected<SymbolRef::Type> SymTypeOrErr = Symbol->getType();
1257 if (!SymTypeOrErr) {
1258 std::string Buf;
1260 logAllUnhandledErrors(SymTypeOrErr.takeError(), OS);
1261 report_fatal_error(Twine(OS.str()));
1262 }
1263 SymType = *SymTypeOrErr;
1264 }
1265 if (gsi != GlobalSymbolTable.end()) {
1266 const auto &SymInfo = gsi->second;
1267 Value.SectionID = SymInfo.getSectionID();
1268 Value.Offset = SymInfo.getOffset();
1269 Value.Addend = SymInfo.getOffset() + Addend;
1270 } else {
1271 switch (SymType) {
1272 case SymbolRef::ST_Debug: {
1273 // TODO: Now ELF SymbolRef::ST_Debug = STT_SECTION, it's not obviously
1274 // and can be changed by another developers. Maybe best way is add
1275 // a new symbol type ST_Section to SymbolRef and use it.
1276 auto SectionOrErr = Symbol->getSection();
1277 if (!SectionOrErr) {
1278 std::string Buf;
1280 logAllUnhandledErrors(SectionOrErr.takeError(), OS);
1281 report_fatal_error(Twine(OS.str()));
1282 }
1283 section_iterator si = *SectionOrErr;
1284 if (si == Obj.section_end())
1285 llvm_unreachable("Symbol section not found, bad object file format!");
1286 LLVM_DEBUG(dbgs() << "\t\tThis is section symbol\n");
1287 bool isCode = si->isText();
1288 if (auto SectionIDOrErr = findOrEmitSection(Obj, (*si), isCode,
1289 ObjSectionToID))
1290 Value.SectionID = *SectionIDOrErr;
1291 else
1292 return SectionIDOrErr.takeError();
1293 Value.Addend = Addend;
1294 break;
1295 }
1296 case SymbolRef::ST_Data:
1299 case SymbolRef::ST_Unknown: {
1300 Value.SymbolName = TargetName.data();
1301 Value.Addend = Addend;
1302
1303 // Absolute relocations will have a zero symbol ID (STN_UNDEF), which
1304 // will manifest here as a NULL symbol name.
1305 // We can set this as a valid (but empty) symbol name, and rely
1306 // on addRelocationForSymbol to handle this.
1307 if (!Value.SymbolName)
1308 Value.SymbolName = "";
1309 break;
1310 }
1311 default:
1312 llvm_unreachable("Unresolved symbol type!");
1313 break;
1314 }
1315 }
1316
1317 uint64_t Offset = RelI->getOffset();
1318
1319 LLVM_DEBUG(dbgs() << "\t\tSectionID: " << SectionID << " Offset: " << Offset
1320 << "\n");
1322 if ((RelType == ELF::R_AARCH64_CALL26 ||
1323 RelType == ELF::R_AARCH64_JUMP26) &&
1325 resolveAArch64Branch(SectionID, Value, RelI, Stubs);
1326 } else if (RelType == ELF::R_AARCH64_ADR_GOT_PAGE) {
1327 // Create new GOT entry or find existing one. If GOT entry is
1328 // to be created, then we also emit ABS64 relocation for it.
1329 uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_AARCH64_ABS64);
1330 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1331 ELF::R_AARCH64_ADR_PREL_PG_HI21);
1332
1333 } else if (RelType == ELF::R_AARCH64_LD64_GOT_LO12_NC) {
1334 uint64_t GOTOffset = findOrAllocGOTEntry(Value, ELF::R_AARCH64_ABS64);
1335 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1336 ELF::R_AARCH64_LDST64_ABS_LO12_NC);
1337 } else {
1338 processSimpleRelocation(SectionID, Offset, RelType, Value);
1339 }
1340 } else if (Arch == Triple::arm) {
1341 if (RelType == ELF::R_ARM_PC24 || RelType == ELF::R_ARM_CALL ||
1342 RelType == ELF::R_ARM_JUMP24) {
1343 // This is an ARM branch relocation, need to use a stub function.
1344 LLVM_DEBUG(dbgs() << "\t\tThis is an ARM branch relocation.\n");
1345 SectionEntry &Section = Sections[SectionID];
1346
1347 // Look for an existing stub.
1348 StubMap::const_iterator i = Stubs.find(Value);
1349 if (i != Stubs.end()) {
1350 resolveRelocation(Section, Offset,
1351 Section.getLoadAddressWithOffset(i->second), RelType,
1352 0);
1353 LLVM_DEBUG(dbgs() << " Stub function found\n");
1354 } else {
1355 // Create a new stub function.
1356 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1357 Stubs[Value] = Section.getStubOffset();
1358 uint8_t *StubTargetAddr = createStubFunction(
1359 Section.getAddressWithOffset(Section.getStubOffset()));
1360 RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(),
1361 ELF::R_ARM_ABS32, Value.Addend);
1362 if (Value.SymbolName)
1363 addRelocationForSymbol(RE, Value.SymbolName);
1364 else
1365 addRelocationForSection(RE, Value.SectionID);
1366
1367 resolveRelocation(
1368 Section, Offset,
1369 Section.getLoadAddressWithOffset(Section.getStubOffset()), RelType,
1370 0);
1371 Section.advanceStubOffset(getMaxStubSize());
1372 }
1373 } else {
1374 uint32_t *Placeholder =
1375 reinterpret_cast<uint32_t*>(computePlaceholderAddress(SectionID, Offset));
1376 if (RelType == ELF::R_ARM_PREL31 || RelType == ELF::R_ARM_TARGET1 ||
1377 RelType == ELF::R_ARM_ABS32) {
1378 Value.Addend += *Placeholder;
1379 } else if (RelType == ELF::R_ARM_MOVW_ABS_NC || RelType == ELF::R_ARM_MOVT_ABS) {
1380 // See ELF for ARM documentation
1381 Value.Addend += (int16_t)((*Placeholder & 0xFFF) | (((*Placeholder >> 16) & 0xF) << 12));
1382 }
1383 processSimpleRelocation(SectionID, Offset, RelType, Value);
1384 }
1385 } else if (IsMipsO32ABI) {
1386 uint8_t *Placeholder = reinterpret_cast<uint8_t *>(
1387 computePlaceholderAddress(SectionID, Offset));
1388 uint32_t Opcode = readBytesUnaligned(Placeholder, 4);
1389 if (RelType == ELF::R_MIPS_26) {
1390 // This is an Mips branch relocation, need to use a stub function.
1391 LLVM_DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1392 SectionEntry &Section = Sections[SectionID];
1393
1394 // Extract the addend from the instruction.
1395 // We shift up by two since the Value will be down shifted again
1396 // when applying the relocation.
1397 uint32_t Addend = (Opcode & 0x03ffffff) << 2;
1398
1399 Value.Addend += Addend;
1400
1401 // Look up for existing stub.
1402 StubMap::const_iterator i = Stubs.find(Value);
1403 if (i != Stubs.end()) {
1404 RelocationEntry RE(SectionID, Offset, RelType, i->second);
1405 addRelocationForSection(RE, SectionID);
1406 LLVM_DEBUG(dbgs() << " Stub function found\n");
1407 } else {
1408 // Create a new stub function.
1409 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1410 Stubs[Value] = Section.getStubOffset();
1411
1412 unsigned AbiVariant = Obj.getPlatformFlags();
1413
1414 uint8_t *StubTargetAddr = createStubFunction(
1415 Section.getAddressWithOffset(Section.getStubOffset()), AbiVariant);
1416
1417 // Creating Hi and Lo relocations for the filled stub instructions.
1418 RelocationEntry REHi(SectionID, StubTargetAddr - Section.getAddress(),
1419 ELF::R_MIPS_HI16, Value.Addend);
1420 RelocationEntry RELo(SectionID,
1421 StubTargetAddr - Section.getAddress() + 4,
1422 ELF::R_MIPS_LO16, Value.Addend);
1423
1424 if (Value.SymbolName) {
1425 addRelocationForSymbol(REHi, Value.SymbolName);
1426 addRelocationForSymbol(RELo, Value.SymbolName);
1427 } else {
1428 addRelocationForSection(REHi, Value.SectionID);
1429 addRelocationForSection(RELo, Value.SectionID);
1430 }
1431
1432 RelocationEntry RE(SectionID, Offset, RelType, Section.getStubOffset());
1433 addRelocationForSection(RE, SectionID);
1434 Section.advanceStubOffset(getMaxStubSize());
1435 }
1436 } else if (RelType == ELF::R_MIPS_HI16 || RelType == ELF::R_MIPS_PCHI16) {
1437 int64_t Addend = (Opcode & 0x0000ffff) << 16;
1438 RelocationEntry RE(SectionID, Offset, RelType, Addend);
1439 PendingRelocs.push_back(std::make_pair(Value, RE));
1440 } else if (RelType == ELF::R_MIPS_LO16 || RelType == ELF::R_MIPS_PCLO16) {
1441 int64_t Addend = Value.Addend + SignExtend32<16>(Opcode & 0x0000ffff);
1442 for (auto I = PendingRelocs.begin(); I != PendingRelocs.end();) {
1443 const RelocationValueRef &MatchingValue = I->first;
1444 RelocationEntry &Reloc = I->second;
1445 if (MatchingValue == Value &&
1446 RelType == getMatchingLoRelocation(Reloc.RelType) &&
1447 SectionID == Reloc.SectionID) {
1448 Reloc.Addend += Addend;
1449 if (Value.SymbolName)
1450 addRelocationForSymbol(Reloc, Value.SymbolName);
1451 else
1452 addRelocationForSection(Reloc, Value.SectionID);
1453 I = PendingRelocs.erase(I);
1454 } else
1455 ++I;
1456 }
1457 RelocationEntry RE(SectionID, Offset, RelType, Addend);
1458 if (Value.SymbolName)
1459 addRelocationForSymbol(RE, Value.SymbolName);
1460 else
1461 addRelocationForSection(RE, Value.SectionID);
1462 } else {
1463 if (RelType == ELF::R_MIPS_32)
1464 Value.Addend += Opcode;
1465 else if (RelType == ELF::R_MIPS_PC16)
1466 Value.Addend += SignExtend32<18>((Opcode & 0x0000ffff) << 2);
1467 else if (RelType == ELF::R_MIPS_PC19_S2)
1468 Value.Addend += SignExtend32<21>((Opcode & 0x0007ffff) << 2);
1469 else if (RelType == ELF::R_MIPS_PC21_S2)
1470 Value.Addend += SignExtend32<23>((Opcode & 0x001fffff) << 2);
1471 else if (RelType == ELF::R_MIPS_PC26_S2)
1472 Value.Addend += SignExtend32<28>((Opcode & 0x03ffffff) << 2);
1473 processSimpleRelocation(SectionID, Offset, RelType, Value);
1474 }
1475 } else if (IsMipsN32ABI || IsMipsN64ABI) {
1476 uint32_t r_type = RelType & 0xff;
1477 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1478 if (r_type == ELF::R_MIPS_CALL16 || r_type == ELF::R_MIPS_GOT_PAGE
1479 || r_type == ELF::R_MIPS_GOT_DISP) {
1480 StringMap<uint64_t>::iterator i = GOTSymbolOffsets.find(TargetName);
1481 if (i != GOTSymbolOffsets.end())
1482 RE.SymOffset = i->second;
1483 else {
1484 RE.SymOffset = allocateGOTEntries(1);
1485 GOTSymbolOffsets[TargetName] = RE.SymOffset;
1486 }
1487 if (Value.SymbolName)
1488 addRelocationForSymbol(RE, Value.SymbolName);
1489 else
1490 addRelocationForSection(RE, Value.SectionID);
1491 } else if (RelType == ELF::R_MIPS_26) {
1492 // This is an Mips branch relocation, need to use a stub function.
1493 LLVM_DEBUG(dbgs() << "\t\tThis is a Mips branch relocation.");
1494 SectionEntry &Section = Sections[SectionID];
1495
1496 // Look up for existing stub.
1497 StubMap::const_iterator i = Stubs.find(Value);
1498 if (i != Stubs.end()) {
1499 RelocationEntry RE(SectionID, Offset, RelType, i->second);
1500 addRelocationForSection(RE, SectionID);
1501 LLVM_DEBUG(dbgs() << " Stub function found\n");
1502 } else {
1503 // Create a new stub function.
1504 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1505 Stubs[Value] = Section.getStubOffset();
1506
1507 unsigned AbiVariant = Obj.getPlatformFlags();
1508
1509 uint8_t *StubTargetAddr = createStubFunction(
1510 Section.getAddressWithOffset(Section.getStubOffset()), AbiVariant);
1511
1512 if (IsMipsN32ABI) {
1513 // Creating Hi and Lo relocations for the filled stub instructions.
1514 RelocationEntry REHi(SectionID, StubTargetAddr - Section.getAddress(),
1515 ELF::R_MIPS_HI16, Value.Addend);
1516 RelocationEntry RELo(SectionID,
1517 StubTargetAddr - Section.getAddress() + 4,
1518 ELF::R_MIPS_LO16, Value.Addend);
1519 if (Value.SymbolName) {
1520 addRelocationForSymbol(REHi, Value.SymbolName);
1521 addRelocationForSymbol(RELo, Value.SymbolName);
1522 } else {
1523 addRelocationForSection(REHi, Value.SectionID);
1524 addRelocationForSection(RELo, Value.SectionID);
1525 }
1526 } else {
1527 // Creating Highest, Higher, Hi and Lo relocations for the filled stub
1528 // instructions.
1529 RelocationEntry REHighest(SectionID,
1530 StubTargetAddr - Section.getAddress(),
1531 ELF::R_MIPS_HIGHEST, Value.Addend);
1532 RelocationEntry REHigher(SectionID,
1533 StubTargetAddr - Section.getAddress() + 4,
1534 ELF::R_MIPS_HIGHER, Value.Addend);
1535 RelocationEntry REHi(SectionID,
1536 StubTargetAddr - Section.getAddress() + 12,
1537 ELF::R_MIPS_HI16, Value.Addend);
1538 RelocationEntry RELo(SectionID,
1539 StubTargetAddr - Section.getAddress() + 20,
1540 ELF::R_MIPS_LO16, Value.Addend);
1541 if (Value.SymbolName) {
1542 addRelocationForSymbol(REHighest, Value.SymbolName);
1543 addRelocationForSymbol(REHigher, Value.SymbolName);
1544 addRelocationForSymbol(REHi, Value.SymbolName);
1545 addRelocationForSymbol(RELo, Value.SymbolName);
1546 } else {
1547 addRelocationForSection(REHighest, Value.SectionID);
1548 addRelocationForSection(REHigher, Value.SectionID);
1549 addRelocationForSection(REHi, Value.SectionID);
1550 addRelocationForSection(RELo, Value.SectionID);
1551 }
1552 }
1553 RelocationEntry RE(SectionID, Offset, RelType, Section.getStubOffset());
1554 addRelocationForSection(RE, SectionID);
1555 Section.advanceStubOffset(getMaxStubSize());
1556 }
1557 } else {
1558 processSimpleRelocation(SectionID, Offset, RelType, Value);
1559 }
1560
1561 } else if (Arch == Triple::ppc64 || Arch == Triple::ppc64le) {
1562 if (RelType == ELF::R_PPC64_REL24) {
1563 // Determine ABI variant in use for this object.
1564 unsigned AbiVariant = Obj.getPlatformFlags();
1565 AbiVariant &= ELF::EF_PPC64_ABI;
1566 // A PPC branch relocation will need a stub function if the target is
1567 // an external symbol (either Value.SymbolName is set, or SymType is
1568 // Symbol::ST_Unknown) or if the target address is not within the
1569 // signed 24-bits branch address.
1570 SectionEntry &Section = Sections[SectionID];
1571 uint8_t *Target = Section.getAddressWithOffset(Offset);
1572 bool RangeOverflow = false;
1573 bool IsExtern = Value.SymbolName || SymType == SymbolRef::ST_Unknown;
1574 if (!IsExtern) {
1575 if (AbiVariant != 2) {
1576 // In the ELFv1 ABI, a function call may point to the .opd entry,
1577 // so the final symbol value is calculated based on the relocation
1578 // values in the .opd section.
1579 if (auto Err = findOPDEntrySection(Obj, ObjSectionToID, Value))
1580 return std::move(Err);
1581 } else {
1582 // In the ELFv2 ABI, a function symbol may provide a local entry
1583 // point, which must be used for direct calls.
1584 if (Value.SectionID == SectionID){
1585 uint8_t SymOther = Symbol->getOther();
1586 Value.Addend += ELF::decodePPC64LocalEntryOffset(SymOther);
1587 }
1588 }
1589 uint8_t *RelocTarget =
1590 Sections[Value.SectionID].getAddressWithOffset(Value.Addend);
1591 int64_t delta = static_cast<int64_t>(Target - RelocTarget);
1592 // If it is within 26-bits branch range, just set the branch target
1593 if (SignExtend64<26>(delta) != delta) {
1594 RangeOverflow = true;
1595 } else if ((AbiVariant != 2) ||
1596 (AbiVariant == 2 && Value.SectionID == SectionID)) {
1597 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1598 addRelocationForSection(RE, Value.SectionID);
1599 }
1600 }
1601 if (IsExtern || (AbiVariant == 2 && Value.SectionID != SectionID) ||
1602 RangeOverflow) {
1603 // It is an external symbol (either Value.SymbolName is set, or
1604 // SymType is SymbolRef::ST_Unknown) or out of range.
1605 StubMap::const_iterator i = Stubs.find(Value);
1606 if (i != Stubs.end()) {
1607 // Symbol function stub already created, just relocate to it
1608 resolveRelocation(Section, Offset,
1609 Section.getLoadAddressWithOffset(i->second),
1610 RelType, 0);
1611 LLVM_DEBUG(dbgs() << " Stub function found\n");
1612 } else {
1613 // Create a new stub function.
1614 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1615 Stubs[Value] = Section.getStubOffset();
1616 uint8_t *StubTargetAddr = createStubFunction(
1617 Section.getAddressWithOffset(Section.getStubOffset()),
1618 AbiVariant);
1619 RelocationEntry RE(SectionID, StubTargetAddr - Section.getAddress(),
1620 ELF::R_PPC64_ADDR64, Value.Addend);
1621
1622 // Generates the 64-bits address loads as exemplified in section
1623 // 4.5.1 in PPC64 ELF ABI. Note that the relocations need to
1624 // apply to the low part of the instructions, so we have to update
1625 // the offset according to the target endianness.
1626 uint64_t StubRelocOffset = StubTargetAddr - Section.getAddress();
1628 StubRelocOffset += 2;
1629
1630 RelocationEntry REhst(SectionID, StubRelocOffset + 0,
1631 ELF::R_PPC64_ADDR16_HIGHEST, Value.Addend);
1632 RelocationEntry REhr(SectionID, StubRelocOffset + 4,
1633 ELF::R_PPC64_ADDR16_HIGHER, Value.Addend);
1634 RelocationEntry REh(SectionID, StubRelocOffset + 12,
1635 ELF::R_PPC64_ADDR16_HI, Value.Addend);
1636 RelocationEntry REl(SectionID, StubRelocOffset + 16,
1637 ELF::R_PPC64_ADDR16_LO, Value.Addend);
1638
1639 if (Value.SymbolName) {
1640 addRelocationForSymbol(REhst, Value.SymbolName);
1641 addRelocationForSymbol(REhr, Value.SymbolName);
1642 addRelocationForSymbol(REh, Value.SymbolName);
1643 addRelocationForSymbol(REl, Value.SymbolName);
1644 } else {
1645 addRelocationForSection(REhst, Value.SectionID);
1646 addRelocationForSection(REhr, Value.SectionID);
1647 addRelocationForSection(REh, Value.SectionID);
1648 addRelocationForSection(REl, Value.SectionID);
1649 }
1650
1651 resolveRelocation(
1652 Section, Offset,
1653 Section.getLoadAddressWithOffset(Section.getStubOffset()),
1654 RelType, 0);
1655 Section.advanceStubOffset(getMaxStubSize());
1656 }
1657 if (IsExtern || (AbiVariant == 2 && Value.SectionID != SectionID)) {
1658 // Restore the TOC for external calls
1659 if (AbiVariant == 2)
1660 writeInt32BE(Target + 4, 0xE8410018); // ld r2,24(r1)
1661 else
1662 writeInt32BE(Target + 4, 0xE8410028); // ld r2,40(r1)
1663 }
1664 }
1665 } else if (RelType == ELF::R_PPC64_TOC16 ||
1666 RelType == ELF::R_PPC64_TOC16_DS ||
1667 RelType == ELF::R_PPC64_TOC16_LO ||
1668 RelType == ELF::R_PPC64_TOC16_LO_DS ||
1669 RelType == ELF::R_PPC64_TOC16_HI ||
1670 RelType == ELF::R_PPC64_TOC16_HA) {
1671 // These relocations are supposed to subtract the TOC address from
1672 // the final value. This does not fit cleanly into the RuntimeDyld
1673 // scheme, since there may be *two* sections involved in determining
1674 // the relocation value (the section of the symbol referred to by the
1675 // relocation, and the TOC section associated with the current module).
1676 //
1677 // Fortunately, these relocations are currently only ever generated
1678 // referring to symbols that themselves reside in the TOC, which means
1679 // that the two sections are actually the same. Thus they cancel out
1680 // and we can immediately resolve the relocation right now.
1681 switch (RelType) {
1682 case ELF::R_PPC64_TOC16: RelType = ELF::R_PPC64_ADDR16; break;
1683 case ELF::R_PPC64_TOC16_DS: RelType = ELF::R_PPC64_ADDR16_DS; break;
1684 case ELF::R_PPC64_TOC16_LO: RelType = ELF::R_PPC64_ADDR16_LO; break;
1685 case ELF::R_PPC64_TOC16_LO_DS: RelType = ELF::R_PPC64_ADDR16_LO_DS; break;
1686 case ELF::R_PPC64_TOC16_HI: RelType = ELF::R_PPC64_ADDR16_HI; break;
1687 case ELF::R_PPC64_TOC16_HA: RelType = ELF::R_PPC64_ADDR16_HA; break;
1688 default: llvm_unreachable("Wrong relocation type.");
1689 }
1690
1691 RelocationValueRef TOCValue;
1692 if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, TOCValue))
1693 return std::move(Err);
1694 if (Value.SymbolName || Value.SectionID != TOCValue.SectionID)
1695 llvm_unreachable("Unsupported TOC relocation.");
1696 Value.Addend -= TOCValue.Addend;
1697 resolveRelocation(Sections[SectionID], Offset, Value.Addend, RelType, 0);
1698 } else {
1699 // There are two ways to refer to the TOC address directly: either
1700 // via a ELF::R_PPC64_TOC relocation (where both symbol and addend are
1701 // ignored), or via any relocation that refers to the magic ".TOC."
1702 // symbols (in which case the addend is respected).
1703 if (RelType == ELF::R_PPC64_TOC) {
1704 RelType = ELF::R_PPC64_ADDR64;
1705 if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, Value))
1706 return std::move(Err);
1707 } else if (TargetName == ".TOC.") {
1708 if (auto Err = findPPC64TOCSection(Obj, ObjSectionToID, Value))
1709 return std::move(Err);
1710 Value.Addend += Addend;
1711 }
1712
1713 RelocationEntry RE(SectionID, Offset, RelType, Value.Addend);
1714
1715 if (Value.SymbolName)
1716 addRelocationForSymbol(RE, Value.SymbolName);
1717 else
1718 addRelocationForSection(RE, Value.SectionID);
1719 }
1720 } else if (Arch == Triple::systemz &&
1721 (RelType == ELF::R_390_PLT32DBL || RelType == ELF::R_390_GOTENT)) {
1722 // Create function stubs for both PLT and GOT references, regardless of
1723 // whether the GOT reference is to data or code. The stub contains the
1724 // full address of the symbol, as needed by GOT references, and the
1725 // executable part only adds an overhead of 8 bytes.
1726 //
1727 // We could try to conserve space by allocating the code and data
1728 // parts of the stub separately. However, as things stand, we allocate
1729 // a stub for every relocation, so using a GOT in JIT code should be
1730 // no less space efficient than using an explicit constant pool.
1731 LLVM_DEBUG(dbgs() << "\t\tThis is a SystemZ indirect relocation.");
1732 SectionEntry &Section = Sections[SectionID];
1733
1734 // Look for an existing stub.
1735 StubMap::const_iterator i = Stubs.find(Value);
1736 uintptr_t StubAddress;
1737 if (i != Stubs.end()) {
1738 StubAddress = uintptr_t(Section.getAddressWithOffset(i->second));
1739 LLVM_DEBUG(dbgs() << " Stub function found\n");
1740 } else {
1741 // Create a new stub function.
1742 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1743
1744 uintptr_t BaseAddress = uintptr_t(Section.getAddress());
1745 StubAddress =
1746 alignTo(BaseAddress + Section.getStubOffset(), getStubAlignment());
1747 unsigned StubOffset = StubAddress - BaseAddress;
1748
1749 Stubs[Value] = StubOffset;
1750 createStubFunction((uint8_t *)StubAddress);
1751 RelocationEntry RE(SectionID, StubOffset + 8, ELF::R_390_64,
1752 Value.Offset);
1753 if (Value.SymbolName)
1754 addRelocationForSymbol(RE, Value.SymbolName);
1755 else
1756 addRelocationForSection(RE, Value.SectionID);
1757 Section.advanceStubOffset(getMaxStubSize());
1758 }
1759
1760 if (RelType == ELF::R_390_GOTENT)
1761 resolveRelocation(Section, Offset, StubAddress + 8, ELF::R_390_PC32DBL,
1762 Addend);
1763 else
1764 resolveRelocation(Section, Offset, StubAddress, RelType, Addend);
1765 } else if (Arch == Triple::x86_64) {
1766 if (RelType == ELF::R_X86_64_PLT32) {
1767 // The way the PLT relocations normally work is that the linker allocates
1768 // the
1769 // PLT and this relocation makes a PC-relative call into the PLT. The PLT
1770 // entry will then jump to an address provided by the GOT. On first call,
1771 // the
1772 // GOT address will point back into PLT code that resolves the symbol. After
1773 // the first call, the GOT entry points to the actual function.
1774 //
1775 // For local functions we're ignoring all of that here and just replacing
1776 // the PLT32 relocation type with PC32, which will translate the relocation
1777 // into a PC-relative call directly to the function. For external symbols we
1778 // can't be sure the function will be within 2^32 bytes of the call site, so
1779 // we need to create a stub, which calls into the GOT. This case is
1780 // equivalent to the usual PLT implementation except that we use the stub
1781 // mechanism in RuntimeDyld (which puts stubs at the end of the section)
1782 // rather than allocating a PLT section.
1783 if (Value.SymbolName && MemMgr.allowStubAllocation()) {
1784 // This is a call to an external function.
1785 // Look for an existing stub.
1786 SectionEntry *Section = &Sections[SectionID];
1787 StubMap::const_iterator i = Stubs.find(Value);
1788 uintptr_t StubAddress;
1789 if (i != Stubs.end()) {
1790 StubAddress = uintptr_t(Section->getAddress()) + i->second;
1791 LLVM_DEBUG(dbgs() << " Stub function found\n");
1792 } else {
1793 // Create a new stub function (equivalent to a PLT entry).
1794 LLVM_DEBUG(dbgs() << " Create a new stub function\n");
1795
1796 uintptr_t BaseAddress = uintptr_t(Section->getAddress());
1797 StubAddress = alignTo(BaseAddress + Section->getStubOffset(),
1798 getStubAlignment());
1799 unsigned StubOffset = StubAddress - BaseAddress;
1800 Stubs[Value] = StubOffset;
1801 createStubFunction((uint8_t *)StubAddress);
1802
1803 // Bump our stub offset counter
1804 Section->advanceStubOffset(getMaxStubSize());
1805
1806 // Allocate a GOT Entry
1807 uint64_t GOTOffset = allocateGOTEntries(1);
1808 // This potentially creates a new Section which potentially
1809 // invalidates the Section pointer, so reload it.
1810 Section = &Sections[SectionID];
1811
1812 // The load of the GOT address has an addend of -4
1813 resolveGOTOffsetRelocation(SectionID, StubOffset + 2, GOTOffset - 4,
1814 ELF::R_X86_64_PC32);
1815
1816 // Fill in the value of the symbol we're targeting into the GOT
1818 computeGOTOffsetRE(GOTOffset, 0, ELF::R_X86_64_64),
1819 Value.SymbolName);
1820 }
1821
1822 // Make the target call a call into the stub table.
1823 resolveRelocation(*Section, Offset, StubAddress, ELF::R_X86_64_PC32,
1824 Addend);
1825 } else {
1827 computePlaceholderAddress(SectionID, Offset));
1828 processSimpleRelocation(SectionID, Offset, ELF::R_X86_64_PC32, Value);
1829 }
1830 } else if (RelType == ELF::R_X86_64_GOTPCREL ||
1831 RelType == ELF::R_X86_64_GOTPCRELX ||
1832 RelType == ELF::R_X86_64_REX_GOTPCRELX) {
1833 uint64_t GOTOffset = allocateGOTEntries(1);
1834 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
1835 ELF::R_X86_64_PC32);
1836
1837 // Fill in the value of the symbol we're targeting into the GOT
1838 RelocationEntry RE =
1839 computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_64);
1840 if (Value.SymbolName)
1841 addRelocationForSymbol(RE, Value.SymbolName);
1842 else
1843 addRelocationForSection(RE, Value.SectionID);
1844 } else if (RelType == ELF::R_X86_64_GOT64) {
1845 // Fill in a 64-bit GOT offset.
1846 uint64_t GOTOffset = allocateGOTEntries(1);
1847 resolveRelocation(Sections[SectionID], Offset, GOTOffset,
1848 ELF::R_X86_64_64, 0);
1849
1850 // Fill in the value of the symbol we're targeting into the GOT
1851 RelocationEntry RE =
1852 computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_64);
1853 if (Value.SymbolName)
1854 addRelocationForSymbol(RE, Value.SymbolName);
1855 else
1856 addRelocationForSection(RE, Value.SectionID);
1857 } else if (RelType == ELF::R_X86_64_GOTPC32) {
1858 // Materialize the address of the base of the GOT relative to the PC.
1859 // This doesn't create a GOT entry, but it does mean we need a GOT
1860 // section.
1861 (void)allocateGOTEntries(0);
1862 resolveGOTOffsetRelocation(SectionID, Offset, Addend, ELF::R_X86_64_PC32);
1863 } else if (RelType == ELF::R_X86_64_GOTPC64) {
1864 (void)allocateGOTEntries(0);
1865 resolveGOTOffsetRelocation(SectionID, Offset, Addend, ELF::R_X86_64_PC64);
1866 } else if (RelType == ELF::R_X86_64_GOTOFF64) {
1867 // GOTOFF relocations ultimately require a section difference relocation.
1868 (void)allocateGOTEntries(0);
1869 processSimpleRelocation(SectionID, Offset, RelType, Value);
1870 } else if (RelType == ELF::R_X86_64_PC32) {
1871 Value.Addend += support::ulittle32_t::ref(computePlaceholderAddress(SectionID, Offset));
1872 processSimpleRelocation(SectionID, Offset, RelType, Value);
1873 } else if (RelType == ELF::R_X86_64_PC64) {
1874 Value.Addend += support::ulittle64_t::ref(computePlaceholderAddress(SectionID, Offset));
1875 processSimpleRelocation(SectionID, Offset, RelType, Value);
1876 } else if (RelType == ELF::R_X86_64_GOTTPOFF) {
1877 processX86_64GOTTPOFFRelocation(SectionID, Offset, Value, Addend);
1878 } else if (RelType == ELF::R_X86_64_TLSGD ||
1879 RelType == ELF::R_X86_64_TLSLD) {
1880 // The next relocation must be the relocation for __tls_get_addr.
1881 ++RelI;
1882 auto &GetAddrRelocation = *RelI;
1883 processX86_64TLSRelocation(SectionID, Offset, RelType, Value, Addend,
1884 GetAddrRelocation);
1885 } else {
1886 processSimpleRelocation(SectionID, Offset, RelType, Value);
1887 }
1888 } else {
1889 if (Arch == Triple::x86) {
1890 Value.Addend += support::ulittle32_t::ref(computePlaceholderAddress(SectionID, Offset));
1891 }
1892 processSimpleRelocation(SectionID, Offset, RelType, Value);
1893 }
1894 return ++RelI;
1895}
1896
1897void RuntimeDyldELF::processX86_64GOTTPOFFRelocation(unsigned SectionID,
1900 int64_t Addend) {
1901 // Use the approach from "x86-64 Linker Optimizations" from the TLS spec
1902 // to replace the GOTTPOFF relocation with a TPOFF relocation. The spec
1903 // only mentions one optimization even though there are two different
1904 // code sequences for the Initial Exec TLS Model. We match the code to
1905 // find out which one was used.
1906
1907 // A possible TLS code sequence and its replacement
1908 struct CodeSequence {
1909 // The expected code sequence
1910 ArrayRef<uint8_t> ExpectedCodeSequence;
1911 // The negative offset of the GOTTPOFF relocation to the beginning of
1912 // the sequence
1913 uint64_t TLSSequenceOffset;
1914 // The new code sequence
1915 ArrayRef<uint8_t> NewCodeSequence;
1916 // The offset of the new TPOFF relocation
1917 uint64_t TpoffRelocationOffset;
1918 };
1919
1920 std::array<CodeSequence, 2> CodeSequences;
1921
1922 // Initial Exec Code Model Sequence
1923 {
1924 static const std::initializer_list<uint8_t> ExpectedCodeSequenceList = {
1925 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00,
1926 0x00, // mov %fs:0, %rax
1927 0x48, 0x03, 0x05, 0x00, 0x00, 0x00, 0x00 // add x@gotpoff(%rip),
1928 // %rax
1929 };
1930 CodeSequences[0].ExpectedCodeSequence =
1931 ArrayRef<uint8_t>(ExpectedCodeSequenceList);
1932 CodeSequences[0].TLSSequenceOffset = 12;
1933
1934 static const std::initializer_list<uint8_t> NewCodeSequenceList = {
1935 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:0, %rax
1936 0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00 // lea x@tpoff(%rax), %rax
1937 };
1938 CodeSequences[0].NewCodeSequence = ArrayRef<uint8_t>(NewCodeSequenceList);
1939 CodeSequences[0].TpoffRelocationOffset = 12;
1940 }
1941
1942 // Initial Exec Code Model Sequence, II
1943 {
1944 static const std::initializer_list<uint8_t> ExpectedCodeSequenceList = {
1945 0x48, 0x8b, 0x05, 0x00, 0x00, 0x00, 0x00, // mov x@gotpoff(%rip), %rax
1946 0x64, 0x48, 0x8b, 0x00, 0x00, 0x00, 0x00 // mov %fs:(%rax), %rax
1947 };
1948 CodeSequences[1].ExpectedCodeSequence =
1949 ArrayRef<uint8_t>(ExpectedCodeSequenceList);
1950 CodeSequences[1].TLSSequenceOffset = 3;
1951
1952 static const std::initializer_list<uint8_t> NewCodeSequenceList = {
1953 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00, // 6 byte nop
1954 0x64, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00, // mov %fs:x@tpoff, %rax
1955 };
1956 CodeSequences[1].NewCodeSequence = ArrayRef<uint8_t>(NewCodeSequenceList);
1957 CodeSequences[1].TpoffRelocationOffset = 10;
1958 }
1959
1960 bool Resolved = false;
1961 auto &Section = Sections[SectionID];
1962 for (const auto &C : CodeSequences) {
1963 assert(C.ExpectedCodeSequence.size() == C.NewCodeSequence.size() &&
1964 "Old and new code sequences must have the same size");
1965
1966 if (Offset < C.TLSSequenceOffset ||
1967 (Offset - C.TLSSequenceOffset + C.NewCodeSequence.size()) >
1968 Section.getSize()) {
1969 // This can't be a matching sequence as it doesn't fit in the current
1970 // section
1971 continue;
1972 }
1973
1974 auto TLSSequenceStartOffset = Offset - C.TLSSequenceOffset;
1975 auto *TLSSequence = Section.getAddressWithOffset(TLSSequenceStartOffset);
1976 if (ArrayRef<uint8_t>(TLSSequence, C.ExpectedCodeSequence.size()) !=
1977 C.ExpectedCodeSequence) {
1978 continue;
1979 }
1980
1981 memcpy(TLSSequence, C.NewCodeSequence.data(), C.NewCodeSequence.size());
1982
1983 // The original GOTTPOFF relocation has an addend as it is PC relative,
1984 // so it needs to be corrected. The TPOFF32 relocation is used as an
1985 // absolute value (which is an offset from %fs:0), so remove the addend
1986 // again.
1987 RelocationEntry RE(SectionID,
1988 TLSSequenceStartOffset + C.TpoffRelocationOffset,
1989 ELF::R_X86_64_TPOFF32, Value.Addend - Addend);
1990
1991 if (Value.SymbolName)
1992 addRelocationForSymbol(RE, Value.SymbolName);
1993 else
1994 addRelocationForSection(RE, Value.SectionID);
1995
1996 Resolved = true;
1997 break;
1998 }
1999
2000 if (!Resolved) {
2001 // The GOTTPOFF relocation was not used in one of the sequences
2002 // described in the spec, so we can't optimize it to a TPOFF
2003 // relocation.
2004 uint64_t GOTOffset = allocateGOTEntries(1);
2005 resolveGOTOffsetRelocation(SectionID, Offset, GOTOffset + Addend,
2006 ELF::R_X86_64_PC32);
2007 RelocationEntry RE =
2008 computeGOTOffsetRE(GOTOffset, Value.Offset, ELF::R_X86_64_TPOFF64);
2009 if (Value.SymbolName)
2010 addRelocationForSymbol(RE, Value.SymbolName);
2011 else
2012 addRelocationForSection(RE, Value.SectionID);
2013 }
2014}
2015
2016void RuntimeDyldELF::processX86_64TLSRelocation(
2017 unsigned SectionID, uint64_t Offset, uint64_t RelType,
2018 RelocationValueRef Value, int64_t Addend,
2019 const RelocationRef &GetAddrRelocation) {
2020 // Since we are statically linking and have no additional DSOs, we can resolve
2021 // the relocation directly without using __tls_get_addr.
2022 // Use the approach from "x86-64 Linker Optimizations" from the TLS spec
2023 // to replace it with the Local Exec relocation variant.
2024
2025 // Find out whether the code was compiled with the large or small memory
2026 // model. For this we look at the next relocation which is the relocation
2027 // for the __tls_get_addr function. If it's a 32 bit relocation, it's the
2028 // small code model, with a 64 bit relocation it's the large code model.
2029 bool IsSmallCodeModel;
2030 // Is the relocation for the __tls_get_addr a PC-relative GOT relocation?
2031 bool IsGOTPCRel = false;
2032
2033 switch (GetAddrRelocation.getType()) {
2034 case ELF::R_X86_64_GOTPCREL:
2035 case ELF::R_X86_64_REX_GOTPCRELX:
2036 case ELF::R_X86_64_GOTPCRELX:
2037 IsGOTPCRel = true;
2038 [[fallthrough]];
2039 case ELF::R_X86_64_PLT32:
2040 IsSmallCodeModel = true;
2041 break;
2042 case ELF::R_X86_64_PLTOFF64:
2043 IsSmallCodeModel = false;
2044 break;
2045 default:
2047 "invalid TLS relocations for General/Local Dynamic TLS Model: "
2048 "expected PLT or GOT relocation for __tls_get_addr function");
2049 }
2050
2051 // The negative offset to the start of the TLS code sequence relative to
2052 // the offset of the TLSGD/TLSLD relocation
2053 uint64_t TLSSequenceOffset;
2054 // The expected start of the code sequence
2055 ArrayRef<uint8_t> ExpectedCodeSequence;
2056 // The new TLS code sequence that will replace the existing code
2057 ArrayRef<uint8_t> NewCodeSequence;
2058
2059 if (RelType == ELF::R_X86_64_TLSGD) {
2060 // The offset of the new TPOFF32 relocation (offset starting from the
2061 // beginning of the whole TLS sequence)
2062 uint64_t TpoffRelocOffset;
2063
2064 if (IsSmallCodeModel) {
2065 if (!IsGOTPCRel) {
2066 static const std::initializer_list<uint8_t> CodeSequence = {
2067 0x66, // data16 (no-op prefix)
2068 0x48, 0x8d, 0x3d, 0x00, 0x00,
2069 0x00, 0x00, // lea <disp32>(%rip), %rdi
2070 0x66, 0x66, // two data16 prefixes
2071 0x48, // rex64 (no-op prefix)
2072 0xe8, 0x00, 0x00, 0x00, 0x00 // call __tls_get_addr@plt
2073 };
2074 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2075 TLSSequenceOffset = 4;
2076 } else {
2077 // This code sequence is not described in the TLS spec but gcc
2078 // generates it sometimes.
2079 static const std::initializer_list<uint8_t> CodeSequence = {
2080 0x66, // data16 (no-op prefix)
2081 0x48, 0x8d, 0x3d, 0x00, 0x00,
2082 0x00, 0x00, // lea <disp32>(%rip), %rdi
2083 0x66, // data16 prefix (no-op prefix)
2084 0x48, // rex64 (no-op prefix)
2085 0xff, 0x15, 0x00, 0x00, 0x00,
2086 0x00 // call *__tls_get_addr@gotpcrel(%rip)
2087 };
2088 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2089 TLSSequenceOffset = 4;
2090 }
2091
2092 // The replacement code for the small code model. It's the same for
2093 // both sequences.
2094 static const std::initializer_list<uint8_t> SmallSequence = {
2095 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00,
2096 0x00, // mov %fs:0, %rax
2097 0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00 // lea x@tpoff(%rax),
2098 // %rax
2099 };
2100 NewCodeSequence = ArrayRef<uint8_t>(SmallSequence);
2101 TpoffRelocOffset = 12;
2102 } else {
2103 static const std::initializer_list<uint8_t> CodeSequence = {
2104 0x48, 0x8d, 0x3d, 0x00, 0x00, 0x00, 0x00, // lea <disp32>(%rip),
2105 // %rdi
2106 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2107 0x00, // movabs $__tls_get_addr@pltoff, %rax
2108 0x48, 0x01, 0xd8, // add %rbx, %rax
2109 0xff, 0xd0 // call *%rax
2110 };
2111 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2112 TLSSequenceOffset = 3;
2113
2114 // The replacement code for the large code model
2115 static const std::initializer_list<uint8_t> LargeSequence = {
2116 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00,
2117 0x00, // mov %fs:0, %rax
2118 0x48, 0x8d, 0x80, 0x00, 0x00, 0x00, 0x00, // lea x@tpoff(%rax),
2119 // %rax
2120 0x66, 0x0f, 0x1f, 0x44, 0x00, 0x00 // nopw 0x0(%rax,%rax,1)
2121 };
2122 NewCodeSequence = ArrayRef<uint8_t>(LargeSequence);
2123 TpoffRelocOffset = 12;
2124 }
2125
2126 // The TLSGD/TLSLD relocations are PC-relative, so they have an addend.
2127 // The new TPOFF32 relocations is used as an absolute offset from
2128 // %fs:0, so remove the TLSGD/TLSLD addend again.
2129 RelocationEntry RE(SectionID, Offset - TLSSequenceOffset + TpoffRelocOffset,
2130 ELF::R_X86_64_TPOFF32, Value.Addend - Addend);
2131 if (Value.SymbolName)
2132 addRelocationForSymbol(RE, Value.SymbolName);
2133 else
2134 addRelocationForSection(RE, Value.SectionID);
2135 } else if (RelType == ELF::R_X86_64_TLSLD) {
2136 if (IsSmallCodeModel) {
2137 if (!IsGOTPCRel) {
2138 static const std::initializer_list<uint8_t> CodeSequence = {
2139 0x48, 0x8d, 0x3d, 0x00, 0x00, 0x00, // leaq <disp32>(%rip), %rdi
2140 0x00, 0xe8, 0x00, 0x00, 0x00, 0x00 // call __tls_get_addr@plt
2141 };
2142 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2143 TLSSequenceOffset = 3;
2144
2145 // The replacement code for the small code model
2146 static const std::initializer_list<uint8_t> SmallSequence = {
2147 0x66, 0x66, 0x66, // three data16 prefixes (no-op)
2148 0x64, 0x48, 0x8b, 0x04, 0x25,
2149 0x00, 0x00, 0x00, 0x00 // mov %fs:0, %rax
2150 };
2151 NewCodeSequence = ArrayRef<uint8_t>(SmallSequence);
2152 } else {
2153 // This code sequence is not described in the TLS spec but gcc
2154 // generates it sometimes.
2155 static const std::initializer_list<uint8_t> CodeSequence = {
2156 0x48, 0x8d, 0x3d, 0x00,
2157 0x00, 0x00, 0x00, // leaq <disp32>(%rip), %rdi
2158 0xff, 0x15, 0x00, 0x00,
2159 0x00, 0x00 // call
2160 // *__tls_get_addr@gotpcrel(%rip)
2161 };
2162 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2163 TLSSequenceOffset = 3;
2164
2165 // The replacement is code is just like above but it needs to be
2166 // one byte longer.
2167 static const std::initializer_list<uint8_t> SmallSequence = {
2168 0x0f, 0x1f, 0x40, 0x00, // 4 byte nop
2169 0x64, 0x48, 0x8b, 0x04, 0x25,
2170 0x00, 0x00, 0x00, 0x00 // mov %fs:0, %rax
2171 };
2172 NewCodeSequence = ArrayRef<uint8_t>(SmallSequence);
2173 }
2174 } else {
2175 // This is the same sequence as for the TLSGD sequence with the large
2176 // memory model above
2177 static const std::initializer_list<uint8_t> CodeSequence = {
2178 0x48, 0x8d, 0x3d, 0x00, 0x00, 0x00, 0x00, // lea <disp32>(%rip),
2179 // %rdi
2180 0x48, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2181 0x48, // movabs $__tls_get_addr@pltoff, %rax
2182 0x01, 0xd8, // add %rbx, %rax
2183 0xff, 0xd0 // call *%rax
2184 };
2185 ExpectedCodeSequence = ArrayRef<uint8_t>(CodeSequence);
2186 TLSSequenceOffset = 3;
2187
2188 // The replacement code for the large code model
2189 static const std::initializer_list<uint8_t> LargeSequence = {
2190 0x66, 0x66, 0x66, // three data16 prefixes (no-op)
2191 0x66, 0x66, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00,
2192 0x00, // 10 byte nop
2193 0x64, 0x48, 0x8b, 0x04, 0x25, 0x00, 0x00, 0x00, 0x00 // mov %fs:0,%rax
2194 };
2195 NewCodeSequence = ArrayRef<uint8_t>(LargeSequence);
2196 }
2197 } else {
2198 llvm_unreachable("both TLS relocations handled above");
2199 }
2200
2201 assert(ExpectedCodeSequence.size() == NewCodeSequence.size() &&
2202 "Old and new code sequences must have the same size");
2203
2204 auto &Section = Sections[SectionID];
2205 if (Offset < TLSSequenceOffset ||
2206 (Offset - TLSSequenceOffset + NewCodeSequence.size()) >
2207 Section.getSize()) {
2208 report_fatal_error("unexpected end of section in TLS sequence");
2209 }
2210
2211 auto *TLSSequence = Section.getAddressWithOffset(Offset - TLSSequenceOffset);
2212 if (ArrayRef<uint8_t>(TLSSequence, ExpectedCodeSequence.size()) !=
2213 ExpectedCodeSequence) {
2215 "invalid TLS sequence for Global/Local Dynamic TLS Model");
2216 }
2217
2218 memcpy(TLSSequence, NewCodeSequence.data(), NewCodeSequence.size());
2219}
2220
2222 // We don't use the GOT in all of these cases, but it's essentially free
2223 // to put them all here.
2224 size_t Result = 0;
2225 switch (Arch) {
2226 case Triple::x86_64:
2227 case Triple::aarch64:
2228 case Triple::aarch64_be:
2229 case Triple::ppc64:
2230 case Triple::ppc64le:
2231 case Triple::systemz:
2232 Result = sizeof(uint64_t);
2233 break;
2234 case Triple::x86:
2235 case Triple::arm:
2236 case Triple::thumb:
2237 Result = sizeof(uint32_t);
2238 break;
2239 case Triple::mips:
2240 case Triple::mipsel:
2241 case Triple::mips64:
2242 case Triple::mips64el:
2244 Result = sizeof(uint32_t);
2245 else if (IsMipsN64ABI)
2246 Result = sizeof(uint64_t);
2247 else
2248 llvm_unreachable("Mips ABI not handled");
2249 break;
2250 default:
2251 llvm_unreachable("Unsupported CPU type!");
2252 }
2253 return Result;
2254}
2255
2256uint64_t RuntimeDyldELF::allocateGOTEntries(unsigned no) {
2257 if (GOTSectionID == 0) {
2258 GOTSectionID = Sections.size();
2259 // Reserve a section id. We'll allocate the section later
2260 // once we know the total size
2261 Sections.push_back(SectionEntry(".got", nullptr, 0, 0, 0));
2262 }
2263 uint64_t StartOffset = CurrentGOTIndex * getGOTEntrySize();
2264 CurrentGOTIndex += no;
2265 return StartOffset;
2266}
2267
2268uint64_t RuntimeDyldELF::findOrAllocGOTEntry(const RelocationValueRef &Value,
2269 unsigned GOTRelType) {
2270 auto E = GOTOffsetMap.insert({Value, 0});
2271 if (E.second) {
2272 uint64_t GOTOffset = allocateGOTEntries(1);
2273
2274 // Create relocation for newly created GOT entry
2275 RelocationEntry RE =
2276 computeGOTOffsetRE(GOTOffset, Value.Offset, GOTRelType);
2277 if (Value.SymbolName)
2278 addRelocationForSymbol(RE, Value.SymbolName);
2279 else
2280 addRelocationForSection(RE, Value.SectionID);
2281
2282 E.first->second = GOTOffset;
2283 }
2284
2285 return E.first->second;
2286}
2287
2288void RuntimeDyldELF::resolveGOTOffsetRelocation(unsigned SectionID,
2290 uint64_t GOTOffset,
2291 uint32_t Type) {
2292 // Fill in the relative address of the GOT Entry into the stub
2293 RelocationEntry GOTRE(SectionID, Offset, Type, GOTOffset);
2294 addRelocationForSection(GOTRE, GOTSectionID);
2295}
2296
2297RelocationEntry RuntimeDyldELF::computeGOTOffsetRE(uint64_t GOTOffset,
2298 uint64_t SymbolOffset,
2299 uint32_t Type) {
2300 return RelocationEntry(GOTSectionID, GOTOffset, Type, SymbolOffset);
2301}
2302
2303void RuntimeDyldELF::processNewSymbol(const SymbolRef &ObjSymbol, SymbolTableEntry& Symbol) {
2304 // This should never return an error as `processNewSymbol` wouldn't have been
2305 // called if getFlags() returned an error before.
2306 auto ObjSymbolFlags = cantFail(ObjSymbol.getFlags());
2307
2308 if (ObjSymbolFlags & SymbolRef::SF_Indirect) {
2309 if (IFuncStubSectionID == 0) {
2310 // Create a dummy section for the ifunc stubs. It will be actually
2311 // allocated in finalizeLoad() below.
2312 IFuncStubSectionID = Sections.size();
2313 Sections.push_back(
2314 SectionEntry(".text.__llvm_IFuncStubs", nullptr, 0, 0, 0));
2315 // First 64B are reserverd for the IFunc resolver
2316 IFuncStubOffset = 64;
2317 }
2318
2319 IFuncStubs.push_back(IFuncStub{IFuncStubOffset, Symbol});
2320 // Modify the symbol so that it points to the ifunc stub instead of to the
2321 // resolver function.
2322 Symbol = SymbolTableEntry(IFuncStubSectionID, IFuncStubOffset,
2323 Symbol.getFlags());
2324 IFuncStubOffset += getMaxIFuncStubSize();
2325 }
2326}
2327
2329 ObjSectionToIDMap &SectionMap) {
2330 if (IsMipsO32ABI)
2331 if (!PendingRelocs.empty())
2332 return make_error<RuntimeDyldError>("Can't find matching LO16 reloc");
2333
2334 // Create the IFunc stubs if necessary. This must be done before processing
2335 // the GOT entries, as the IFunc stubs may create some.
2336 if (IFuncStubSectionID != 0) {
2337 uint8_t *IFuncStubsAddr = MemMgr.allocateCodeSection(
2338 IFuncStubOffset, 1, IFuncStubSectionID, ".text.__llvm_IFuncStubs");
2339 if (!IFuncStubsAddr)
2340 return make_error<RuntimeDyldError>(
2341 "Unable to allocate memory for IFunc stubs!");
2342 Sections[IFuncStubSectionID] =
2343 SectionEntry(".text.__llvm_IFuncStubs", IFuncStubsAddr, IFuncStubOffset,
2344 IFuncStubOffset, 0);
2345
2346 createIFuncResolver(IFuncStubsAddr);
2347
2348 LLVM_DEBUG(dbgs() << "Creating IFunc stubs SectionID: "
2349 << IFuncStubSectionID << " Addr: "
2350 << Sections[IFuncStubSectionID].getAddress() << '\n');
2351 for (auto &IFuncStub : IFuncStubs) {
2352 auto &Symbol = IFuncStub.OriginalSymbol;
2353 LLVM_DEBUG(dbgs() << "\tSectionID: " << Symbol.getSectionID()
2354 << " Offset: " << format("%p", Symbol.getOffset())
2355 << " IFuncStubOffset: "
2356 << format("%p\n", IFuncStub.StubOffset));
2357 createIFuncStub(IFuncStubSectionID, 0, IFuncStub.StubOffset,
2358 Symbol.getSectionID(), Symbol.getOffset());
2359 }
2360
2361 IFuncStubSectionID = 0;
2362 IFuncStubOffset = 0;
2363 IFuncStubs.clear();
2364 }
2365
2366 // If necessary, allocate the global offset table
2367 if (GOTSectionID != 0) {
2368 // Allocate memory for the section
2369 size_t TotalSize = CurrentGOTIndex * getGOTEntrySize();
2370 uint8_t *Addr = MemMgr.allocateDataSection(TotalSize, getGOTEntrySize(),
2371 GOTSectionID, ".got", false);
2372 if (!Addr)
2373 return make_error<RuntimeDyldError>("Unable to allocate memory for GOT!");
2374
2375 Sections[GOTSectionID] =
2376 SectionEntry(".got", Addr, TotalSize, TotalSize, 0);
2377
2378 // For now, initialize all GOT entries to zero. We'll fill them in as
2379 // needed when GOT-based relocations are applied.
2380 memset(Addr, 0, TotalSize);
2381 if (IsMipsN32ABI || IsMipsN64ABI) {
2382 // To correctly resolve Mips GOT relocations, we need a mapping from
2383 // object's sections to GOTs.
2384 for (section_iterator SI = Obj.section_begin(), SE = Obj.section_end();
2385 SI != SE; ++SI) {
2386 if (SI->relocation_begin() != SI->relocation_end()) {
2387 Expected<section_iterator> RelSecOrErr = SI->getRelocatedSection();
2388 if (!RelSecOrErr)
2389 return make_error<RuntimeDyldError>(
2390 toString(RelSecOrErr.takeError()));
2391
2392 section_iterator RelocatedSection = *RelSecOrErr;
2393 ObjSectionToIDMap::iterator i = SectionMap.find(*RelocatedSection);
2394 assert(i != SectionMap.end());
2395 SectionToGOTMap[i->second] = GOTSectionID;
2396 }
2397 }
2398 GOTSymbolOffsets.clear();
2399 }
2400 }
2401
2402 // Look for and record the EH frame section.
2403 ObjSectionToIDMap::iterator i, e;
2404 for (i = SectionMap.begin(), e = SectionMap.end(); i != e; ++i) {
2405 const SectionRef &Section = i->first;
2406
2408 Expected<StringRef> NameOrErr = Section.getName();
2409 if (NameOrErr)
2410 Name = *NameOrErr;
2411 else
2412 consumeError(NameOrErr.takeError());
2413
2414 if (Name == ".eh_frame") {
2415 UnregisteredEHFrameSections.push_back(i->second);
2416 break;
2417 }
2418 }
2419
2420 GOTOffsetMap.clear();
2421 GOTSectionID = 0;
2422 CurrentGOTIndex = 0;
2423
2424 return Error::success();
2425}
2426
2428 return Obj.isELF();
2429}
2430
2431void RuntimeDyldELF::createIFuncResolver(uint8_t *Addr) const {
2432 if (Arch == Triple::x86_64) {
2433 // The adddres of the GOT1 entry is in %r11, the GOT2 entry is in %r11+8
2434 // (see createIFuncStub() for details)
2435 // The following code first saves all registers that contain the original
2436 // function arguments as those registers are not saved by the resolver
2437 // function. %r11 is saved as well so that the GOT2 entry can be updated
2438 // afterwards. Then it calls the actual IFunc resolver function whose
2439 // address is stored in GOT2. After the resolver function returns, all
2440 // saved registers are restored and the return value is written to GOT1.
2441 // Finally, jump to the now resolved function.
2442 // clang-format off
2443 const uint8_t StubCode[] = {
2444 0x57, // push %rdi
2445 0x56, // push %rsi
2446 0x52, // push %rdx
2447 0x51, // push %rcx
2448 0x41, 0x50, // push %r8
2449 0x41, 0x51, // push %r9
2450 0x41, 0x53, // push %r11
2451 0x41, 0xff, 0x53, 0x08, // call *0x8(%r11)
2452 0x41, 0x5b, // pop %r11
2453 0x41, 0x59, // pop %r9
2454 0x41, 0x58, // pop %r8
2455 0x59, // pop %rcx
2456 0x5a, // pop %rdx
2457 0x5e, // pop %rsi
2458 0x5f, // pop %rdi
2459 0x49, 0x89, 0x03, // mov %rax,(%r11)
2460 0xff, 0xe0 // jmp *%rax
2461 };
2462 // clang-format on
2463 static_assert(sizeof(StubCode) <= 64,
2464 "maximum size of the IFunc resolver is 64B");
2465 memcpy(Addr, StubCode, sizeof(StubCode));
2466 } else {
2468 "IFunc resolver is not supported for target architecture");
2469 }
2470}
2471
2472void RuntimeDyldELF::createIFuncStub(unsigned IFuncStubSectionID,
2473 uint64_t IFuncResolverOffset,
2474 uint64_t IFuncStubOffset,
2475 unsigned IFuncSectionID,
2476 uint64_t IFuncOffset) {
2477 auto &IFuncStubSection = Sections[IFuncStubSectionID];
2478 auto *Addr = IFuncStubSection.getAddressWithOffset(IFuncStubOffset);
2479
2480 if (Arch == Triple::x86_64) {
2481 // The first instruction loads a PC-relative address into %r11 which is a
2482 // GOT entry for this stub. This initially contains the address to the
2483 // IFunc resolver. We can use %r11 here as it's caller saved but not used
2484 // to pass any arguments. In fact, x86_64 ABI even suggests using %r11 for
2485 // code in the PLT. The IFunc resolver will use %r11 to update the GOT
2486 // entry.
2487 //
2488 // The next instruction just jumps to the address contained in the GOT
2489 // entry. As mentioned above, we do this two-step jump by first setting
2490 // %r11 so that the IFunc resolver has access to it.
2491 //
2492 // The IFunc resolver of course also needs to know the actual address of
2493 // the actual IFunc resolver function. This will be stored in a GOT entry
2494 // right next to the first one for this stub. So, the IFunc resolver will
2495 // be able to call it with %r11+8.
2496 //
2497 // In total, two adjacent GOT entries (+relocation) and one additional
2498 // relocation are required:
2499 // GOT1: Address of the IFunc resolver.
2500 // GOT2: Address of the IFunc resolver function.
2501 // IFuncStubOffset+3: 32-bit PC-relative address of GOT1.
2502 uint64_t GOT1 = allocateGOTEntries(2);
2503 uint64_t GOT2 = GOT1 + getGOTEntrySize();
2504
2505 RelocationEntry RE1(GOTSectionID, GOT1, ELF::R_X86_64_64,
2506 IFuncResolverOffset, {});
2507 addRelocationForSection(RE1, IFuncStubSectionID);
2508 RelocationEntry RE2(GOTSectionID, GOT2, ELF::R_X86_64_64, IFuncOffset, {});
2509 addRelocationForSection(RE2, IFuncSectionID);
2510
2511 const uint8_t StubCode[] = {
2512 0x4c, 0x8d, 0x1d, 0x00, 0x00, 0x00, 0x00, // leaq 0x0(%rip),%r11
2513 0x41, 0xff, 0x23 // jmpq *(%r11)
2514 };
2515 assert(sizeof(StubCode) <= getMaxIFuncStubSize() &&
2516 "IFunc stub size must not exceed getMaxIFuncStubSize()");
2517 memcpy(Addr, StubCode, sizeof(StubCode));
2518
2519 // The PC-relative value starts 4 bytes from the end of the leaq
2520 // instruction, so the addend is -4.
2521 resolveGOTOffsetRelocation(IFuncStubSectionID, IFuncStubOffset + 3,
2522 GOT1 - 4, ELF::R_X86_64_PC32);
2523 } else {
2524 report_fatal_error("IFunc stub is not supported for target architecture");
2525 }
2526}
2527
2528unsigned RuntimeDyldELF::getMaxIFuncStubSize() const {
2529 if (Arch == Triple::x86_64) {
2530 return 10;
2531 }
2532 return 0;
2533}
2534
2535bool RuntimeDyldELF::relocationNeedsGot(const RelocationRef &R) const {
2536 unsigned RelTy = R.getType();
2538 return RelTy == ELF::R_AARCH64_ADR_GOT_PAGE ||
2539 RelTy == ELF::R_AARCH64_LD64_GOT_LO12_NC;
2540
2541 if (Arch == Triple::x86_64)
2542 return RelTy == ELF::R_X86_64_GOTPCREL ||
2543 RelTy == ELF::R_X86_64_GOTPCRELX ||
2544 RelTy == ELF::R_X86_64_GOT64 ||
2545 RelTy == ELF::R_X86_64_REX_GOTPCRELX;
2546 return false;
2547}
2548
2549bool RuntimeDyldELF::relocationNeedsStub(const RelocationRef &R) const {
2550 if (Arch != Triple::x86_64)
2551 return true; // Conservative answer
2552
2553 switch (R.getType()) {
2554 default:
2555 return true; // Conservative answer
2556
2557
2558 case ELF::R_X86_64_GOTPCREL:
2559 case ELF::R_X86_64_GOTPCRELX:
2560 case ELF::R_X86_64_REX_GOTPCRELX:
2561 case ELF::R_X86_64_GOTPC64:
2562 case ELF::R_X86_64_GOT64:
2563 case ELF::R_X86_64_GOTOFF64:
2564 case ELF::R_X86_64_PC32:
2565 case ELF::R_X86_64_PC64:
2566 case ELF::R_X86_64_64:
2567 // We know that these reloation types won't need a stub function. This list
2568 // can be extended as needed.
2569 return false;
2570 }
2571}
2572
2573} // namespace llvm
amdgpu aa AMDGPU Address space based Alias Analysis Wrapper
Given that RA is a live value
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Addr
std::string Name
#define LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
Definition: ELFTypes.h:104
bool End
Definition: ELF_riscv.cpp:480
#define I(x, y, z)
Definition: MD5.cpp:58
#define P(N)
static void or32le(void *P, int32_t V)
static void or32AArch64Imm(void *L, uint64_t Imm)
static void write(bool isBE, void *P, T V)
static uint64_t getBits(uint64_t Val, int Start, int End)
static void write32AArch64Addr(void *L, uint64_t Imm)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
raw_pwrite_stream & OS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:165
const T * data() const
Definition: ArrayRef.h:162
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
Symbol resolution interface.
Definition: JITSymbol.h:371
static std::unique_ptr< MemoryBuffer > getMemBufferCopy(StringRef InputData, const Twine &BufferName="")
Open the specified memory range as a MemoryBuffer, copying the contents and taking ownership of it.
RelocationEntry - used to represent relocations internally in the dynamic linker.
uint32_t RelType
RelType - relocation type.
uint64_t Offset
Offset - offset into the section.
int64_t Addend
Addend - the relocation addend encoded in the instruction itself.
unsigned SectionID
SectionID - the section this relocation points to.
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:2213
void registerEHFrames() override
size_t getGOTEntrySize() override
~RuntimeDyldELF() override
static std::unique_ptr< RuntimeDyldELF > create(Triple::ArchType Arch, RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver)
Error finalizeLoad(const ObjectFile &Obj, ObjSectionToIDMap &SectionMap) override
DenseMap< SID, SID > SectionToGOTMap
bool isCompatibleFile(const object::ObjectFile &Obj) const override
std::unique_ptr< RuntimeDyld::LoadedObjectInfo > loadObject(const object::ObjectFile &O) override
RuntimeDyldELF(RuntimeDyld::MemoryManager &MemMgr, JITSymbolResolver &Resolver)
Expected< relocation_iterator > processRelocationRef(unsigned SectionID, relocation_iterator RelI, const ObjectFile &Obj, ObjSectionToIDMap &ObjSectionToID, StubMap &Stubs) override
Parses one or more object file relocations (some object files use relocation pairs) and stores it to ...
std::map< SectionRef, unsigned > ObjSectionToIDMap
void writeInt32BE(uint8_t *Addr, uint32_t Value)
void writeInt64BE(uint8_t *Addr, uint64_t Value)
std::map< RelocationValueRef, uintptr_t > StubMap
void writeInt16BE(uint8_t *Addr, uint16_t Value)
void addRelocationForSymbol(const RelocationEntry &RE, StringRef SymbolName)
RuntimeDyld::MemoryManager & MemMgr
void addRelocationForSection(const RelocationEntry &RE, unsigned SectionID)
Expected< unsigned > findOrEmitSection(const ObjectFile &Obj, const SectionRef &Section, bool IsCode, ObjSectionToIDMap &LocalSections)
Find Section in LocalSections.
Triple::ArchType Arch
uint8_t * createStubFunction(uint8_t *Addr, unsigned AbiVariant=0)
Emits long jump instruction to Addr.
uint64_t readBytesUnaligned(uint8_t *Src, unsigned Size) const
Endian-aware read Read the least significant Size bytes from Src.
RTDyldSymbolTable GlobalSymbolTable
Expected< ObjSectionToIDMap > loadObjectImpl(const object::ObjectFile &Obj)
virtual uint8_t * allocateDataSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName, bool IsReadOnly)=0
Allocate a memory block of (at least) the given size suitable for data.
virtual uint8_t * allocateCodeSection(uintptr_t Size, unsigned Alignment, unsigned SectionID, StringRef SectionName)=0
Allocate a memory block of (at least) the given size suitable for executable code.
virtual void registerEHFrames(uint8_t *Addr, uint64_t LoadAddr, size_t Size)=0
Register the EH frames with the runtime so that c++ exceptions work.
virtual bool allowStubAllocation() const
Override to return false to tell LLVM no stub space will be needed.
Definition: RuntimeDyld.h:148
SectionEntry - represents a section emitted into memory by the dynamic linker.
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
iterator end()
Definition: StringMap.h:220
iterator find(StringRef Key)
Definition: StringMap.h:233
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
Symbol info for RuntimeDyld.
Target - Wrapper for Target specific information.
@ UnknownArch
Definition: Triple.h:47
@ aarch64_be
Definition: Triple.h:52
@ mips64el
Definition: Triple.h:67
static StringRef getArchTypePrefix(ArchType Kind)
Get the "prefix" canonical name for the Kind architecture.
Definition: Triple.cpp:149
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
Expected< uint32_t > getFlags() const
Get symbol flags (bitwise OR of SymbolRef::Flags)
Definition: SymbolicFile.h:206
DataRefImpl getRawDataRefImpl() const
Definition: SymbolicFile.h:210
StringRef getData() const
Definition: Binary.cpp:39
bool isLittleEndian() const
Definition: Binary.h:155
StringRef getFileName() const
Definition: Binary.cpp:41
bool isELF() const
Definition: Binary.h:123
virtual unsigned getPlatformFlags() const =0
Returns platform-specific object flags, if any.
static bool classof(const Binary *v)
Expected< const Elf_Sym * > getSymbol(DataRefImpl Sym) const
static Expected< ELFObjectFile< ELFT > > create(MemoryBufferRef Object, bool InitContent=true)
Expected< int64_t > getAddend() const
This class is the base class for all object file types.
Definition: ObjectFile.h:229
virtual section_iterator section_end() const =0
virtual uint8_t getBytesInAddress() const =0
The number of bytes used to represent an address in this object file format.
section_iterator_range sections() const
Definition: ObjectFile.h:329
virtual StringRef getFileFormatName() const =0
virtual section_iterator section_begin() const =0
This is a value type class that represents a single relocation in the list of relocations in the obje...
Definition: ObjectFile.h:52
uint64_t getType() const
Definition: ObjectFile.h:628
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81
DataRefImpl getRawDataRefImpl() const
Definition: ObjectFile.h:598
bool isText() const
Whether this section contains instructions.
Definition: ObjectFile.h:550
Expected< StringRef > getName() const
Definition: ObjectFile.h:517
This is a value type class that represents a single symbol in the list of symbols in the object file.
Definition: ObjectFile.h:168
Expected< section_iterator > getSection() const
Get section this symbol is defined in reference to.
Definition: ObjectFile.h:480
virtual basic_symbol_iterator symbol_end() const =0
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
static int64_t decodePPC64LocalEntryOffset(unsigned Other)
Definition: ELF.h:414
@ EF_PPC64_ABI
Definition: ELF.h:406
@ EF_MIPS_ABI_O32
Definition: ELF.h:522
@ EF_MIPS_ABI2
Definition: ELF.h:514
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
@ Resolved
Queried, materialization begun.
void write32le(void *P, uint32_t V)
Definition: Endian.h:468
uint32_t read32le(const void *P)
Definition: Endian.h:425
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition: Error.cpp:65
static uint16_t applyPPChighera(uint64_t value)
static uint16_t applyPPChi(uint64_t value)
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:977
static uint16_t applyPPChighesta(uint64_t value)
static uint16_t applyPPChighest(uint64_t value)
Error write(MCStreamer &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue)
Definition: DWP.cpp:625
static uint16_t applyPPCha(uint64_t value)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition: Casting.h:548
static uint16_t applyPPClo(uint64_t value)
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:756
static uint16_t applyPPChigher(uint64_t value)
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
static void or32le(void *P, int32_t V)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1849
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition: Casting.h:565
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition: MathExtras.h:509
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1069
static void write32AArch64Addr(void *T, uint64_t s, uint64_t p, int shift)
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
SymInfo contains information about symbol: it's address and section index which is -1LL for absolute ...