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