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