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