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