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