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