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