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