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