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