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