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