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