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