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     errorOrWarn("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   errorOrWarn("R_RISCV_PCREL_LO12 relocation points to " +
561               isec->getObjMsg(d->value) +
562               " without an associated R_RISCV_PCREL_HI20 relocation");
563   return nullptr;
564 }
565 
566 // A TLS symbol's virtual address is relative to the TLS segment. Add a
567 // target-specific adjustment to produce a thread-pointer-relative offset.
568 static int64_t getTlsTpOffset(const Symbol &s) {
569   // On targets that support TLSDESC, _TLS_MODULE_BASE_@tpoff = 0.
570   if (&s == ElfSym::tlsModuleBase)
571     return 0;
572 
573   // There are 2 TLS layouts. Among targets we support, x86 uses TLS Variant 2
574   // while most others use Variant 1. At run time TP will be aligned to p_align.
575 
576   // Variant 1. TP will be followed by an optional gap (which is the size of 2
577   // pointers on ARM/AArch64, 0 on other targets), followed by alignment
578   // padding, then the static TLS blocks. The alignment padding is added so that
579   // (TP + gap + padding) is congruent to p_vaddr modulo p_align.
580   //
581   // Variant 2. Static TLS blocks, followed by alignment padding are placed
582   // before TP. The alignment padding is added so that (TP - padding -
583   // p_memsz) is congruent to p_vaddr modulo p_align.
584   PhdrEntry *tls = Out::tlsPhdr;
585   switch (config->emachine) {
586     // Variant 1.
587   case EM_ARM:
588   case EM_AARCH64:
589     return s.getVA(0) + config->wordsize * 2 +
590            ((tls->p_vaddr - config->wordsize * 2) & (tls->p_align - 1));
591   case EM_MIPS:
592   case EM_PPC:
593   case EM_PPC64:
594     // Adjusted Variant 1. TP is placed with a displacement of 0x7000, which is
595     // to allow a signed 16-bit offset to reach 0x1000 of TCB/thread-library
596     // data and 0xf000 of the program's TLS segment.
597     return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1)) - 0x7000;
598   case EM_RISCV:
599     return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1));
600 
601     // Variant 2.
602   case EM_HEXAGON:
603   case EM_SPARCV9:
604   case EM_386:
605   case EM_X86_64:
606     return s.getVA(0) - tls->p_memsz -
607            ((-tls->p_vaddr - tls->p_memsz) & (tls->p_align - 1));
608   default:
609     llvm_unreachable("unhandled Config->EMachine");
610   }
611 }
612 
613 uint64_t InputSectionBase::getRelocTargetVA(const InputFile *file, RelType type,
614                                             int64_t a, uint64_t p,
615                                             const Symbol &sym, RelExpr expr) {
616   switch (expr) {
617   case R_ABS:
618   case R_DTPREL:
619   case R_RELAX_TLS_LD_TO_LE_ABS:
620   case R_RELAX_GOT_PC_NOPIC:
621   case R_RISCV_ADD:
622     return sym.getVA(a);
623   case R_ADDEND:
624     return a;
625   case R_ARM_SBREL:
626     return sym.getVA(a) - getARMStaticBase(sym);
627   case R_GOT:
628   case R_RELAX_TLS_GD_TO_IE_ABS:
629     return sym.getGotVA() + a;
630   case R_GOTONLY_PC:
631     return in.got->getVA() + a - p;
632   case R_GOTPLTONLY_PC:
633     return in.gotPlt->getVA() + a - p;
634   case R_GOTREL:
635   case R_PPC64_RELAX_TOC:
636     return sym.getVA(a) - in.got->getVA();
637   case R_GOTPLTREL:
638     return sym.getVA(a) - in.gotPlt->getVA();
639   case R_GOTPLT:
640   case R_RELAX_TLS_GD_TO_IE_GOTPLT:
641     return sym.getGotVA() + a - in.gotPlt->getVA();
642   case R_TLSLD_GOT_OFF:
643   case R_GOT_OFF:
644   case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
645     return sym.getGotOffset() + a;
646   case R_AARCH64_GOT_PAGE_PC:
647   case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
648     return getAArch64Page(sym.getGotVA() + a) - getAArch64Page(p);
649   case R_AARCH64_GOT_PAGE:
650     return sym.getGotVA() + a - getAArch64Page(in.got->getVA());
651   case R_GOT_PC:
652   case R_RELAX_TLS_GD_TO_IE:
653     return sym.getGotVA() + a - p;
654   case R_MIPS_GOTREL:
655     return sym.getVA(a) - in.mipsGot->getGp(file);
656   case R_MIPS_GOT_GP:
657     return in.mipsGot->getGp(file) + a;
658   case R_MIPS_GOT_GP_PC: {
659     // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
660     // is _gp_disp symbol. In that case we should use the following
661     // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
662     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
663     // microMIPS variants of these relocations use slightly different
664     // expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi()
665     // to correctly handle less-significant bit of the microMIPS symbol.
666     uint64_t v = in.mipsGot->getGp(file) + a - p;
667     if (type == R_MIPS_LO16 || type == R_MICROMIPS_LO16)
668       v += 4;
669     if (type == R_MICROMIPS_LO16 || type == R_MICROMIPS_HI16)
670       v -= 1;
671     return v;
672   }
673   case R_MIPS_GOT_LOCAL_PAGE:
674     // If relocation against MIPS local symbol requires GOT entry, this entry
675     // should be initialized by 'page address'. This address is high 16-bits
676     // of sum the symbol's value and the addend.
677     return in.mipsGot->getVA() + in.mipsGot->getPageEntryOffset(file, sym, a) -
678            in.mipsGot->getGp(file);
679   case R_MIPS_GOT_OFF:
680   case R_MIPS_GOT_OFF32:
681     // In case of MIPS if a GOT relocation has non-zero addend this addend
682     // should be applied to the GOT entry content not to the GOT entry offset.
683     // That is why we use separate expression type.
684     return in.mipsGot->getVA() + in.mipsGot->getSymEntryOffset(file, sym, a) -
685            in.mipsGot->getGp(file);
686   case R_MIPS_TLSGD:
687     return in.mipsGot->getVA() + in.mipsGot->getGlobalDynOffset(file, sym) -
688            in.mipsGot->getGp(file);
689   case R_MIPS_TLSLD:
690     return in.mipsGot->getVA() + in.mipsGot->getTlsIndexOffset(file) -
691            in.mipsGot->getGp(file);
692   case R_AARCH64_PAGE_PC: {
693     uint64_t val = sym.isUndefWeak() ? p + a : sym.getVA(a);
694     return getAArch64Page(val) - getAArch64Page(p);
695   }
696   case R_RISCV_PC_INDIRECT: {
697     if (const Relocation *hiRel = getRISCVPCRelHi20(&sym, a))
698       return getRelocTargetVA(file, hiRel->type, hiRel->addend, sym.getVA(),
699                               *hiRel->sym, hiRel->expr);
700     return 0;
701   }
702   case R_PC:
703   case R_ARM_PCA: {
704     uint64_t dest;
705     if (expr == R_ARM_PCA)
706       // Some PC relative ARM (Thumb) relocations align down the place.
707       p = p & 0xfffffffc;
708     if (sym.isUndefined()) {
709       // On ARM and AArch64 a branch to an undefined weak resolves to the next
710       // instruction, otherwise the place. On RISCV, resolve an undefined weak
711       // to the same instruction to cause an infinite loop (making the user
712       // aware of the issue) while ensuring no overflow.
713       // Note: if the symbol is hidden, its binding has been converted to local,
714       // so we just check isUndefined() here.
715       if (config->emachine == EM_ARM)
716         dest = getARMUndefinedRelativeWeakVA(type, a, p);
717       else if (config->emachine == EM_AARCH64)
718         dest = getAArch64UndefinedRelativeWeakVA(type, p) + a;
719       else if (config->emachine == EM_PPC)
720         dest = p;
721       else if (config->emachine == EM_RISCV)
722         dest = getRISCVUndefinedRelativeWeakVA(type, p) + a;
723       else
724         dest = sym.getVA(a);
725     } else {
726       dest = sym.getVA(a);
727     }
728     return dest - p;
729   }
730   case R_PLT:
731     return sym.getPltVA() + a;
732   case R_PLT_PC:
733   case R_PPC64_CALL_PLT:
734     return sym.getPltVA() + a - p;
735   case R_PLT_GOTPLT:
736     return sym.getPltVA() + a - in.gotPlt->getVA();
737   case R_PPC32_PLTREL:
738     // R_PPC_PLTREL24 uses the addend (usually 0 or 0x8000) to indicate r30
739     // stores _GLOBAL_OFFSET_TABLE_ or .got2+0x8000. The addend is ignored for
740     // target VA computation.
741     return sym.getPltVA() - p;
742   case R_PPC64_CALL: {
743     uint64_t symVA = sym.getVA(a);
744     // If we have an undefined weak symbol, we might get here with a symbol
745     // address of zero. That could overflow, but the code must be unreachable,
746     // so don't bother doing anything at all.
747     if (!symVA)
748       return 0;
749 
750     // PPC64 V2 ABI describes two entry points to a function. The global entry
751     // point is used for calls where the caller and callee (may) have different
752     // TOC base pointers and r2 needs to be modified to hold the TOC base for
753     // the callee. For local calls the caller and callee share the same
754     // TOC base and so the TOC pointer initialization code should be skipped by
755     // branching to the local entry point.
756     return symVA - p + getPPC64GlobalEntryToLocalEntryOffset(sym.stOther);
757   }
758   case R_PPC64_TOCBASE:
759     return getPPC64TocBase() + a;
760   case R_RELAX_GOT_PC:
761   case R_PPC64_RELAX_GOT_PC:
762     return sym.getVA(a) - p;
763   case R_RELAX_TLS_GD_TO_LE:
764   case R_RELAX_TLS_IE_TO_LE:
765   case R_RELAX_TLS_LD_TO_LE:
766   case R_TPREL:
767     // It is not very clear what to return if the symbol is undefined. With
768     // --noinhibit-exec, even a non-weak undefined reference may reach here.
769     // Just return A, which matches R_ABS, and the behavior of some dynamic
770     // loaders.
771     if (sym.isUndefined())
772       return a;
773     return getTlsTpOffset(sym) + a;
774   case R_RELAX_TLS_GD_TO_LE_NEG:
775   case R_TPREL_NEG:
776     if (sym.isUndefined())
777       return a;
778     return -getTlsTpOffset(sym) + a;
779   case R_SIZE:
780     return sym.getSize() + a;
781   case R_TLSDESC:
782     return in.got->getTlsDescAddr(sym) + a;
783   case R_TLSDESC_PC:
784     return in.got->getTlsDescAddr(sym) + a - p;
785   case R_TLSDESC_GOTPLT:
786     return in.got->getTlsDescAddr(sym) + a - in.gotPlt->getVA();
787   case R_AARCH64_TLSDESC_PAGE:
788     return getAArch64Page(in.got->getTlsDescAddr(sym) + a) - getAArch64Page(p);
789   case R_TLSGD_GOT:
790     return in.got->getGlobalDynOffset(sym) + a;
791   case R_TLSGD_GOTPLT:
792     return in.got->getGlobalDynAddr(sym) + a - in.gotPlt->getVA();
793   case R_TLSGD_PC:
794     return in.got->getGlobalDynAddr(sym) + a - p;
795   case R_TLSLD_GOTPLT:
796     return in.got->getVA() + in.got->getTlsIndexOff() + a - in.gotPlt->getVA();
797   case R_TLSLD_GOT:
798     return in.got->getTlsIndexOff() + a;
799   case R_TLSLD_PC:
800     return in.got->getTlsIndexVA() + a - p;
801   default:
802     llvm_unreachable("invalid expression");
803   }
804 }
805 
806 // This function applies relocations to sections without SHF_ALLOC bit.
807 // Such sections are never mapped to memory at runtime. Debug sections are
808 // an example. Relocations in non-alloc sections are much easier to
809 // handle than in allocated sections because it will never need complex
810 // treatment such as GOT or PLT (because at runtime no one refers them).
811 // So, we handle relocations for non-alloc sections directly in this
812 // function as a performance optimization.
813 template <class ELFT, class RelTy>
814 void InputSection::relocateNonAlloc(uint8_t *buf, ArrayRef<RelTy> rels) {
815   const unsigned bits = sizeof(typename ELFT::uint) * 8;
816   const TargetInfo &target = *elf::target;
817   const bool isDebug = isDebugSection(*this);
818   const bool isDebugLocOrRanges =
819       isDebug && (name == ".debug_loc" || name == ".debug_ranges");
820   const bool isDebugLine = isDebug && name == ".debug_line";
821   Optional<uint64_t> tombstone;
822   for (const auto &patAndValue : llvm::reverse(config->deadRelocInNonAlloc))
823     if (patAndValue.first.match(this->name)) {
824       tombstone = patAndValue.second;
825       break;
826     }
827 
828   for (const RelTy &rel : rels) {
829     RelType type = rel.getType(config->isMips64EL);
830 
831     // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations
832     // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed
833     // in 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we
834     // need to keep this bug-compatible code for a while.
835     if (config->emachine == EM_386 && type == R_386_GOTPC)
836       continue;
837 
838     uint64_t offset = rel.r_offset;
839     uint8_t *bufLoc = buf + offset;
840     int64_t addend = getAddend<ELFT>(rel);
841     if (!RelTy::IsRela)
842       addend += target.getImplicitAddend(bufLoc, type);
843 
844     Symbol &sym = getFile<ELFT>()->getRelocTargetSym(rel);
845     RelExpr expr = target.getRelExpr(type, sym, bufLoc);
846     if (expr == R_NONE)
847       continue;
848 
849     if (tombstone ||
850         (isDebug && (type == target.symbolicRel || expr == R_DTPREL))) {
851       // Resolve relocations in .debug_* referencing (discarded symbols or ICF
852       // folded section symbols) to a tombstone value. Resolving to addend is
853       // unsatisfactory because the result address range may collide with a
854       // valid range of low address, or leave multiple CUs claiming ownership of
855       // the same range of code, which may confuse consumers.
856       //
857       // To address the problems, we use -1 as a tombstone value for most
858       // .debug_* sections. We have to ignore the addend because we don't want
859       // to resolve an address attribute (which may have a non-zero addend) to
860       // -1+addend (wrap around to a low address).
861       //
862       // R_DTPREL type relocations represent an offset into the dynamic thread
863       // vector. The computed value is st_value plus a non-negative offset.
864       // Negative values are invalid, so -1 can be used as the tombstone value.
865       //
866       // If the referenced symbol is discarded (made Undefined), or the
867       // section defining the referenced symbol is garbage collected,
868       // sym.getOutputSection() is nullptr. `ds->folded` catches the ICF folded
869       // case. However, resolving a relocation in .debug_line to -1 would stop
870       // debugger users from setting breakpoints on the folded-in function, so
871       // exclude .debug_line.
872       //
873       // For pre-DWARF-v5 .debug_loc and .debug_ranges, -1 is a reserved value
874       // (base address selection entry), use 1 (which is used by GNU ld for
875       // .debug_ranges).
876       //
877       // TODO To reduce disruption, we use 0 instead of -1 as the tombstone
878       // value. Enable -1 in a future release.
879       auto *ds = dyn_cast<Defined>(&sym);
880       if (!sym.getOutputSection() || (ds && ds->folded && !isDebugLine)) {
881         // If -z dead-reloc-in-nonalloc= is specified, respect it.
882         const uint64_t value = tombstone ? SignExtend64<bits>(*tombstone)
883                                          : (isDebugLocOrRanges ? 1 : 0);
884         target.relocateNoSym(bufLoc, type, value);
885         continue;
886       }
887     }
888 
889     // For a relocatable link, only tombstone values are applied.
890     if (config->relocatable)
891       continue;
892 
893     if (expr == R_SIZE) {
894       target.relocateNoSym(bufLoc, type,
895                            SignExtend64<bits>(sym.getSize() + addend));
896       continue;
897     }
898 
899     // R_ABS/R_DTPREL and some other relocations can be used from non-SHF_ALLOC
900     // sections.
901     if (expr == R_ABS || expr == R_DTPREL || expr == R_GOTPLTREL ||
902         expr == R_RISCV_ADD) {
903       target.relocateNoSym(bufLoc, type, SignExtend64<bits>(sym.getVA(addend)));
904       continue;
905     }
906 
907     std::string msg = getLocation(offset) + ": has non-ABS relocation " +
908                       toString(type) + " against symbol '" + toString(sym) +
909                       "'";
910     if (expr != R_PC && expr != R_ARM_PCA) {
911       error(msg);
912       return;
913     }
914 
915     // If the control reaches here, we found a PC-relative relocation in a
916     // non-ALLOC section. Since non-ALLOC section is not loaded into memory
917     // at runtime, the notion of PC-relative doesn't make sense here. So,
918     // this is a usage error. However, GNU linkers historically accept such
919     // relocations without any errors and relocate them as if they were at
920     // address 0. For bug-compatibilty, we accept them with warnings. We
921     // know Steel Bank Common Lisp as of 2018 have this bug.
922     warn(msg);
923     target.relocateNoSym(
924         bufLoc, type,
925         SignExtend64<bits>(sym.getVA(addend - offset - outSecOff)));
926   }
927 }
928 
929 // This is used when '-r' is given.
930 // For REL targets, InputSection::copyRelocations() may store artificial
931 // relocations aimed to update addends. They are handled in relocateAlloc()
932 // for allocatable sections, and this function does the same for
933 // non-allocatable sections, such as sections with debug information.
934 static void relocateNonAllocForRelocatable(InputSection *sec, uint8_t *buf) {
935   const unsigned bits = config->is64 ? 64 : 32;
936 
937   for (const Relocation &rel : sec->relocations) {
938     // InputSection::copyRelocations() adds only R_ABS relocations.
939     assert(rel.expr == R_ABS);
940     uint8_t *bufLoc = buf + rel.offset;
941     uint64_t targetVA = SignExtend64(rel.sym->getVA(rel.addend), bits);
942     target->relocate(bufLoc, rel, targetVA);
943   }
944 }
945 
946 template <class ELFT>
947 void InputSectionBase::relocate(uint8_t *buf, uint8_t *bufEnd) {
948   if ((flags & SHF_EXECINSTR) && LLVM_UNLIKELY(getFile<ELFT>()->splitStack))
949     adjustSplitStackFunctionPrologues<ELFT>(buf, bufEnd);
950 
951   if (flags & SHF_ALLOC) {
952     relocateAlloc(buf, bufEnd);
953     return;
954   }
955 
956   auto *sec = cast<InputSection>(this);
957   if (config->relocatable)
958     relocateNonAllocForRelocatable(sec, buf);
959   // For a relocatable link, also call relocateNonAlloc() to rewrite applicable
960   // locations with tombstone values.
961   const RelsOrRelas<ELFT> rels = sec->template relsOrRelas<ELFT>();
962   if (rels.areRelocsRel())
963     sec->relocateNonAlloc<ELFT>(buf, rels.rels);
964   else
965     sec->relocateNonAlloc<ELFT>(buf, rels.relas);
966 }
967 
968 void InputSectionBase::relocateAlloc(uint8_t *buf, uint8_t *bufEnd) {
969   assert(flags & SHF_ALLOC);
970   const unsigned bits = config->wordsize * 8;
971   const TargetInfo &target = *elf::target;
972   uint64_t lastPPCRelaxedRelocOff = UINT64_C(-1);
973   AArch64Relaxer aarch64relaxer(relocations);
974   for (size_t i = 0, size = relocations.size(); i != size; ++i) {
975     const Relocation &rel = relocations[i];
976     if (rel.expr == R_NONE)
977       continue;
978     uint64_t offset = rel.offset;
979     uint8_t *bufLoc = buf + offset;
980 
981     uint64_t secAddr = getOutputSection()->addr;
982     if (auto *sec = dyn_cast<InputSection>(this))
983       secAddr += sec->outSecOff;
984     const uint64_t addrLoc = secAddr + offset;
985     const uint64_t targetVA =
986         SignExtend64(getRelocTargetVA(file, rel.type, rel.addend, addrLoc,
987                                       *rel.sym, rel.expr),
988                      bits);
989     switch (rel.expr) {
990     case R_RELAX_GOT_PC:
991     case R_RELAX_GOT_PC_NOPIC:
992       target.relaxGot(bufLoc, rel, targetVA);
993       break;
994     case R_AARCH64_GOT_PAGE_PC:
995       if (i + 1 < size && aarch64relaxer.tryRelaxAdrpLdr(
996                               rel, relocations[i + 1], secAddr, buf)) {
997         ++i;
998         continue;
999       }
1000       target.relocate(bufLoc, rel, targetVA);
1001       break;
1002     case R_AARCH64_PAGE_PC:
1003       if (i + 1 < size && aarch64relaxer.tryRelaxAdrpAdd(
1004                               rel, relocations[i + 1], secAddr, buf)) {
1005         ++i;
1006         continue;
1007       }
1008       target.relocate(bufLoc, rel, targetVA);
1009       break;
1010     case R_PPC64_RELAX_GOT_PC: {
1011       // The R_PPC64_PCREL_OPT relocation must appear immediately after
1012       // R_PPC64_GOT_PCREL34 in the relocations table at the same offset.
1013       // We can only relax R_PPC64_PCREL_OPT if we have also relaxed
1014       // the associated R_PPC64_GOT_PCREL34 since only the latter has an
1015       // associated symbol. So save the offset when relaxing R_PPC64_GOT_PCREL34
1016       // and only relax the other if the saved offset matches.
1017       if (rel.type == R_PPC64_GOT_PCREL34)
1018         lastPPCRelaxedRelocOff = offset;
1019       if (rel.type == R_PPC64_PCREL_OPT && offset != lastPPCRelaxedRelocOff)
1020         break;
1021       target.relaxGot(bufLoc, rel, targetVA);
1022       break;
1023     }
1024     case R_PPC64_RELAX_TOC:
1025       // rel.sym refers to the STT_SECTION symbol associated to the .toc input
1026       // section. If an R_PPC64_TOC16_LO (.toc + addend) references the TOC
1027       // entry, there may be R_PPC64_TOC16_HA not paired with
1028       // R_PPC64_TOC16_LO_DS. Don't relax. This loses some relaxation
1029       // opportunities but is safe.
1030       if (ppc64noTocRelax.count({rel.sym, rel.addend}) ||
1031           !tryRelaxPPC64TocIndirection(rel, bufLoc))
1032         target.relocate(bufLoc, rel, targetVA);
1033       break;
1034     case R_RELAX_TLS_IE_TO_LE:
1035       target.relaxTlsIeToLe(bufLoc, rel, targetVA);
1036       break;
1037     case R_RELAX_TLS_LD_TO_LE:
1038     case R_RELAX_TLS_LD_TO_LE_ABS:
1039       target.relaxTlsLdToLe(bufLoc, rel, targetVA);
1040       break;
1041     case R_RELAX_TLS_GD_TO_LE:
1042     case R_RELAX_TLS_GD_TO_LE_NEG:
1043       target.relaxTlsGdToLe(bufLoc, rel, targetVA);
1044       break;
1045     case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
1046     case R_RELAX_TLS_GD_TO_IE:
1047     case R_RELAX_TLS_GD_TO_IE_ABS:
1048     case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
1049     case R_RELAX_TLS_GD_TO_IE_GOTPLT:
1050       target.relaxTlsGdToIe(bufLoc, rel, targetVA);
1051       break;
1052     case R_PPC64_CALL:
1053       // If this is a call to __tls_get_addr, it may be part of a TLS
1054       // sequence that has been relaxed and turned into a nop. In this
1055       // case, we don't want to handle it as a call.
1056       if (read32(bufLoc) == 0x60000000) // nop
1057         break;
1058 
1059       // Patch a nop (0x60000000) to a ld.
1060       if (rel.sym->needsTocRestore) {
1061         // gcc/gfortran 5.4, 6.3 and earlier versions do not add nop for
1062         // recursive calls even if the function is preemptible. This is not
1063         // wrong in the common case where the function is not preempted at
1064         // runtime. Just ignore.
1065         if ((bufLoc + 8 > bufEnd || read32(bufLoc + 4) != 0x60000000) &&
1066             rel.sym->file != file) {
1067           // Use substr(6) to remove the "__plt_" prefix.
1068           errorOrWarn(getErrorLocation(bufLoc) + "call to " +
1069                       lld::toString(*rel.sym).substr(6) +
1070                       " lacks nop, can't restore toc");
1071           break;
1072         }
1073         write32(bufLoc + 4, 0xe8410018); // ld %r2, 24(%r1)
1074       }
1075       target.relocate(bufLoc, rel, targetVA);
1076       break;
1077     default:
1078       target.relocate(bufLoc, rel, targetVA);
1079       break;
1080     }
1081   }
1082 
1083   // Apply jumpInstrMods.  jumpInstrMods are created when the opcode of
1084   // a jmp insn must be modified to shrink the jmp insn or to flip the jmp
1085   // insn.  This is primarily used to relax and optimize jumps created with
1086   // basic block sections.
1087   if (jumpInstrMod) {
1088     target.applyJumpInstrMod(buf + jumpInstrMod->offset, jumpInstrMod->original,
1089                              jumpInstrMod->size);
1090   }
1091 }
1092 
1093 // For each function-defining prologue, find any calls to __morestack,
1094 // and replace them with calls to __morestack_non_split.
1095 static void switchMorestackCallsToMorestackNonSplit(
1096     DenseSet<Defined *> &prologues,
1097     SmallVector<Relocation *, 0> &morestackCalls) {
1098 
1099   // If the target adjusted a function's prologue, all calls to
1100   // __morestack inside that function should be switched to
1101   // __morestack_non_split.
1102   Symbol *moreStackNonSplit = symtab->find("__morestack_non_split");
1103   if (!moreStackNonSplit) {
1104     error("mixing split-stack objects requires a definition of "
1105           "__morestack_non_split");
1106     return;
1107   }
1108 
1109   // Sort both collections to compare addresses efficiently.
1110   llvm::sort(morestackCalls, [](const Relocation *l, const Relocation *r) {
1111     return l->offset < r->offset;
1112   });
1113   std::vector<Defined *> functions(prologues.begin(), prologues.end());
1114   llvm::sort(functions, [](const Defined *l, const Defined *r) {
1115     return l->value < r->value;
1116   });
1117 
1118   auto it = morestackCalls.begin();
1119   for (Defined *f : functions) {
1120     // Find the first call to __morestack within the function.
1121     while (it != morestackCalls.end() && (*it)->offset < f->value)
1122       ++it;
1123     // Adjust all calls inside the function.
1124     while (it != morestackCalls.end() && (*it)->offset < f->value + f->size) {
1125       (*it)->sym = moreStackNonSplit;
1126       ++it;
1127     }
1128   }
1129 }
1130 
1131 static bool enclosingPrologueAttempted(uint64_t offset,
1132                                        const DenseSet<Defined *> &prologues) {
1133   for (Defined *f : prologues)
1134     if (f->value <= offset && offset < f->value + f->size)
1135       return true;
1136   return false;
1137 }
1138 
1139 // If a function compiled for split stack calls a function not
1140 // compiled for split stack, then the caller needs its prologue
1141 // adjusted to ensure that the called function will have enough stack
1142 // available. Find those functions, and adjust their prologues.
1143 template <class ELFT>
1144 void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *buf,
1145                                                          uint8_t *end) {
1146   DenseSet<Defined *> prologues;
1147   SmallVector<Relocation *, 0> morestackCalls;
1148 
1149   for (Relocation &rel : relocations) {
1150     // Ignore calls into the split-stack api.
1151     if (rel.sym->getName().startswith("__morestack")) {
1152       if (rel.sym->getName().equals("__morestack"))
1153         morestackCalls.push_back(&rel);
1154       continue;
1155     }
1156 
1157     // A relocation to non-function isn't relevant. Sometimes
1158     // __morestack is not marked as a function, so this check comes
1159     // after the name check.
1160     if (rel.sym->type != STT_FUNC)
1161       continue;
1162 
1163     // If the callee's-file was compiled with split stack, nothing to do.  In
1164     // this context, a "Defined" symbol is one "defined by the binary currently
1165     // being produced". So an "undefined" symbol might be provided by a shared
1166     // library. It is not possible to tell how such symbols were compiled, so be
1167     // conservative.
1168     if (Defined *d = dyn_cast<Defined>(rel.sym))
1169       if (InputSection *isec = cast_or_null<InputSection>(d->section))
1170         if (!isec || !isec->getFile<ELFT>() || isec->getFile<ELFT>()->splitStack)
1171           continue;
1172 
1173     if (enclosingPrologueAttempted(rel.offset, prologues))
1174       continue;
1175 
1176     if (Defined *f = getEnclosingFunction(rel.offset)) {
1177       prologues.insert(f);
1178       if (target->adjustPrologueForCrossSplitStack(buf + f->value, end,
1179                                                    f->stOther))
1180         continue;
1181       if (!getFile<ELFT>()->someNoSplitStack)
1182         error(lld::toString(this) + ": " + f->getName() +
1183               " (with -fsplit-stack) calls " + rel.sym->getName() +
1184               " (without -fsplit-stack), but couldn't adjust its prologue");
1185     }
1186   }
1187 
1188   if (target->needsMoreStackNonSplit)
1189     switchMorestackCallsToMorestackNonSplit(prologues, morestackCalls);
1190 }
1191 
1192 template <class ELFT> void InputSection::writeTo(uint8_t *buf) {
1193   if (LLVM_UNLIKELY(type == SHT_NOBITS))
1194     return;
1195   // If -r or --emit-relocs is given, then an InputSection
1196   // may be a relocation section.
1197   if (LLVM_UNLIKELY(type == SHT_RELA)) {
1198     copyRelocations<ELFT>(buf, getDataAs<typename ELFT::Rela>());
1199     return;
1200   }
1201   if (LLVM_UNLIKELY(type == SHT_REL)) {
1202     copyRelocations<ELFT>(buf, getDataAs<typename ELFT::Rel>());
1203     return;
1204   }
1205 
1206   // If -r is given, we may have a SHT_GROUP section.
1207   if (LLVM_UNLIKELY(type == SHT_GROUP)) {
1208     copyShtGroup<ELFT>(buf);
1209     return;
1210   }
1211 
1212   // If this is a compressed section, uncompress section contents directly
1213   // to the buffer.
1214   if (uncompressedSize >= 0) {
1215     size_t size = uncompressedSize;
1216     if (Error e = zlib::uncompress(toStringRef(rawData), (char *)buf, size))
1217       fatal(toString(this) +
1218             ": uncompress failed: " + llvm::toString(std::move(e)));
1219     uint8_t *bufEnd = buf + size;
1220     relocate<ELFT>(buf, bufEnd);
1221     return;
1222   }
1223 
1224   // Copy section contents from source object file to output file
1225   // and then apply relocations.
1226   memcpy(buf, rawData.data(), rawData.size());
1227   relocate<ELFT>(buf, buf + rawData.size());
1228 }
1229 
1230 void InputSection::replace(InputSection *other) {
1231   alignment = std::max(alignment, other->alignment);
1232 
1233   // When a section is replaced with another section that was allocated to
1234   // another partition, the replacement section (and its associated sections)
1235   // need to be placed in the main partition so that both partitions will be
1236   // able to access it.
1237   if (partition != other->partition) {
1238     partition = 1;
1239     for (InputSection *isec : dependentSections)
1240       isec->partition = 1;
1241   }
1242 
1243   other->repl = repl;
1244   other->markDead();
1245 }
1246 
1247 template <class ELFT>
1248 EhInputSection::EhInputSection(ObjFile<ELFT> &f,
1249                                const typename ELFT::Shdr &header,
1250                                StringRef name)
1251     : InputSectionBase(f, header, name, InputSectionBase::EHFrame) {}
1252 
1253 SyntheticSection *EhInputSection::getParent() const {
1254   return cast_or_null<SyntheticSection>(parent);
1255 }
1256 
1257 // Returns the index of the first relocation that points to a region between
1258 // Begin and Begin+Size.
1259 template <class IntTy, class RelTy>
1260 static unsigned getReloc(IntTy begin, IntTy size, const ArrayRef<RelTy> &rels,
1261                          unsigned &relocI) {
1262   // Start search from RelocI for fast access. That works because the
1263   // relocations are sorted in .eh_frame.
1264   for (unsigned n = rels.size(); relocI < n; ++relocI) {
1265     const RelTy &rel = rels[relocI];
1266     if (rel.r_offset < begin)
1267       continue;
1268 
1269     if (rel.r_offset < begin + size)
1270       return relocI;
1271     return -1;
1272   }
1273   return -1;
1274 }
1275 
1276 // .eh_frame is a sequence of CIE or FDE records.
1277 // This function splits an input section into records and returns them.
1278 template <class ELFT> void EhInputSection::split() {
1279   const RelsOrRelas<ELFT> rels = relsOrRelas<ELFT>();
1280   // getReloc expects the relocations to be sorted by r_offset. See the comment
1281   // in scanRelocs.
1282   if (rels.areRelocsRel()) {
1283     SmallVector<typename ELFT::Rel, 0> storage;
1284     split<ELFT>(sortRels(rels.rels, storage));
1285   } else {
1286     SmallVector<typename ELFT::Rela, 0> storage;
1287     split<ELFT>(sortRels(rels.relas, storage));
1288   }
1289 }
1290 
1291 template <class ELFT, class RelTy>
1292 void EhInputSection::split(ArrayRef<RelTy> rels) {
1293   ArrayRef<uint8_t> d = rawData;
1294   const char *msg = nullptr;
1295   unsigned relI = 0;
1296   while (!d.empty()) {
1297     if (d.size() < 4) {
1298       msg = "CIE/FDE too small";
1299       break;
1300     }
1301     uint64_t size = endian::read32<ELFT::TargetEndianness>(d.data());
1302     // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead,
1303     // but we do not support that format yet.
1304     if (size == UINT32_MAX) {
1305       msg = "CIE/FDE too large";
1306       break;
1307     }
1308     size += 4;
1309     if (size > d.size()) {
1310       msg = "CIE/FDE ends past the end of the section";
1311       break;
1312     }
1313 
1314     uint64_t off = d.data() - rawData.data();
1315     pieces.emplace_back(off, this, size, getReloc(off, size, rels, relI));
1316     d = d.slice(size);
1317   }
1318   if (msg)
1319     errorOrWarn("corrupted .eh_frame: " + Twine(msg) + "\n>>> defined in " +
1320                 getObjMsg(d.data() - rawData.data()));
1321 }
1322 
1323 // Return the offset in an output section for a given input offset.
1324 uint64_t EhInputSection::getParentOffset(uint64_t offset) const {
1325   const EhSectionPiece &piece = partition_point(
1326       pieces, [=](EhSectionPiece p) { return p.inputOff <= offset; })[-1];
1327   if (piece.outputOff == -1) // invalid piece
1328     return offset - piece.inputOff;
1329   return piece.outputOff + (offset - piece.inputOff);
1330 }
1331 
1332 static size_t findNull(StringRef s, size_t entSize) {
1333   for (unsigned i = 0, n = s.size(); i != n; i += entSize) {
1334     const char *b = s.begin() + i;
1335     if (std::all_of(b, b + entSize, [](char c) { return c == 0; }))
1336       return i;
1337   }
1338   llvm_unreachable("");
1339 }
1340 
1341 SyntheticSection *MergeInputSection::getParent() const {
1342   return cast_or_null<SyntheticSection>(parent);
1343 }
1344 
1345 // Split SHF_STRINGS section. Such section is a sequence of
1346 // null-terminated strings.
1347 void MergeInputSection::splitStrings(StringRef s, size_t entSize) {
1348   const bool live = !(flags & SHF_ALLOC) || !config->gcSections;
1349   const char *p = s.data(), *end = s.data() + s.size();
1350   if (!std::all_of(end - entSize, end, [](char c) { return c == 0; }))
1351     fatal(toString(this) + ": string is not null terminated");
1352   if (entSize == 1) {
1353     // Optimize the common case.
1354     do {
1355       size_t size = strlen(p);
1356       pieces.emplace_back(p - s.begin(), xxHash64(StringRef(p, size)), live);
1357       p += size + 1;
1358     } while (p != end);
1359   } else {
1360     do {
1361       size_t size = findNull(StringRef(p, end - p), entSize);
1362       pieces.emplace_back(p - s.begin(), xxHash64(StringRef(p, size)), live);
1363       p += size + entSize;
1364     } while (p != end);
1365   }
1366 }
1367 
1368 // Split non-SHF_STRINGS section. Such section is a sequence of
1369 // fixed size records.
1370 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> data,
1371                                         size_t entSize) {
1372   size_t size = data.size();
1373   assert((size % entSize) == 0);
1374   const bool live = !(flags & SHF_ALLOC) || !config->gcSections;
1375 
1376   pieces.resize_for_overwrite(size / entSize);
1377   for (size_t i = 0, j = 0; i != size; i += entSize, j++)
1378     pieces[j] = {i, (uint32_t)xxHash64(data.slice(i, entSize)), live};
1379 }
1380 
1381 template <class ELFT>
1382 MergeInputSection::MergeInputSection(ObjFile<ELFT> &f,
1383                                      const typename ELFT::Shdr &header,
1384                                      StringRef name)
1385     : InputSectionBase(f, header, name, InputSectionBase::Merge) {}
1386 
1387 MergeInputSection::MergeInputSection(uint64_t flags, uint32_t type,
1388                                      uint64_t entsize, ArrayRef<uint8_t> data,
1389                                      StringRef name)
1390     : InputSectionBase(nullptr, flags, type, entsize, /*Link*/ 0, /*Info*/ 0,
1391                        /*Alignment*/ entsize, data, name, SectionBase::Merge) {}
1392 
1393 // This function is called after we obtain a complete list of input sections
1394 // that need to be linked. This is responsible to split section contents
1395 // into small chunks for further processing.
1396 //
1397 // Note that this function is called from parallelForEach. This must be
1398 // thread-safe (i.e. no memory allocation from the pools).
1399 void MergeInputSection::splitIntoPieces() {
1400   assert(pieces.empty());
1401 
1402   if (flags & SHF_STRINGS)
1403     splitStrings(toStringRef(data()), entsize);
1404   else
1405     splitNonStrings(data(), entsize);
1406 }
1407 
1408 SectionPiece &MergeInputSection::getSectionPiece(uint64_t offset) {
1409   if (rawData.size() <= offset)
1410     fatal(toString(this) + ": offset is outside the section");
1411   return partition_point(
1412       pieces, [=](SectionPiece p) { return p.inputOff <= offset; })[-1];
1413 }
1414 
1415 // Return the offset in an output section for a given input offset.
1416 uint64_t MergeInputSection::getParentOffset(uint64_t offset) const {
1417   const SectionPiece &piece = getSectionPiece(offset);
1418   return piece.outputOff + (offset - piece.inputOff);
1419 }
1420 
1421 template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
1422                                     StringRef);
1423 template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
1424                                     StringRef);
1425 template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
1426                                     StringRef);
1427 template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
1428                                     StringRef);
1429 
1430 template void InputSection::writeTo<ELF32LE>(uint8_t *);
1431 template void InputSection::writeTo<ELF32BE>(uint8_t *);
1432 template void InputSection::writeTo<ELF64LE>(uint8_t *);
1433 template void InputSection::writeTo<ELF64BE>(uint8_t *);
1434 
1435 template RelsOrRelas<ELF32LE> InputSectionBase::relsOrRelas<ELF32LE>() const;
1436 template RelsOrRelas<ELF32BE> InputSectionBase::relsOrRelas<ELF32BE>() const;
1437 template RelsOrRelas<ELF64LE> InputSectionBase::relsOrRelas<ELF64LE>() const;
1438 template RelsOrRelas<ELF64BE> InputSectionBase::relsOrRelas<ELF64BE>() const;
1439 
1440 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
1441                                               const ELF32LE::Shdr &, StringRef);
1442 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
1443                                               const ELF32BE::Shdr &, StringRef);
1444 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
1445                                               const ELF64LE::Shdr &, StringRef);
1446 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
1447                                               const ELF64BE::Shdr &, StringRef);
1448 
1449 template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
1450                                         const ELF32LE::Shdr &, StringRef);
1451 template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
1452                                         const ELF32BE::Shdr &, StringRef);
1453 template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
1454                                         const ELF64LE::Shdr &, StringRef);
1455 template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
1456                                         const ELF64BE::Shdr &, StringRef);
1457 
1458 template void EhInputSection::split<ELF32LE>();
1459 template void EhInputSection::split<ELF32BE>();
1460 template void EhInputSection::split<ELF64LE>();
1461 template void EhInputSection::split<ELF64BE>();
1462