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