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