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