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