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