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