[SLP][REVEC] The vectorized result for ShuffleVector may not be ShuffleVectorInst...
[llvm-project.git] / lld / ELF / InputSection.cpp
blob1221f56dfe68a698128c70d5f128e09040f18bcb
1 //===- InputSection.cpp ---------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
9 #include "InputSection.h"
10 #include "Config.h"
11 #include "InputFiles.h"
12 #include "OutputSections.h"
13 #include "Relocations.h"
14 #include "SymbolTable.h"
15 #include "Symbols.h"
16 #include "SyntheticSections.h"
17 #include "Target.h"
18 #include "lld/Common/CommonLinkerContext.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Compression.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/xxhash.h"
23 #include <algorithm>
24 #include <mutex>
25 #include <optional>
26 #include <vector>
28 using namespace llvm;
29 using namespace llvm::ELF;
30 using namespace llvm::object;
31 using namespace llvm::support;
32 using namespace llvm::support::endian;
33 using namespace llvm::sys;
34 using namespace lld;
35 using namespace lld::elf;
37 // Returns a string to construct an error message.
38 std::string elf::toStr(Ctx &ctx, const InputSectionBase *sec) {
39 return (toStr(ctx, sec->file) + ":(" + sec->name + ")").str();
42 const ELFSyncStream &elf::operator<<(const ELFSyncStream &s,
43 const InputSectionBase *sec) {
44 return s << toStr(s.ctx, sec);
47 template <class ELFT>
48 static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &file,
49 const typename ELFT::Shdr &hdr) {
50 if (hdr.sh_type == SHT_NOBITS)
51 return ArrayRef<uint8_t>(nullptr, hdr.sh_size);
52 return check(file.getObj().getSectionContents(hdr));
55 InputSectionBase::InputSectionBase(InputFile *file, uint64_t flags,
56 uint32_t type, uint64_t entsize,
57 uint32_t link, uint32_t info,
58 uint32_t addralign, ArrayRef<uint8_t> data,
59 StringRef name, Kind sectionKind)
60 : SectionBase(sectionKind, file, name, flags, entsize, addralign, type,
61 info, link),
62 content_(data.data()), size(data.size()) {
63 // In order to reduce memory allocation, we assume that mergeable
64 // sections are smaller than 4 GiB, which is not an unreasonable
65 // assumption as of 2017.
66 if (sectionKind == SectionBase::Merge && content().size() > UINT32_MAX)
67 ErrAlways(getCtx()) << this << ": section too large";
69 // The ELF spec states that a value of 0 means the section has
70 // no alignment constraints.
71 uint32_t v = std::max<uint32_t>(addralign, 1);
72 if (!isPowerOf2_64(v))
73 Fatal(getCtx()) << this << ": sh_addralign is not a power of 2";
74 this->addralign = v;
76 // If SHF_COMPRESSED is set, parse the header. The legacy .zdebug format is no
77 // longer supported.
78 if (flags & SHF_COMPRESSED) {
79 Ctx &ctx = file->ctx;
80 invokeELFT(parseCompressedHeader, ctx);
84 // SHF_INFO_LINK and SHF_GROUP are normally resolved and not copied to the
85 // output section. However, for relocatable linking without
86 // --force-group-allocation, the SHF_GROUP flag and section groups are retained.
87 static uint64_t getFlags(Ctx &ctx, uint64_t flags) {
88 flags &= ~(uint64_t)SHF_INFO_LINK;
89 if (ctx.arg.resolveGroups)
90 flags &= ~(uint64_t)SHF_GROUP;
91 return flags;
94 template <class ELFT>
95 InputSectionBase::InputSectionBase(ObjFile<ELFT> &file,
96 const typename ELFT::Shdr &hdr,
97 StringRef name, Kind sectionKind)
98 : InputSectionBase(&file, getFlags(file.ctx, hdr.sh_flags), hdr.sh_type,
99 hdr.sh_entsize, hdr.sh_link, hdr.sh_info,
100 hdr.sh_addralign, getSectionContents(file, hdr), name,
101 sectionKind) {
102 // We reject object files having insanely large alignments even though
103 // they are allowed by the spec. I think 4GB is a reasonable limitation.
104 // We might want to relax this in the future.
105 if (hdr.sh_addralign > UINT32_MAX)
106 Fatal(getCtx()) << &file << ": section sh_addralign is too large";
109 size_t InputSectionBase::getSize() const {
110 if (auto *s = dyn_cast<SyntheticSection>(this))
111 return s->getSize();
112 return size - bytesDropped;
115 template <class ELFT>
116 static void decompressAux(Ctx &ctx, const InputSectionBase &sec, uint8_t *out,
117 size_t size) {
118 auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(sec.content_);
119 auto compressed = ArrayRef<uint8_t>(sec.content_, sec.compressedSize)
120 .slice(sizeof(typename ELFT::Chdr));
121 if (Error e = hdr->ch_type == ELFCOMPRESS_ZLIB
122 ? compression::zlib::decompress(compressed, out, size)
123 : compression::zstd::decompress(compressed, out, size))
124 Fatal(ctx) << &sec << ": decompress failed: " << std::move(e);
127 void InputSectionBase::decompress() const {
128 Ctx &ctx = getCtx();
129 uint8_t *uncompressedBuf;
131 static std::mutex mu;
132 std::lock_guard<std::mutex> lock(mu);
133 uncompressedBuf = ctx.bAlloc.Allocate<uint8_t>(size);
136 invokeELFT(decompressAux, ctx, *this, uncompressedBuf, size);
137 content_ = uncompressedBuf;
138 compressed = false;
141 template <class ELFT>
142 RelsOrRelas<ELFT> InputSectionBase::relsOrRelas(bool supportsCrel) const {
143 if (relSecIdx == 0)
144 return {};
145 RelsOrRelas<ELFT> ret;
146 auto *f = cast<ObjFile<ELFT>>(file);
147 typename ELFT::Shdr shdr = f->template getELFShdrs<ELFT>()[relSecIdx];
148 if (shdr.sh_type == SHT_CREL) {
149 // Return an iterator if supported by caller.
150 if (supportsCrel) {
151 ret.crels = Relocs<typename ELFT::Crel>(
152 (const uint8_t *)f->mb.getBufferStart() + shdr.sh_offset);
153 return ret;
155 InputSectionBase *const &relSec = f->getSections()[relSecIdx];
156 // Otherwise, allocate a buffer to hold the decoded RELA relocations. When
157 // called for the first time, relSec is null (without --emit-relocs) or an
158 // InputSection with false decodedCrel.
159 if (!relSec || !cast<InputSection>(relSec)->decodedCrel) {
160 auto *sec = makeThreadLocal<InputSection>(*f, shdr, name);
161 f->cacheDecodedCrel(relSecIdx, sec);
162 sec->type = SHT_RELA;
163 sec->decodedCrel = true;
165 RelocsCrel<ELFT::Is64Bits> entries(sec->content_);
166 sec->size = entries.size() * sizeof(typename ELFT::Rela);
167 auto *relas = makeThreadLocalN<typename ELFT::Rela>(entries.size());
168 sec->content_ = reinterpret_cast<uint8_t *>(relas);
169 for (auto [i, r] : llvm::enumerate(entries)) {
170 relas[i].r_offset = r.r_offset;
171 relas[i].setSymbolAndType(r.r_symidx, r.r_type, false);
172 relas[i].r_addend = r.r_addend;
175 ret.relas = {ArrayRef(
176 reinterpret_cast<const typename ELFT::Rela *>(relSec->content_),
177 relSec->size / sizeof(typename ELFT::Rela))};
178 return ret;
181 const void *content = f->mb.getBufferStart() + shdr.sh_offset;
182 size_t size = shdr.sh_size;
183 if (shdr.sh_type == SHT_REL) {
184 ret.rels = {ArrayRef(reinterpret_cast<const typename ELFT::Rel *>(content),
185 size / sizeof(typename ELFT::Rel))};
186 } else {
187 assert(shdr.sh_type == SHT_RELA);
188 ret.relas = {
189 ArrayRef(reinterpret_cast<const typename ELFT::Rela *>(content),
190 size / sizeof(typename ELFT::Rela))};
192 return ret;
195 Ctx &SectionBase::getCtx() const { return file->ctx; }
197 uint64_t SectionBase::getOffset(uint64_t offset) const {
198 switch (kind()) {
199 case Output: {
200 auto *os = cast<OutputSection>(this);
201 // For output sections we treat offset -1 as the end of the section.
202 return offset == uint64_t(-1) ? os->size : offset;
204 case Class:
205 llvm_unreachable("section classes do not have offsets");
206 case Regular:
207 case Synthetic:
208 case Spill:
209 return cast<InputSection>(this)->outSecOff + offset;
210 case EHFrame: {
211 // Two code paths may reach here. First, clang_rt.crtbegin.o and GCC
212 // crtbeginT.o may reference the start of an empty .eh_frame to identify the
213 // start of the output .eh_frame. Just return offset.
215 // Second, InputSection::copyRelocations on .eh_frame. Some pieces may be
216 // discarded due to GC/ICF. We should compute the output section offset.
217 const EhInputSection *es = cast<EhInputSection>(this);
218 if (!es->content().empty())
219 if (InputSection *isec = es->getParent())
220 return isec->outSecOff + es->getParentOffset(offset);
221 return offset;
223 case Merge:
224 const MergeInputSection *ms = cast<MergeInputSection>(this);
225 if (InputSection *isec = ms->getParent())
226 return isec->outSecOff + ms->getParentOffset(offset);
227 return ms->getParentOffset(offset);
229 llvm_unreachable("invalid section kind");
232 uint64_t SectionBase::getVA(uint64_t offset) const {
233 const OutputSection *out = getOutputSection();
234 return (out ? out->addr : 0) + getOffset(offset);
237 OutputSection *SectionBase::getOutputSection() {
238 InputSection *sec;
239 if (auto *isec = dyn_cast<InputSection>(this))
240 sec = isec;
241 else if (auto *ms = dyn_cast<MergeInputSection>(this))
242 sec = ms->getParent();
243 else if (auto *eh = dyn_cast<EhInputSection>(this))
244 sec = eh->getParent();
245 else
246 return cast<OutputSection>(this);
247 return sec ? sec->getParent() : nullptr;
250 // When a section is compressed, `rawData` consists with a header followed
251 // by zlib-compressed data. This function parses a header to initialize
252 // `uncompressedSize` member and remove the header from `rawData`.
253 template <typename ELFT>
254 void InputSectionBase::parseCompressedHeader(Ctx &ctx) {
255 flags &= ~(uint64_t)SHF_COMPRESSED;
257 // New-style header
258 if (content().size() < sizeof(typename ELFT::Chdr)) {
259 ErrAlways(ctx) << this << ": corrupted compressed section";
260 return;
263 auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(content().data());
264 if (hdr->ch_type == ELFCOMPRESS_ZLIB) {
265 if (!compression::zlib::isAvailable())
266 ErrAlways(ctx) << this
267 << " is compressed with ELFCOMPRESS_ZLIB, but lld is "
268 "not built with zlib support";
269 } else if (hdr->ch_type == ELFCOMPRESS_ZSTD) {
270 if (!compression::zstd::isAvailable())
271 ErrAlways(ctx) << this
272 << " is compressed with ELFCOMPRESS_ZSTD, but lld is "
273 "not built with zstd support";
274 } else {
275 ErrAlways(ctx) << this << ": unsupported compression type ("
276 << Twine(hdr->ch_type) << ")";
277 return;
280 compressed = true;
281 compressedSize = size;
282 size = hdr->ch_size;
283 addralign = std::max<uint32_t>(hdr->ch_addralign, 1);
286 InputSection *InputSectionBase::getLinkOrderDep() const {
287 assert(flags & SHF_LINK_ORDER);
288 if (!link)
289 return nullptr;
290 return cast<InputSection>(file->getSections()[link]);
293 // Find a symbol that encloses a given location.
294 Defined *InputSectionBase::getEnclosingSymbol(uint64_t offset,
295 uint8_t type) const {
296 if (file->isInternal())
297 return nullptr;
298 for (Symbol *b : file->getSymbols())
299 if (Defined *d = dyn_cast<Defined>(b))
300 if (d->section == this && d->value <= offset &&
301 offset < d->value + d->size && (type == 0 || type == d->type))
302 return d;
303 return nullptr;
306 // Returns an object file location string. Used to construct an error message.
307 std::string InputSectionBase::getLocation(uint64_t offset) const {
308 std::string secAndOffset =
309 (name + "+0x" + Twine::utohexstr(offset) + ")").str();
311 std::string filename = toStr(getCtx(), file);
312 if (Defined *d = getEnclosingFunction(offset))
313 return filename + ":(function " + toStr(getCtx(), *d) + ": " + secAndOffset;
315 return filename + ":(" + secAndOffset;
318 // This function is intended to be used for constructing an error message.
319 // The returned message looks like this:
321 // foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
323 // Returns an empty string if there's no way to get line info.
324 std::string InputSectionBase::getSrcMsg(const Symbol &sym,
325 uint64_t offset) const {
326 return file->getSrcMsg(sym, *this, offset);
329 // Returns a filename string along with an optional section name. This
330 // function is intended to be used for constructing an error
331 // message. The returned message looks like this:
333 // path/to/foo.o:(function bar)
335 // or
337 // path/to/foo.o:(function bar) in archive path/to/bar.a
338 std::string InputSectionBase::getObjMsg(uint64_t off) const {
339 std::string filename = std::string(file->getName());
341 std::string archive;
342 if (!file->archiveName.empty())
343 archive = (" in archive " + file->archiveName).str();
345 // Find a symbol that encloses a given location. getObjMsg may be called
346 // before ObjFile::initSectionsAndLocalSyms where local symbols are
347 // initialized.
348 if (Defined *d = getEnclosingSymbol(off))
349 return filename + ":(" + toStr(getCtx(), *d) + ")" + archive;
351 // If there's no symbol, print out the offset in the section.
352 return (filename + ":(" + name + "+0x" + utohexstr(off) + ")" + archive)
353 .str();
356 PotentialSpillSection::PotentialSpillSection(const InputSectionBase &source,
357 InputSectionDescription &isd)
358 : InputSection(source.file, source.flags, source.type, source.addralign, {},
359 source.name, SectionBase::Spill),
360 isd(&isd) {}
362 InputSection InputSection::discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), "");
364 InputSection::InputSection(InputFile *f, uint64_t flags, uint32_t type,
365 uint32_t addralign, ArrayRef<uint8_t> data,
366 StringRef name, Kind k)
367 : InputSectionBase(f, flags, type,
368 /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, addralign, data,
369 name, k) {
370 assert(f || this == &InputSection::discarded);
373 template <class ELFT>
374 InputSection::InputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
375 StringRef name)
376 : InputSectionBase(f, header, name, InputSectionBase::Regular) {}
378 // Copy SHT_GROUP section contents. Used only for the -r option.
379 template <class ELFT> void InputSection::copyShtGroup(uint8_t *buf) {
380 // ELFT::Word is the 32-bit integral type in the target endianness.
381 using u32 = typename ELFT::Word;
382 ArrayRef<u32> from = getDataAs<u32>();
383 auto *to = reinterpret_cast<u32 *>(buf);
385 // The first entry is not a section number but a flag.
386 *to++ = from[0];
388 // Adjust section numbers because section numbers in an input object files are
389 // different in the output. We also need to handle combined or discarded
390 // members.
391 ArrayRef<InputSectionBase *> sections = file->getSections();
392 DenseSet<uint32_t> seen;
393 for (uint32_t idx : from.slice(1)) {
394 OutputSection *osec = sections[idx]->getOutputSection();
395 if (osec && seen.insert(osec->sectionIndex).second)
396 *to++ = osec->sectionIndex;
400 InputSectionBase *InputSection::getRelocatedSection() const {
401 if (file->isInternal() || !isStaticRelSecType(type))
402 return nullptr;
403 ArrayRef<InputSectionBase *> sections = file->getSections();
404 return sections[info];
407 template <class ELFT, class RelTy>
408 void InputSection::copyRelocations(Ctx &ctx, uint8_t *buf) {
409 if (ctx.arg.relax && !ctx.arg.relocatable &&
410 (ctx.arg.emachine == EM_RISCV || ctx.arg.emachine == EM_LOONGARCH)) {
411 // On LoongArch and RISC-V, relaxation might change relocations: copy
412 // from internal ones that are updated by relaxation.
413 InputSectionBase *sec = getRelocatedSection();
414 copyRelocations<ELFT, RelTy>(
415 ctx, buf,
416 llvm::make_range(sec->relocations.begin(), sec->relocations.end()));
417 } else {
418 // Convert the raw relocations in the input section into Relocation objects
419 // suitable to be used by copyRelocations below.
420 struct MapRel {
421 Ctx &ctx;
422 const ObjFile<ELFT> &file;
423 Relocation operator()(const RelTy &rel) const {
424 // RelExpr is not used so set to a dummy value.
425 return Relocation{R_NONE, rel.getType(ctx.arg.isMips64EL), rel.r_offset,
426 getAddend<ELFT>(rel), &file.getRelocTargetSym(rel)};
430 using RawRels = ArrayRef<RelTy>;
431 using MapRelIter =
432 llvm::mapped_iterator<typename RawRels::iterator, MapRel>;
433 auto mapRel = MapRel{ctx, *getFile<ELFT>()};
434 RawRels rawRels = getDataAs<RelTy>();
435 auto rels = llvm::make_range(MapRelIter(rawRels.begin(), mapRel),
436 MapRelIter(rawRels.end(), mapRel));
437 copyRelocations<ELFT, RelTy>(ctx, buf, rels);
441 // This is used for -r and --emit-relocs. We can't use memcpy to copy
442 // relocations because we need to update symbol table offset and section index
443 // for each relocation. So we copy relocations one by one.
444 template <class ELFT, class RelTy, class RelIt>
445 void InputSection::copyRelocations(Ctx &ctx, uint8_t *buf,
446 llvm::iterator_range<RelIt> rels) {
447 const TargetInfo &target = *ctx.target;
448 InputSectionBase *sec = getRelocatedSection();
449 (void)sec->contentMaybeDecompress(); // uncompress if needed
451 for (const Relocation &rel : rels) {
452 RelType type = rel.type;
453 const ObjFile<ELFT> *file = getFile<ELFT>();
454 Symbol &sym = *rel.sym;
456 auto *p = reinterpret_cast<typename ELFT::Rela *>(buf);
457 buf += sizeof(RelTy);
459 if (RelTy::HasAddend)
460 p->r_addend = rel.addend;
462 // Output section VA is zero for -r, so r_offset is an offset within the
463 // section, but for --emit-relocs it is a virtual address.
464 p->r_offset = sec->getVA(rel.offset);
465 p->setSymbolAndType(ctx.in.symTab->getSymbolIndex(sym), type,
466 ctx.arg.isMips64EL);
468 if (sym.type == STT_SECTION) {
469 // We combine multiple section symbols into only one per
470 // section. This means we have to update the addend. That is
471 // trivial for Elf_Rela, but for Elf_Rel we have to write to the
472 // section data. We do that by adding to the Relocation vector.
474 // .eh_frame is horribly special and can reference discarded sections. To
475 // avoid having to parse and recreate .eh_frame, we just replace any
476 // relocation in it pointing to discarded sections with R_*_NONE, which
477 // hopefully creates a frame that is ignored at runtime. Also, don't warn
478 // on .gcc_except_table and debug sections.
480 // See the comment in maybeReportUndefined for PPC32 .got2 and PPC64 .toc
481 auto *d = dyn_cast<Defined>(&sym);
482 if (!d) {
483 if (!isDebugSection(*sec) && sec->name != ".eh_frame" &&
484 sec->name != ".gcc_except_table" && sec->name != ".got2" &&
485 sec->name != ".toc") {
486 uint32_t secIdx = cast<Undefined>(sym).discardedSecIdx;
487 Elf_Shdr_Impl<ELFT> sec = file->template getELFShdrs<ELFT>()[secIdx];
488 Warn(ctx) << "relocation refers to a discarded section: "
489 << CHECK2(file->getObj().getSectionName(sec), file)
490 << "\n>>> referenced by " << getObjMsg(p->r_offset);
492 p->setSymbolAndType(0, 0, false);
493 continue;
495 SectionBase *section = d->section;
496 assert(section->isLive());
498 int64_t addend = rel.addend;
499 const uint8_t *bufLoc = sec->content().begin() + rel.offset;
500 if (!RelTy::HasAddend)
501 addend = target.getImplicitAddend(bufLoc, type);
503 if (ctx.arg.emachine == EM_MIPS &&
504 target.getRelExpr(type, sym, bufLoc) == R_MIPS_GOTREL) {
505 // Some MIPS relocations depend on "gp" value. By default,
506 // this value has 0x7ff0 offset from a .got section. But
507 // relocatable files produced by a compiler or a linker
508 // might redefine this default value and we must use it
509 // for a calculation of the relocation result. When we
510 // generate EXE or DSO it's trivial. Generating a relocatable
511 // output is more difficult case because the linker does
512 // not calculate relocations in this mode and loses
513 // individual "gp" values used by each input object file.
514 // As a workaround we add the "gp" value to the relocation
515 // addend and save it back to the file.
516 addend += sec->getFile<ELFT>()->mipsGp0;
519 if (RelTy::HasAddend)
520 p->r_addend =
521 sym.getVA(ctx, addend) - section->getOutputSection()->addr;
522 // For SHF_ALLOC sections relocated by REL, append a relocation to
523 // sec->relocations so that relocateAlloc transitively called by
524 // writeSections will update the implicit addend. Non-SHF_ALLOC sections
525 // utilize relocateNonAlloc to process raw relocations and do not need
526 // this sec->relocations change.
527 else if (ctx.arg.relocatable && (sec->flags & SHF_ALLOC) &&
528 type != target.noneRel)
529 sec->addReloc({R_ABS, type, rel.offset, addend, &sym});
530 } else if (ctx.arg.emachine == EM_PPC && type == R_PPC_PLTREL24 &&
531 p->r_addend >= 0x8000 && sec->file->ppc32Got2) {
532 // Similar to R_MIPS_GPREL{16,32}. If the addend of R_PPC_PLTREL24
533 // indicates that r30 is relative to the input section .got2
534 // (r_addend>=0x8000), after linking, r30 should be relative to the output
535 // section .got2 . To compensate for the shift, adjust r_addend by
536 // ppc32Got->outSecOff.
537 p->r_addend += sec->file->ppc32Got2->outSecOff;
542 // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
543 // references specially. The general rule is that the value of the symbol in
544 // this context is the address of the place P. A further special case is that
545 // branch relocations to an undefined weak reference resolve to the next
546 // instruction.
547 static uint32_t getARMUndefinedRelativeWeakVA(RelType type, uint32_t a,
548 uint32_t p) {
549 switch (type) {
550 // Unresolved branch relocations to weak references resolve to next
551 // instruction, this will be either 2 or 4 bytes on from P.
552 case R_ARM_THM_JUMP8:
553 case R_ARM_THM_JUMP11:
554 return p + 2 + a;
555 case R_ARM_CALL:
556 case R_ARM_JUMP24:
557 case R_ARM_PC24:
558 case R_ARM_PLT32:
559 case R_ARM_PREL31:
560 case R_ARM_THM_JUMP19:
561 case R_ARM_THM_JUMP24:
562 return p + 4 + a;
563 case R_ARM_THM_CALL:
564 // We don't want an interworking BLX to ARM
565 return p + 5 + a;
566 // Unresolved non branch pc-relative relocations
567 // R_ARM_TARGET2 which can be resolved relatively is not present as it never
568 // targets a weak-reference.
569 case R_ARM_MOVW_PREL_NC:
570 case R_ARM_MOVT_PREL:
571 case R_ARM_REL32:
572 case R_ARM_THM_ALU_PREL_11_0:
573 case R_ARM_THM_MOVW_PREL_NC:
574 case R_ARM_THM_MOVT_PREL:
575 case R_ARM_THM_PC12:
576 return p + a;
577 // p + a is unrepresentable as negative immediates can't be encoded.
578 case R_ARM_THM_PC8:
579 return p;
581 llvm_unreachable("ARM pc-relative relocation expected\n");
584 // The comment above getARMUndefinedRelativeWeakVA applies to this function.
585 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t type, uint64_t p) {
586 switch (type) {
587 // Unresolved branch relocations to weak references resolve to next
588 // instruction, this is 4 bytes on from P.
589 case R_AARCH64_CALL26:
590 case R_AARCH64_CONDBR19:
591 case R_AARCH64_JUMP26:
592 case R_AARCH64_TSTBR14:
593 return p + 4;
594 // Unresolved non branch pc-relative relocations
595 case R_AARCH64_PREL16:
596 case R_AARCH64_PREL32:
597 case R_AARCH64_PREL64:
598 case R_AARCH64_ADR_PREL_LO21:
599 case R_AARCH64_LD_PREL_LO19:
600 case R_AARCH64_PLT32:
601 return p;
603 llvm_unreachable("AArch64 pc-relative relocation expected\n");
606 static uint64_t getRISCVUndefinedRelativeWeakVA(uint64_t type, uint64_t p) {
607 switch (type) {
608 case R_RISCV_BRANCH:
609 case R_RISCV_JAL:
610 case R_RISCV_CALL:
611 case R_RISCV_CALL_PLT:
612 case R_RISCV_RVC_BRANCH:
613 case R_RISCV_RVC_JUMP:
614 case R_RISCV_PLT32:
615 return p;
616 default:
617 return 0;
621 // ARM SBREL relocations are of the form S + A - B where B is the static base
622 // The ARM ABI defines base to be "addressing origin of the output segment
623 // defining the symbol S". We defined the "addressing origin"/static base to be
624 // the base of the PT_LOAD segment containing the Sym.
625 // The procedure call standard only defines a Read Write Position Independent
626 // RWPI variant so in practice we should expect the static base to be the base
627 // of the RW segment.
628 static uint64_t getARMStaticBase(const Symbol &sym) {
629 OutputSection *os = sym.getOutputSection();
630 if (!os || !os->ptLoad || !os->ptLoad->firstSec)
631 Fatal(os->ctx) << "SBREL relocation to " << sym.getName()
632 << " without static base";
633 return os->ptLoad->firstSec->addr;
636 // For R_RISCV_PC_INDIRECT (R_RISCV_PCREL_LO12_{I,S}), the symbol actually
637 // points the corresponding R_RISCV_PCREL_HI20 relocation, and the target VA
638 // is calculated using PCREL_HI20's symbol.
640 // This function returns the R_RISCV_PCREL_HI20 relocation from the
641 // R_RISCV_PCREL_LO12 relocation.
642 static Relocation *getRISCVPCRelHi20(Ctx &ctx, const InputSectionBase *loSec,
643 const Relocation &loReloc) {
644 uint64_t addend = loReloc.addend;
645 Symbol *sym = loReloc.sym;
647 const Defined *d = cast<Defined>(sym);
648 if (!d->section) {
649 Err(ctx) << loSec->getLocation(loReloc.offset)
650 << ": R_RISCV_PCREL_LO12 relocation points to an absolute symbol: "
651 << sym->getName();
652 return nullptr;
654 InputSection *hiSec = cast<InputSection>(d->section);
656 if (hiSec != loSec)
657 Err(ctx) << loSec->getLocation(loReloc.offset)
658 << ": R_RISCV_PCREL_LO12 relocation points to a symbol '"
659 << sym->getName() << "' in a different section '" << hiSec->name
660 << "'";
662 if (addend != 0)
663 Warn(ctx) << loSec->getLocation(loReloc.offset)
664 << ": non-zero addend in R_RISCV_PCREL_LO12 relocation to "
665 << hiSec->getObjMsg(d->value) << " is ignored";
667 // Relocations are sorted by offset, so we can use std::equal_range to do
668 // binary search.
669 Relocation hiReloc;
670 hiReloc.offset = d->value;
671 auto range =
672 std::equal_range(hiSec->relocs().begin(), hiSec->relocs().end(), hiReloc,
673 [](const Relocation &lhs, const Relocation &rhs) {
674 return lhs.offset < rhs.offset;
677 for (auto it = range.first; it != range.second; ++it)
678 if (it->type == R_RISCV_PCREL_HI20 || it->type == R_RISCV_GOT_HI20 ||
679 it->type == R_RISCV_TLS_GD_HI20 || it->type == R_RISCV_TLS_GOT_HI20)
680 return &*it;
682 Err(ctx) << loSec->getLocation(loReloc.offset)
683 << ": R_RISCV_PCREL_LO12 relocation points to "
684 << hiSec->getObjMsg(d->value)
685 << " without an associated R_RISCV_PCREL_HI20 relocation";
686 return nullptr;
689 // A TLS symbol's virtual address is relative to the TLS segment. Add a
690 // target-specific adjustment to produce a thread-pointer-relative offset.
691 static int64_t getTlsTpOffset(Ctx &ctx, const Symbol &s) {
692 // On targets that support TLSDESC, _TLS_MODULE_BASE_@tpoff = 0.
693 if (&s == ctx.sym.tlsModuleBase)
694 return 0;
696 // There are 2 TLS layouts. Among targets we support, x86 uses TLS Variant 2
697 // while most others use Variant 1. At run time TP will be aligned to p_align.
699 // Variant 1. TP will be followed by an optional gap (which is the size of 2
700 // pointers on ARM/AArch64, 0 on other targets), followed by alignment
701 // padding, then the static TLS blocks. The alignment padding is added so that
702 // (TP + gap + padding) is congruent to p_vaddr modulo p_align.
704 // Variant 2. Static TLS blocks, followed by alignment padding are placed
705 // before TP. The alignment padding is added so that (TP - padding -
706 // p_memsz) is congruent to p_vaddr modulo p_align.
707 PhdrEntry *tls = ctx.tlsPhdr;
708 if (!tls) // Reported an error in getSymVA
709 return 0;
710 switch (ctx.arg.emachine) {
711 // Variant 1.
712 case EM_ARM:
713 case EM_AARCH64:
714 return s.getVA(ctx, 0) + ctx.arg.wordsize * 2 +
715 ((tls->p_vaddr - ctx.arg.wordsize * 2) & (tls->p_align - 1));
716 case EM_MIPS:
717 case EM_PPC:
718 case EM_PPC64:
719 // Adjusted Variant 1. TP is placed with a displacement of 0x7000, which is
720 // to allow a signed 16-bit offset to reach 0x1000 of TCB/thread-library
721 // data and 0xf000 of the program's TLS segment.
722 return s.getVA(ctx, 0) + (tls->p_vaddr & (tls->p_align - 1)) - 0x7000;
723 case EM_LOONGARCH:
724 case EM_RISCV:
725 // See the comment in handleTlsRelocation. For TLSDESC=>IE,
726 // R_RISCV_TLSDESC_{LOAD_LO12,ADD_LO12_I,CALL} also reach here. While
727 // `tls` may be null, the return value is ignored.
728 if (s.type != STT_TLS)
729 return 0;
730 return s.getVA(ctx, 0) + (tls->p_vaddr & (tls->p_align - 1));
732 // Variant 2.
733 case EM_HEXAGON:
734 case EM_S390:
735 case EM_SPARCV9:
736 case EM_386:
737 case EM_X86_64:
738 return s.getVA(ctx, 0) - tls->p_memsz -
739 ((-tls->p_vaddr - tls->p_memsz) & (tls->p_align - 1));
740 default:
741 llvm_unreachable("unhandled ctx.arg.emachine");
745 uint64_t InputSectionBase::getRelocTargetVA(Ctx &ctx, const Relocation &r,
746 uint64_t p) const {
747 int64_t a = r.addend;
748 switch (r.expr) {
749 case R_ABS:
750 case R_DTPREL:
751 case R_RELAX_TLS_LD_TO_LE_ABS:
752 case R_RELAX_GOT_PC_NOPIC:
753 case R_AARCH64_AUTH:
754 case R_RISCV_ADD:
755 case R_RISCV_LEB128:
756 return r.sym->getVA(ctx, a);
757 case R_ADDEND:
758 return a;
759 case R_RELAX_HINT:
760 return 0;
761 case R_ARM_SBREL:
762 return r.sym->getVA(ctx, a) - getARMStaticBase(*r.sym);
763 case R_GOT:
764 case R_RELAX_TLS_GD_TO_IE_ABS:
765 return r.sym->getGotVA(ctx) + a;
766 case R_LOONGARCH_GOT:
767 // The LoongArch TLS GD relocs reuse the R_LARCH_GOT_PC_LO12 reloc r.type
768 // for their page offsets. The arithmetics are different in the TLS case
769 // so we have to duplicate some logic here.
770 if (r.sym->hasFlag(NEEDS_TLSGD) && r.type != R_LARCH_TLS_IE_PC_LO12)
771 // Like R_LOONGARCH_TLSGD_PAGE_PC but taking the absolute value.
772 return ctx.in.got->getGlobalDynAddr(*r.sym) + a;
773 return r.sym->getGotVA(ctx) + a;
774 case R_GOTONLY_PC:
775 return ctx.in.got->getVA() + a - p;
776 case R_GOTPLTONLY_PC:
777 return ctx.in.gotPlt->getVA() + a - p;
778 case R_GOTREL:
779 case R_PPC64_RELAX_TOC:
780 return r.sym->getVA(ctx, a) - ctx.in.got->getVA();
781 case R_GOTPLTREL:
782 return r.sym->getVA(ctx, a) - ctx.in.gotPlt->getVA();
783 case R_GOTPLT:
784 case R_RELAX_TLS_GD_TO_IE_GOTPLT:
785 return r.sym->getGotVA(ctx) + a - ctx.in.gotPlt->getVA();
786 case R_TLSLD_GOT_OFF:
787 case R_GOT_OFF:
788 case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
789 return r.sym->getGotOffset(ctx) + a;
790 case R_AARCH64_GOT_PAGE_PC:
791 case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
792 return getAArch64Page(r.sym->getGotVA(ctx) + a) - getAArch64Page(p);
793 case R_AARCH64_GOT_PAGE:
794 return r.sym->getGotVA(ctx) + a - getAArch64Page(ctx.in.got->getVA());
795 case R_GOT_PC:
796 case R_RELAX_TLS_GD_TO_IE:
797 return r.sym->getGotVA(ctx) + a - p;
798 case R_GOTPLT_GOTREL:
799 return r.sym->getGotPltVA(ctx) + a - ctx.in.got->getVA();
800 case R_GOTPLT_PC:
801 return r.sym->getGotPltVA(ctx) + a - p;
802 case R_LOONGARCH_GOT_PAGE_PC:
803 if (r.sym->hasFlag(NEEDS_TLSGD))
804 return getLoongArchPageDelta(ctx.in.got->getGlobalDynAddr(*r.sym) + a, p,
805 r.type);
806 return getLoongArchPageDelta(r.sym->getGotVA(ctx) + a, p, r.type);
807 case R_MIPS_GOTREL:
808 return r.sym->getVA(ctx, a) - ctx.in.mipsGot->getGp(file);
809 case R_MIPS_GOT_GP:
810 return ctx.in.mipsGot->getGp(file) + a;
811 case R_MIPS_GOT_GP_PC: {
812 // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC r.type iif the target
813 // is _gp_disp symbol. In that case we should use the following
814 // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
815 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
816 // microMIPS variants of these relocations use slightly different
817 // expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi()
818 // to correctly handle less-significant bit of the microMIPS symbol.
819 uint64_t v = ctx.in.mipsGot->getGp(file) + a - p;
820 if (r.type == R_MIPS_LO16 || r.type == R_MICROMIPS_LO16)
821 v += 4;
822 if (r.type == R_MICROMIPS_LO16 || r.type == R_MICROMIPS_HI16)
823 v -= 1;
824 return v;
826 case R_MIPS_GOT_LOCAL_PAGE:
827 // If relocation against MIPS local symbol requires GOT entry, this entry
828 // should be initialized by 'page address'. This address is high 16-bits
829 // of sum the symbol's value and the addend.
830 return ctx.in.mipsGot->getVA() +
831 ctx.in.mipsGot->getPageEntryOffset(file, *r.sym, a) -
832 ctx.in.mipsGot->getGp(file);
833 case R_MIPS_GOT_OFF:
834 case R_MIPS_GOT_OFF32:
835 // In case of MIPS if a GOT relocation has non-zero addend this addend
836 // should be applied to the GOT entry content not to the GOT entry offset.
837 // That is why we use separate expression r.type.
838 return ctx.in.mipsGot->getVA() +
839 ctx.in.mipsGot->getSymEntryOffset(file, *r.sym, a) -
840 ctx.in.mipsGot->getGp(file);
841 case R_MIPS_TLSGD:
842 return ctx.in.mipsGot->getVA() +
843 ctx.in.mipsGot->getGlobalDynOffset(file, *r.sym) -
844 ctx.in.mipsGot->getGp(file);
845 case R_MIPS_TLSLD:
846 return ctx.in.mipsGot->getVA() + ctx.in.mipsGot->getTlsIndexOffset(file) -
847 ctx.in.mipsGot->getGp(file);
848 case R_AARCH64_PAGE_PC: {
849 uint64_t val = r.sym->isUndefWeak() ? p + a : r.sym->getVA(ctx, a);
850 return getAArch64Page(val) - getAArch64Page(p);
852 case R_RISCV_PC_INDIRECT: {
853 if (const Relocation *hiRel = getRISCVPCRelHi20(ctx, this, r))
854 return getRelocTargetVA(ctx, *hiRel, r.sym->getVA(ctx));
855 return 0;
857 case R_LOONGARCH_PAGE_PC:
858 return getLoongArchPageDelta(r.sym->getVA(ctx, a), p, r.type);
859 case R_PC:
860 case R_ARM_PCA: {
861 uint64_t dest;
862 if (r.expr == R_ARM_PCA)
863 // Some PC relative ARM (Thumb) relocations align down the place.
864 p = p & 0xfffffffc;
865 if (r.sym->isUndefined()) {
866 // On ARM and AArch64 a branch to an undefined weak resolves to the next
867 // instruction, otherwise the place. On RISC-V, resolve an undefined weak
868 // to the same instruction to cause an infinite loop (making the user
869 // aware of the issue) while ensuring no overflow.
870 // Note: if the symbol is hidden, its binding has been converted to local,
871 // so we just check isUndefined() here.
872 if (ctx.arg.emachine == EM_ARM)
873 dest = getARMUndefinedRelativeWeakVA(r.type, a, p);
874 else if (ctx.arg.emachine == EM_AARCH64)
875 dest = getAArch64UndefinedRelativeWeakVA(r.type, p) + a;
876 else if (ctx.arg.emachine == EM_PPC)
877 dest = p;
878 else if (ctx.arg.emachine == EM_RISCV)
879 dest = getRISCVUndefinedRelativeWeakVA(r.type, p) + a;
880 else
881 dest = r.sym->getVA(ctx, a);
882 } else {
883 dest = r.sym->getVA(ctx, a);
885 return dest - p;
887 case R_PLT:
888 return r.sym->getPltVA(ctx) + a;
889 case R_PLT_PC:
890 case R_PPC64_CALL_PLT:
891 return r.sym->getPltVA(ctx) + a - p;
892 case R_LOONGARCH_PLT_PAGE_PC:
893 return getLoongArchPageDelta(r.sym->getPltVA(ctx) + a, p, r.type);
894 case R_PLT_GOTPLT:
895 return r.sym->getPltVA(ctx) + a - ctx.in.gotPlt->getVA();
896 case R_PLT_GOTREL:
897 return r.sym->getPltVA(ctx) + a - ctx.in.got->getVA();
898 case R_PPC32_PLTREL:
899 // R_PPC_PLTREL24 uses the addend (usually 0 or 0x8000) to indicate r30
900 // stores _GLOBAL_OFFSET_TABLE_ or .got2+0x8000. The addend is ignored for
901 // target VA computation.
902 return r.sym->getPltVA(ctx) - p;
903 case R_PPC64_CALL: {
904 uint64_t symVA = r.sym->getVA(ctx, a);
905 // If we have an undefined weak symbol, we might get here with a symbol
906 // address of zero. That could overflow, but the code must be unreachable,
907 // so don't bother doing anything at all.
908 if (!symVA)
909 return 0;
911 // PPC64 V2 ABI describes two entry points to a function. The global entry
912 // point is used for calls where the caller and callee (may) have different
913 // TOC base pointers and r2 needs to be modified to hold the TOC base for
914 // the callee. For local calls the caller and callee share the same
915 // TOC base and so the TOC pointer initialization code should be skipped by
916 // branching to the local entry point.
917 return symVA - p +
918 getPPC64GlobalEntryToLocalEntryOffset(ctx, r.sym->stOther);
920 case R_PPC64_TOCBASE:
921 return getPPC64TocBase(ctx) + a;
922 case R_RELAX_GOT_PC:
923 case R_PPC64_RELAX_GOT_PC:
924 return r.sym->getVA(ctx, a) - p;
925 case R_RELAX_TLS_GD_TO_LE:
926 case R_RELAX_TLS_IE_TO_LE:
927 case R_RELAX_TLS_LD_TO_LE:
928 case R_TPREL:
929 // It is not very clear what to return if the symbol is undefined. With
930 // --noinhibit-exec, even a non-weak undefined reference may reach here.
931 // Just return A, which matches R_ABS, and the behavior of some dynamic
932 // loaders.
933 if (r.sym->isUndefined())
934 return a;
935 return getTlsTpOffset(ctx, *r.sym) + a;
936 case R_RELAX_TLS_GD_TO_LE_NEG:
937 case R_TPREL_NEG:
938 if (r.sym->isUndefined())
939 return a;
940 return -getTlsTpOffset(ctx, *r.sym) + a;
941 case R_SIZE:
942 return r.sym->getSize() + a;
943 case R_TLSDESC:
944 return ctx.in.got->getTlsDescAddr(*r.sym) + a;
945 case R_TLSDESC_PC:
946 return ctx.in.got->getTlsDescAddr(*r.sym) + a - p;
947 case R_TLSDESC_GOTPLT:
948 return ctx.in.got->getTlsDescAddr(*r.sym) + a - ctx.in.gotPlt->getVA();
949 case R_AARCH64_TLSDESC_PAGE:
950 return getAArch64Page(ctx.in.got->getTlsDescAddr(*r.sym) + a) -
951 getAArch64Page(p);
952 case R_LOONGARCH_TLSDESC_PAGE_PC:
953 return getLoongArchPageDelta(ctx.in.got->getTlsDescAddr(*r.sym) + a, p,
954 r.type);
955 case R_TLSGD_GOT:
956 return ctx.in.got->getGlobalDynOffset(*r.sym) + a;
957 case R_TLSGD_GOTPLT:
958 return ctx.in.got->getGlobalDynAddr(*r.sym) + a - ctx.in.gotPlt->getVA();
959 case R_TLSGD_PC:
960 return ctx.in.got->getGlobalDynAddr(*r.sym) + a - p;
961 case R_LOONGARCH_TLSGD_PAGE_PC:
962 return getLoongArchPageDelta(ctx.in.got->getGlobalDynAddr(*r.sym) + a, p,
963 r.type);
964 case R_TLSLD_GOTPLT:
965 return ctx.in.got->getVA() + ctx.in.got->getTlsIndexOff() + a -
966 ctx.in.gotPlt->getVA();
967 case R_TLSLD_GOT:
968 return ctx.in.got->getTlsIndexOff() + a;
969 case R_TLSLD_PC:
970 return ctx.in.got->getTlsIndexVA() + a - p;
971 default:
972 llvm_unreachable("invalid expression");
976 // This function applies relocations to sections without SHF_ALLOC bit.
977 // Such sections are never mapped to memory at runtime. Debug sections are
978 // an example. Relocations in non-alloc sections are much easier to
979 // handle than in allocated sections because it will never need complex
980 // treatment such as GOT or PLT (because at runtime no one refers them).
981 // So, we handle relocations for non-alloc sections directly in this
982 // function as a performance optimization.
983 template <class ELFT, class RelTy>
984 void InputSection::relocateNonAlloc(Ctx &ctx, uint8_t *buf,
985 Relocs<RelTy> rels) {
986 const unsigned bits = sizeof(typename ELFT::uint) * 8;
987 const TargetInfo &target = *ctx.target;
988 const auto emachine = ctx.arg.emachine;
989 const bool isDebug = isDebugSection(*this);
990 const bool isDebugLine = isDebug && name == ".debug_line";
991 std::optional<uint64_t> tombstone;
992 if (isDebug) {
993 if (name == ".debug_loc" || name == ".debug_ranges")
994 tombstone = 1;
995 else if (name == ".debug_names")
996 tombstone = UINT64_MAX; // tombstone value
997 else
998 tombstone = 0;
1000 for (const auto &patAndValue : llvm::reverse(ctx.arg.deadRelocInNonAlloc))
1001 if (patAndValue.first.match(this->name)) {
1002 tombstone = patAndValue.second;
1003 break;
1006 const InputFile *f = this->file;
1007 for (auto it = rels.begin(), end = rels.end(); it != end; ++it) {
1008 const RelTy &rel = *it;
1009 const RelType type = rel.getType(ctx.arg.isMips64EL);
1010 const uint64_t offset = rel.r_offset;
1011 uint8_t *bufLoc = buf + offset;
1012 int64_t addend = getAddend<ELFT>(rel);
1013 if (!RelTy::HasAddend)
1014 addend += target.getImplicitAddend(bufLoc, type);
1016 Symbol &sym = f->getRelocTargetSym(rel);
1017 RelExpr expr = target.getRelExpr(type, sym, bufLoc);
1018 if (expr == R_NONE)
1019 continue;
1020 auto *ds = dyn_cast<Defined>(&sym);
1022 if (emachine == EM_RISCV && type == R_RISCV_SET_ULEB128) {
1023 if (++it != end &&
1024 it->getType(/*isMips64EL=*/false) == R_RISCV_SUB_ULEB128 &&
1025 it->r_offset == offset) {
1026 uint64_t val;
1027 if (!ds && tombstone) {
1028 val = *tombstone;
1029 } else {
1030 val = sym.getVA(ctx, addend) -
1031 (f->getRelocTargetSym(*it).getVA(ctx) + getAddend<ELFT>(*it));
1033 if (overwriteULEB128(bufLoc, val) >= 0x80)
1034 Err(ctx) << getLocation(offset) << ": ULEB128 value " << val
1035 << " exceeds available space; references '" << &sym << "'";
1036 continue;
1038 Err(ctx) << getLocation(offset)
1039 << ": R_RISCV_SET_ULEB128 not paired with R_RISCV_SUB_SET128";
1040 return;
1043 if (tombstone && (expr == R_ABS || expr == R_DTPREL)) {
1044 // Resolve relocations in .debug_* referencing (discarded symbols or ICF
1045 // folded section symbols) to a tombstone value. Resolving to addend is
1046 // unsatisfactory because the result address range may collide with a
1047 // valid range of low address, or leave multiple CUs claiming ownership of
1048 // the same range of code, which may confuse consumers.
1050 // To address the problems, we use -1 as a tombstone value for most
1051 // .debug_* sections. We have to ignore the addend because we don't want
1052 // to resolve an address attribute (which may have a non-zero addend) to
1053 // -1+addend (wrap around to a low address).
1055 // R_DTPREL type relocations represent an offset into the dynamic thread
1056 // vector. The computed value is st_value plus a non-negative offset.
1057 // Negative values are invalid, so -1 can be used as the tombstone value.
1059 // If the referenced symbol is relative to a discarded section (due to
1060 // --gc-sections, COMDAT, etc), it has been converted to a Undefined.
1061 // `ds->folded` catches the ICF folded case. However, resolving a
1062 // relocation in .debug_line to -1 would stop debugger users from setting
1063 // breakpoints on the folded-in function, so exclude .debug_line.
1065 // For pre-DWARF-v5 .debug_loc and .debug_ranges, -1 is a reserved value
1066 // (base address selection entry), use 1 (which is used by GNU ld for
1067 // .debug_ranges).
1069 // TODO To reduce disruption, we use 0 instead of -1 as the tombstone
1070 // value. Enable -1 in a future release.
1071 if (!ds || (ds->folded && !isDebugLine)) {
1072 // If -z dead-reloc-in-nonalloc= is specified, respect it.
1073 uint64_t value = SignExtend64<bits>(*tombstone);
1074 // For a 32-bit local TU reference in .debug_names, X86_64::relocate
1075 // requires that the unsigned value for R_X86_64_32 is truncated to
1076 // 32-bit. Other 64-bit targets's don't discern signed/unsigned 32-bit
1077 // absolute relocations and do not need this change.
1078 if (emachine == EM_X86_64 && type == R_X86_64_32)
1079 value = static_cast<uint32_t>(value);
1080 target.relocateNoSym(bufLoc, type, value);
1081 continue;
1085 // For a relocatable link, content relocated by relocation types with an
1086 // explicit addend, such as RELA, remain unchanged and we can stop here.
1087 // While content relocated by relocation types with an implicit addend, such
1088 // as REL, needs the implicit addend updated.
1089 if (ctx.arg.relocatable && (RelTy::HasAddend || sym.type != STT_SECTION))
1090 continue;
1092 // R_ABS/R_DTPREL and some other relocations can be used from non-SHF_ALLOC
1093 // sections.
1094 if (LLVM_LIKELY(expr == R_ABS) || expr == R_DTPREL || expr == R_GOTPLTREL ||
1095 expr == R_RISCV_ADD) {
1096 target.relocateNoSym(bufLoc, type,
1097 SignExtend64<bits>(sym.getVA(ctx, addend)));
1098 continue;
1101 if (expr == R_SIZE) {
1102 target.relocateNoSym(bufLoc, type,
1103 SignExtend64<bits>(sym.getSize() + addend));
1104 continue;
1107 // If the control reaches here, we found a PC-relative relocation in a
1108 // non-ALLOC section. Since non-ALLOC section is not loaded into memory
1109 // at runtime, the notion of PC-relative doesn't make sense here. So,
1110 // this is a usage error. However, GNU linkers historically accept such
1111 // relocations without any errors and relocate them as if they were at
1112 // address 0. For bug-compatibility, we accept them with warnings. We
1113 // know Steel Bank Common Lisp as of 2018 have this bug.
1115 // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations
1116 // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed in
1117 // 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we need to
1118 // keep this bug-compatible code for a while.
1119 bool isErr = expr != R_PC && !(emachine == EM_386 && type == R_386_GOTPC);
1121 ELFSyncStream diag(ctx, isErr && !ctx.arg.noinhibitExec
1122 ? DiagLevel::Err
1123 : DiagLevel::Warn);
1124 diag << getLocation(offset) << ": has non-ABS relocation " << type
1125 << " against symbol '" << &sym << "'";
1127 if (!isErr)
1128 target.relocateNoSym(
1129 bufLoc, type,
1130 SignExtend64<bits>(sym.getVA(ctx, addend - offset - outSecOff)));
1134 template <class ELFT>
1135 void InputSectionBase::relocate(Ctx &ctx, uint8_t *buf, uint8_t *bufEnd) {
1136 if ((flags & SHF_EXECINSTR) && LLVM_UNLIKELY(getFile<ELFT>()->splitStack))
1137 adjustSplitStackFunctionPrologues<ELFT>(ctx, buf, bufEnd);
1139 if (flags & SHF_ALLOC) {
1140 ctx.target->relocateAlloc(*this, buf);
1141 return;
1144 auto *sec = cast<InputSection>(this);
1145 // For a relocatable link, also call relocateNonAlloc() to rewrite applicable
1146 // locations with tombstone values.
1147 invokeOnRelocs(*sec, sec->relocateNonAlloc<ELFT>, ctx, buf);
1150 // For each function-defining prologue, find any calls to __morestack,
1151 // and replace them with calls to __morestack_non_split.
1152 static void switchMorestackCallsToMorestackNonSplit(
1153 Ctx &ctx, DenseSet<Defined *> &prologues,
1154 SmallVector<Relocation *, 0> &morestackCalls) {
1156 // If the target adjusted a function's prologue, all calls to
1157 // __morestack inside that function should be switched to
1158 // __morestack_non_split.
1159 Symbol *moreStackNonSplit = ctx.symtab->find("__morestack_non_split");
1160 if (!moreStackNonSplit) {
1161 ErrAlways(ctx) << "mixing split-stack objects requires a definition of "
1162 "__morestack_non_split";
1163 return;
1166 // Sort both collections to compare addresses efficiently.
1167 llvm::sort(morestackCalls, [](const Relocation *l, const Relocation *r) {
1168 return l->offset < r->offset;
1170 std::vector<Defined *> functions(prologues.begin(), prologues.end());
1171 llvm::sort(functions, [](const Defined *l, const Defined *r) {
1172 return l->value < r->value;
1175 auto it = morestackCalls.begin();
1176 for (Defined *f : functions) {
1177 // Find the first call to __morestack within the function.
1178 while (it != morestackCalls.end() && (*it)->offset < f->value)
1179 ++it;
1180 // Adjust all calls inside the function.
1181 while (it != morestackCalls.end() && (*it)->offset < f->value + f->size) {
1182 (*it)->sym = moreStackNonSplit;
1183 ++it;
1188 static bool enclosingPrologueAttempted(uint64_t offset,
1189 const DenseSet<Defined *> &prologues) {
1190 for (Defined *f : prologues)
1191 if (f->value <= offset && offset < f->value + f->size)
1192 return true;
1193 return false;
1196 // If a function compiled for split stack calls a function not
1197 // compiled for split stack, then the caller needs its prologue
1198 // adjusted to ensure that the called function will have enough stack
1199 // available. Find those functions, and adjust their prologues.
1200 template <class ELFT>
1201 void InputSectionBase::adjustSplitStackFunctionPrologues(Ctx &ctx, uint8_t *buf,
1202 uint8_t *end) {
1203 DenseSet<Defined *> prologues;
1204 SmallVector<Relocation *, 0> morestackCalls;
1206 for (Relocation &rel : relocs()) {
1207 // Ignore calls into the split-stack api.
1208 if (rel.sym->getName().starts_with("__morestack")) {
1209 if (rel.sym->getName() == "__morestack")
1210 morestackCalls.push_back(&rel);
1211 continue;
1214 // A relocation to non-function isn't relevant. Sometimes
1215 // __morestack is not marked as a function, so this check comes
1216 // after the name check.
1217 if (rel.sym->type != STT_FUNC)
1218 continue;
1220 // If the callee's-file was compiled with split stack, nothing to do. In
1221 // this context, a "Defined" symbol is one "defined by the binary currently
1222 // being produced". So an "undefined" symbol might be provided by a shared
1223 // library. It is not possible to tell how such symbols were compiled, so be
1224 // conservative.
1225 if (Defined *d = dyn_cast<Defined>(rel.sym))
1226 if (InputSection *isec = cast_or_null<InputSection>(d->section))
1227 if (!isec || !isec->getFile<ELFT>() || isec->getFile<ELFT>()->splitStack)
1228 continue;
1230 if (enclosingPrologueAttempted(rel.offset, prologues))
1231 continue;
1233 if (Defined *f = getEnclosingFunction(rel.offset)) {
1234 prologues.insert(f);
1235 if (ctx.target->adjustPrologueForCrossSplitStack(buf + f->value, end,
1236 f->stOther))
1237 continue;
1238 if (!getFile<ELFT>()->someNoSplitStack)
1239 Err(ctx)
1240 << this << ": " << f->getName() << " (with -fsplit-stack) calls "
1241 << rel.sym->getName()
1242 << " (without -fsplit-stack), but couldn't adjust its prologue";
1246 if (ctx.target->needsMoreStackNonSplit)
1247 switchMorestackCallsToMorestackNonSplit(ctx, prologues, morestackCalls);
1250 template <class ELFT> void InputSection::writeTo(Ctx &ctx, uint8_t *buf) {
1251 if (LLVM_UNLIKELY(type == SHT_NOBITS))
1252 return;
1253 // If -r or --emit-relocs is given, then an InputSection
1254 // may be a relocation section.
1255 if (LLVM_UNLIKELY(type == SHT_RELA)) {
1256 copyRelocations<ELFT, typename ELFT::Rela>(ctx, buf);
1257 return;
1259 if (LLVM_UNLIKELY(type == SHT_REL)) {
1260 copyRelocations<ELFT, typename ELFT::Rel>(ctx, buf);
1261 return;
1264 // If -r is given, we may have a SHT_GROUP section.
1265 if (LLVM_UNLIKELY(type == SHT_GROUP)) {
1266 copyShtGroup<ELFT>(buf);
1267 return;
1270 // If this is a compressed section, uncompress section contents directly
1271 // to the buffer.
1272 if (compressed) {
1273 auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(content_);
1274 auto compressed = ArrayRef<uint8_t>(content_, compressedSize)
1275 .slice(sizeof(typename ELFT::Chdr));
1276 size_t size = this->size;
1277 if (Error e = hdr->ch_type == ELFCOMPRESS_ZLIB
1278 ? compression::zlib::decompress(compressed, buf, size)
1279 : compression::zstd::decompress(compressed, buf, size))
1280 Fatal(ctx) << this << ": decompress failed: " << std::move(e);
1281 uint8_t *bufEnd = buf + size;
1282 relocate<ELFT>(ctx, buf, bufEnd);
1283 return;
1286 // Copy section contents from source object file to output file
1287 // and then apply relocations.
1288 memcpy(buf, content().data(), content().size());
1289 relocate<ELFT>(ctx, buf, buf + content().size());
1292 void InputSection::replace(InputSection *other) {
1293 addralign = std::max(addralign, other->addralign);
1295 // When a section is replaced with another section that was allocated to
1296 // another partition, the replacement section (and its associated sections)
1297 // need to be placed in the main partition so that both partitions will be
1298 // able to access it.
1299 if (partition != other->partition) {
1300 partition = 1;
1301 for (InputSection *isec : dependentSections)
1302 isec->partition = 1;
1305 other->repl = repl;
1306 other->markDead();
1309 template <class ELFT>
1310 EhInputSection::EhInputSection(ObjFile<ELFT> &f,
1311 const typename ELFT::Shdr &header,
1312 StringRef name)
1313 : InputSectionBase(f, header, name, InputSectionBase::EHFrame) {}
1315 SyntheticSection *EhInputSection::getParent() const {
1316 return cast_or_null<SyntheticSection>(parent);
1319 // .eh_frame is a sequence of CIE or FDE records.
1320 // This function splits an input section into records and returns them.
1321 template <class ELFT> void EhInputSection::split() {
1322 const RelsOrRelas<ELFT> rels = relsOrRelas<ELFT>(/*supportsCrel=*/false);
1323 // getReloc expects the relocations to be sorted by r_offset. See the comment
1324 // in scanRelocs.
1325 if (rels.areRelocsRel()) {
1326 SmallVector<typename ELFT::Rel, 0> storage;
1327 split<ELFT>(sortRels(rels.rels, storage));
1328 } else {
1329 SmallVector<typename ELFT::Rela, 0> storage;
1330 split<ELFT>(sortRels(rels.relas, storage));
1334 template <class ELFT, class RelTy>
1335 void EhInputSection::split(ArrayRef<RelTy> rels) {
1336 ArrayRef<uint8_t> d = content();
1337 const char *msg = nullptr;
1338 unsigned relI = 0;
1339 while (!d.empty()) {
1340 if (d.size() < 4) {
1341 msg = "CIE/FDE too small";
1342 break;
1344 uint64_t size = endian::read32<ELFT::Endianness>(d.data());
1345 if (size == 0) // ZERO terminator
1346 break;
1347 uint32_t id = endian::read32<ELFT::Endianness>(d.data() + 4);
1348 size += 4;
1349 if (LLVM_UNLIKELY(size > d.size())) {
1350 // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead,
1351 // but we do not support that format yet.
1352 msg = size == UINT32_MAX + uint64_t(4)
1353 ? "CIE/FDE too large"
1354 : "CIE/FDE ends past the end of the section";
1355 break;
1358 // Find the first relocation that points to [off,off+size). Relocations
1359 // have been sorted by r_offset.
1360 const uint64_t off = d.data() - content().data();
1361 while (relI != rels.size() && rels[relI].r_offset < off)
1362 ++relI;
1363 unsigned firstRel = -1;
1364 if (relI != rels.size() && rels[relI].r_offset < off + size)
1365 firstRel = relI;
1366 (id == 0 ? cies : fdes).emplace_back(off, this, size, firstRel);
1367 d = d.slice(size);
1369 if (msg)
1370 Err(file->ctx) << "corrupted .eh_frame: " << msg << "\n>>> defined in "
1371 << getObjMsg(d.data() - content().data());
1374 // Return the offset in an output section for a given input offset.
1375 uint64_t EhInputSection::getParentOffset(uint64_t offset) const {
1376 auto it = partition_point(
1377 fdes, [=](EhSectionPiece p) { return p.inputOff <= offset; });
1378 if (it == fdes.begin() || it[-1].inputOff + it[-1].size <= offset) {
1379 it = partition_point(
1380 cies, [=](EhSectionPiece p) { return p.inputOff <= offset; });
1381 if (it == cies.begin()) // invalid piece
1382 return offset;
1384 if (it[-1].outputOff == -1) // invalid piece
1385 return offset - it[-1].inputOff;
1386 return it[-1].outputOff + (offset - it[-1].inputOff);
1389 static size_t findNull(StringRef s, size_t entSize) {
1390 for (unsigned i = 0, n = s.size(); i != n; i += entSize) {
1391 const char *b = s.begin() + i;
1392 if (std::all_of(b, b + entSize, [](char c) { return c == 0; }))
1393 return i;
1395 llvm_unreachable("");
1398 // Split SHF_STRINGS section. Such section is a sequence of
1399 // null-terminated strings.
1400 void MergeInputSection::splitStrings(StringRef s, size_t entSize) {
1401 const bool live = !(flags & SHF_ALLOC) || !getCtx().arg.gcSections;
1402 const char *p = s.data(), *end = s.data() + s.size();
1403 if (!std::all_of(end - entSize, end, [](char c) { return c == 0; }))
1404 Fatal(getCtx()) << this << ": string is not null terminated";
1405 if (entSize == 1) {
1406 // Optimize the common case.
1407 do {
1408 size_t size = strlen(p);
1409 pieces.emplace_back(p - s.begin(), xxh3_64bits(StringRef(p, size)), live);
1410 p += size + 1;
1411 } while (p != end);
1412 } else {
1413 do {
1414 size_t size = findNull(StringRef(p, end - p), entSize);
1415 pieces.emplace_back(p - s.begin(), xxh3_64bits(StringRef(p, size)), live);
1416 p += size + entSize;
1417 } while (p != end);
1421 // Split non-SHF_STRINGS section. Such section is a sequence of
1422 // fixed size records.
1423 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> data,
1424 size_t entSize) {
1425 size_t size = data.size();
1426 assert((size % entSize) == 0);
1427 const bool live = !(flags & SHF_ALLOC) || !getCtx().arg.gcSections;
1429 pieces.resize_for_overwrite(size / entSize);
1430 for (size_t i = 0, j = 0; i != size; i += entSize, j++)
1431 pieces[j] = {i, (uint32_t)xxh3_64bits(data.slice(i, entSize)), live};
1434 template <class ELFT>
1435 MergeInputSection::MergeInputSection(ObjFile<ELFT> &f,
1436 const typename ELFT::Shdr &header,
1437 StringRef name)
1438 : InputSectionBase(f, header, name, InputSectionBase::Merge) {}
1440 MergeInputSection::MergeInputSection(Ctx &ctx, uint64_t flags, uint32_t type,
1441 uint64_t entsize, ArrayRef<uint8_t> data,
1442 StringRef name)
1443 : InputSectionBase(ctx.internalFile, flags, type, entsize, /*link=*/0,
1444 /*info=*/0,
1445 /*alignment=*/entsize, data, name, SectionBase::Merge) {}
1447 // This function is called after we obtain a complete list of input sections
1448 // that need to be linked. This is responsible to split section contents
1449 // into small chunks for further processing.
1451 // Note that this function is called from parallelForEach. This must be
1452 // thread-safe (i.e. no memory allocation from the pools).
1453 void MergeInputSection::splitIntoPieces() {
1454 assert(pieces.empty());
1456 if (flags & SHF_STRINGS)
1457 splitStrings(toStringRef(contentMaybeDecompress()), entsize);
1458 else
1459 splitNonStrings(contentMaybeDecompress(), entsize);
1462 SectionPiece &MergeInputSection::getSectionPiece(uint64_t offset) {
1463 if (content().size() <= offset)
1464 Fatal(getCtx()) << this << ": offset is outside the section";
1465 return partition_point(
1466 pieces, [=](SectionPiece p) { return p.inputOff <= offset; })[-1];
1469 // Return the offset in an output section for a given input offset.
1470 uint64_t MergeInputSection::getParentOffset(uint64_t offset) const {
1471 const SectionPiece &piece = getSectionPiece(offset);
1472 return piece.outputOff + (offset - piece.inputOff);
1475 template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
1476 StringRef);
1477 template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
1478 StringRef);
1479 template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
1480 StringRef);
1481 template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
1482 StringRef);
1484 template void InputSection::writeTo<ELF32LE>(Ctx &, uint8_t *);
1485 template void InputSection::writeTo<ELF32BE>(Ctx &, uint8_t *);
1486 template void InputSection::writeTo<ELF64LE>(Ctx &, uint8_t *);
1487 template void InputSection::writeTo<ELF64BE>(Ctx &, uint8_t *);
1489 template RelsOrRelas<ELF32LE>
1490 InputSectionBase::relsOrRelas<ELF32LE>(bool) const;
1491 template RelsOrRelas<ELF32BE>
1492 InputSectionBase::relsOrRelas<ELF32BE>(bool) const;
1493 template RelsOrRelas<ELF64LE>
1494 InputSectionBase::relsOrRelas<ELF64LE>(bool) const;
1495 template RelsOrRelas<ELF64BE>
1496 InputSectionBase::relsOrRelas<ELF64BE>(bool) const;
1498 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
1499 const ELF32LE::Shdr &, StringRef);
1500 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
1501 const ELF32BE::Shdr &, StringRef);
1502 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
1503 const ELF64LE::Shdr &, StringRef);
1504 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
1505 const ELF64BE::Shdr &, StringRef);
1507 template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
1508 const ELF32LE::Shdr &, StringRef);
1509 template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
1510 const ELF32BE::Shdr &, StringRef);
1511 template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
1512 const ELF64LE::Shdr &, StringRef);
1513 template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
1514 const ELF64BE::Shdr &, StringRef);
1516 template void EhInputSection::split<ELF32LE>();
1517 template void EhInputSection::split<ELF32BE>();
1518 template void EhInputSection::split<ELF64LE>();
1519 template void EhInputSection::split<ELF64BE>();