1 //===- InputSection.cpp ---------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "InputSection.h"
11 #include "Config.h"
12 #include "EhFrame.h"
13 #include "Error.h"
14 #include "InputFiles.h"
15 #include "LinkerScript.h"
16 #include "Memory.h"
17 #include "OutputSections.h"
18 #include "Relocations.h"
19 #include "SyntheticSections.h"
20 #include "Target.h"
21 #include "Thunks.h"
22 #include "llvm/Object/Decompressor.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Compression.h"
25 #include "llvm/Support/Endian.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/Threading.h"
28 #include <mutex>
29 
30 using namespace llvm;
31 using namespace llvm::ELF;
32 using namespace llvm::object;
33 using namespace llvm::support;
34 using namespace llvm::support::endian;
35 using namespace llvm::sys;
36 
37 using namespace lld;
38 using namespace lld::elf;
39 
40 std::vector<InputSectionBase *> elf::InputSections;
41 
42 // Returns a string to construct an error message.
43 std::string lld::toString(const InputSectionBase *Sec) {
44   return (toString(Sec->File) + ":(" + Sec->Name + ")").str();
45 }
46 
47 template <class ELFT>
48 static ArrayRef<uint8_t> getSectionContents(elf::ObjectFile<ELFT> *File,
49                                             const typename ELFT::Shdr *Hdr) {
50   if (!File || Hdr->sh_type == SHT_NOBITS)
51     return makeArrayRef<uint8_t>(nullptr, Hdr->sh_size);
52   return check(File->getObj().getSectionContents(Hdr));
53 }
54 
55 InputSectionBase::InputSectionBase(InputFile *File, uint64_t Flags,
56                                    uint32_t Type, uint64_t Entsize,
57                                    uint32_t Link, uint32_t Info,
58                                    uint32_t Alignment, ArrayRef<uint8_t> Data,
59                                    StringRef Name, Kind SectionKind)
60     : SectionBase(SectionKind, Name, Flags, Entsize, Alignment, Type, Info,
61                   Link),
62       File(File), Data(Data), Repl(this) {
63   Live = !Config->GcSections || !(Flags & SHF_ALLOC);
64   Assigned = false;
65   NumRelocations = 0;
66   AreRelocsRela = false;
67 
68   // The ELF spec states that a value of 0 means the section has
69   // no alignment constraits.
70   uint32_t V = std::max<uint64_t>(Alignment, 1);
71   if (!isPowerOf2_64(V))
72     fatal(toString(File) + ": section sh_addralign is not a power of 2");
73   this->Alignment = V;
74 }
75 
76 // Drop SHF_GROUP bit unless we are producing a re-linkable object file.
77 // SHF_GROUP is a marker that a section belongs to some comdat group.
78 // That flag doesn't make sense in an executable.
79 static uint64_t getFlags(uint64_t Flags) {
80   Flags &= ~(uint64_t)SHF_INFO_LINK;
81   if (!Config->Relocatable)
82     Flags &= ~(uint64_t)SHF_GROUP;
83   return Flags;
84 }
85 
86 // GNU assembler 2.24 and LLVM 4.0.0's MC (the newest release as of
87 // March 2017) fail to infer section types for sections starting with
88 // ".init_array." or ".fini_array.". They set SHT_PROGBITS instead of
89 // SHF_INIT_ARRAY. As a result, the following assembler directive
90 // creates ".init_array.100" with SHT_PROGBITS, for example.
91 //
92 //   .section .init_array.100, "aw"
93 //
94 // This function forces SHT_{INIT,FINI}_ARRAY so that we can handle
95 // incorrect inputs as if they were correct from the beginning.
96 static uint64_t getType(uint64_t Type, StringRef Name) {
97   if (Type == SHT_PROGBITS && Name.startswith(".init_array."))
98     return SHT_INIT_ARRAY;
99   if (Type == SHT_PROGBITS && Name.startswith(".fini_array."))
100     return SHT_FINI_ARRAY;
101   return Type;
102 }
103 
104 template <class ELFT>
105 InputSectionBase::InputSectionBase(elf::ObjectFile<ELFT> *File,
106                                    const typename ELFT::Shdr *Hdr,
107                                    StringRef Name, Kind SectionKind)
108     : InputSectionBase(File, getFlags(Hdr->sh_flags),
109                        getType(Hdr->sh_type, Name), Hdr->sh_entsize,
110                        Hdr->sh_link, Hdr->sh_info, Hdr->sh_addralign,
111                        getSectionContents(File, Hdr), Name, SectionKind) {
112   // We reject object files having insanely large alignments even though
113   // they are allowed by the spec. I think 4GB is a reasonable limitation.
114   // We might want to relax this in the future.
115   if (Hdr->sh_addralign > UINT32_MAX)
116     fatal(toString(File) + ": section sh_addralign is too large");
117 }
118 
119 size_t InputSectionBase::getSize() const {
120   if (auto *S = dyn_cast<SyntheticSection>(this))
121     return S->getSize();
122 
123   return Data.size();
124 }
125 
126 uint64_t InputSectionBase::getOffsetInFile() const {
127   const uint8_t *FileStart = (const uint8_t *)File->MB.getBufferStart();
128   const uint8_t *SecStart = Data.begin();
129   return SecStart - FileStart;
130 }
131 
132 uint64_t SectionBase::getOffset(uint64_t Offset) const {
133   switch (kind()) {
134   case Output: {
135     auto *OS = cast<OutputSection>(this);
136     // For output sections we treat offset -1 as the end of the section.
137     return Offset == uint64_t(-1) ? OS->Size : Offset;
138   }
139   case Regular:
140     return cast<InputSection>(this)->OutSecOff + Offset;
141   case Synthetic: {
142     auto *IS = cast<InputSection>(this);
143     // For synthetic sections we treat offset -1 as the end of the section.
144     return IS->OutSecOff + (Offset == uint64_t(-1) ? IS->getSize() : Offset);
145   }
146   case EHFrame:
147     // The file crtbeginT.o has relocations pointing to the start of an empty
148     // .eh_frame that is known to be the first in the link. It does that to
149     // identify the start of the output .eh_frame.
150     return Offset;
151   case Merge:
152     const MergeInputSection *MS = cast<MergeInputSection>(this);
153     if (InputSection *IS = MS->getParent())
154       return IS->OutSecOff + MS->getOffset(Offset);
155     return MS->getOffset(Offset);
156   }
157   llvm_unreachable("invalid section kind");
158 }
159 
160 OutputSection *SectionBase::getOutputSection() {
161   InputSection *Sec;
162   if (auto *IS = dyn_cast<InputSection>(this))
163     Sec = IS;
164   else if (auto *MS = dyn_cast<MergeInputSection>(this))
165     Sec = MS->getParent();
166   else if (auto *EH = dyn_cast<EhInputSection>(this))
167     Sec = EH->getParent();
168   else
169     return cast<OutputSection>(this);
170   return Sec ? Sec->getParent() : nullptr;
171 }
172 
173 // Uncompress section contents. Note that this function is called
174 // from parallel_for_each, so it must be thread-safe.
175 void InputSectionBase::uncompress() {
176   Decompressor Dec = check(Decompressor::create(Name, toStringRef(Data),
177                                                 Config->IsLE, Config->Is64));
178 
179   size_t Size = Dec.getDecompressedSize();
180   char *OutputBuf;
181   {
182     static std::mutex Mu;
183     std::lock_guard<std::mutex> Lock(Mu);
184     OutputBuf = BAlloc.Allocate<char>(Size);
185   }
186 
187   if (Error E = Dec.decompress({OutputBuf, Size}))
188     fatal(toString(this) +
189           ": decompress failed: " + llvm::toString(std::move(E)));
190   this->Data = ArrayRef<uint8_t>((uint8_t *)OutputBuf, Size);
191   this->Flags &= ~(uint64_t)SHF_COMPRESSED;
192 }
193 
194 uint64_t SectionBase::getOffset(const DefinedRegular &Sym) const {
195   return getOffset(Sym.Value);
196 }
197 
198 InputSection *InputSectionBase::getLinkOrderDep() const {
199   if ((Flags & SHF_LINK_ORDER) && Link != 0) {
200     InputSectionBase *L = File->getSections()[Link];
201     if (auto *IS = dyn_cast<InputSection>(L))
202       return IS;
203     error(
204         "Merge and .eh_frame sections are not supported with SHF_LINK_ORDER " +
205         toString(L));
206   }
207   return nullptr;
208 }
209 
210 // Returns a source location string. Used to construct an error message.
211 template <class ELFT>
212 std::string InputSectionBase::getLocation(uint64_t Offset) {
213   // We don't have file for synthetic sections.
214   if (getFile<ELFT>() == nullptr)
215     return (Config->OutputFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")")
216         .str();
217 
218   // First check if we can get desired values from debugging information.
219   std::string LineInfo = getFile<ELFT>()->getLineInfo(this, Offset);
220   if (!LineInfo.empty())
221     return LineInfo;
222 
223   // File->SourceFile contains STT_FILE symbol that contains a
224   // source file name. If it's missing, we use an object file name.
225   std::string SrcFile = getFile<ELFT>()->SourceFile;
226   if (SrcFile.empty())
227     SrcFile = toString(File);
228 
229   // Find a function symbol that encloses a given location.
230   for (SymbolBody *B : getFile<ELFT>()->getSymbols())
231     if (auto *D = dyn_cast<DefinedRegular>(B))
232       if (D->Section == this && D->Type == STT_FUNC)
233         if (D->Value <= Offset && Offset < D->Value + D->Size)
234           return SrcFile + ":(function " + toString(*D) + ")";
235 
236   // If there's no symbol, print out the offset in the section.
237   return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str();
238 }
239 
240 // Returns a source location string. This function is intended to be
241 // used for constructing an error message. The returned message looks
242 // like this:
243 //
244 //   foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
245 //
246 // Returns an empty string if there's no way to get line info.
247 template <class ELFT> std::string InputSectionBase::getSrcMsg(uint64_t Offset) {
248   // Synthetic sections don't have input files.
249   elf::ObjectFile<ELFT> *File = getFile<ELFT>();
250   if (!File)
251     return "";
252 
253   Optional<DILineInfo> Info = File->getDILineInfo(this, Offset);
254 
255   // File->SourceFile contains STT_FILE symbol, and that is a last resort.
256   if (!Info)
257     return File->SourceFile;
258 
259   std::string Path = Info->FileName;
260   std::string Filename = path::filename(Path);
261   std::string Lineno = ":" + std::to_string(Info->Line);
262   if (Filename == Path)
263     return Filename + Lineno;
264   return Filename + Lineno + " (" + Path + Lineno + ")";
265 }
266 
267 // Returns a filename string along with an optional section name. This
268 // function is intended to be used for constructing an error
269 // message. The returned message looks like this:
270 //
271 //   path/to/foo.o:(function bar)
272 //
273 // or
274 //
275 //   path/to/foo.o:(function bar) in archive path/to/bar.a
276 template <class ELFT> std::string InputSectionBase::getObjMsg(uint64_t Off) {
277   // Synthetic sections don't have input files.
278   elf::ObjectFile<ELFT> *File = getFile<ELFT>();
279   std::string Filename = File ? File->getName() : "(internal)";
280 
281   std::string Archive;
282   if (!File->ArchiveName.empty())
283     Archive = (" in archive " + File->ArchiveName).str();
284 
285   // Find a symbol that encloses a given location.
286   for (SymbolBody *B : getFile<ELFT>()->getSymbols())
287     if (auto *D = dyn_cast<DefinedRegular>(B))
288       if (D->Section == this && D->Value <= Off && Off < D->Value + D->Size)
289         return Filename + ":(" + toString(*D) + ")" + Archive;
290 
291   // If there's no symbol, print out the offset in the section.
292   return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive)
293       .str();
294 }
295 
296 InputSectionBase InputSectionBase::Discarded;
297 
298 InputSection::InputSection(uint64_t Flags, uint32_t Type, uint32_t Alignment,
299                            ArrayRef<uint8_t> Data, StringRef Name, Kind K)
300     : InputSectionBase(nullptr, Flags, Type,
301                        /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Alignment, Data,
302                        Name, K) {}
303 
304 template <class ELFT>
305 InputSection::InputSection(elf::ObjectFile<ELFT> *F,
306                            const typename ELFT::Shdr *Header, StringRef Name)
307     : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {}
308 
309 bool InputSection::classof(const SectionBase *S) {
310   return S->kind() == SectionBase::Regular ||
311          S->kind() == SectionBase::Synthetic;
312 }
313 
314 bool InputSectionBase::classof(const SectionBase *S) {
315   return S->kind() != Output;
316 }
317 
318 OutputSection *InputSection::getParent() const {
319   return cast_or_null<OutputSection>(Parent);
320 }
321 
322 // Copy SHT_GROUP section contents. Used only for the -r option.
323 template <class ELFT> void InputSection::copyShtGroup(uint8_t *Buf) {
324   // ELFT::Word is the 32-bit integral type in the target endianness.
325   typedef typename ELFT::Word u32;
326   ArrayRef<u32> From = getDataAs<u32>();
327   auto *To = reinterpret_cast<u32 *>(Buf);
328 
329   // The first entry is not a section number but a flag.
330   *To++ = From[0];
331 
332   // Adjust section numbers because section numbers in an input object
333   // files are different in the output.
334   ArrayRef<InputSectionBase *> Sections = this->File->getSections();
335   for (uint32_t Idx : From.slice(1))
336     *To++ = Sections[Idx]->getOutputSection()->SectionIndex;
337 }
338 
339 InputSectionBase *InputSection::getRelocatedSection() {
340   assert(this->Type == SHT_RELA || this->Type == SHT_REL);
341   ArrayRef<InputSectionBase *> Sections = this->File->getSections();
342   return Sections[this->Info];
343 }
344 
345 // This is used for -r and --emit-relocs. We can't use memcpy to copy
346 // relocations because we need to update symbol table offset and section index
347 // for each relocation. So we copy relocations one by one.
348 template <class ELFT, class RelTy>
349 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
350   InputSectionBase *RelocatedSection = getRelocatedSection();
351 
352   // Loop is slow and have complexity O(N*M), where N - amount of
353   // relocations and M - amount of symbols in symbol table.
354   // That happens because getSymbolIndex(...) call below performs
355   // simple linear search.
356   for (const RelTy &Rel : Rels) {
357     uint32_t Type = Rel.getType(Config->IsMips64EL);
358     SymbolBody &Body = this->getFile<ELFT>()->getRelocTargetSym(Rel);
359 
360     auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
361     Buf += sizeof(RelTy);
362 
363     if (Config->IsRela)
364       P->r_addend = getAddend<ELFT>(Rel);
365 
366     // Output section VA is zero for -r, so r_offset is an offset within the
367     // section, but for --emit-relocs it is an virtual address.
368     P->r_offset = RelocatedSection->getOutputSection()->Addr +
369                   RelocatedSection->getOffset(Rel.r_offset);
370     P->setSymbolAndType(InX::SymTab->getSymbolIndex(&Body), Type,
371                         Config->IsMips64EL);
372 
373     if (Body.Type == STT_SECTION) {
374       // We combine multiple section symbols into only one per
375       // section. This means we have to update the addend. That is
376       // trivial for Elf_Rela, but for Elf_Rel we have to write to the
377       // section data. We do that by adding to the Relocation vector.
378 
379       // .eh_frame is horribly special and can reference discarded sections. To
380       // avoid having to parse and recreate .eh_frame, we just replace any
381       // relocation in it pointing to discarded sections with R_*_NONE, which
382       // hopefully creates a frame that is ignored at runtime.
383       SectionBase *Section = cast<DefinedRegular>(Body).Section;
384       if (Section == &InputSection::Discarded) {
385         P->setSymbolAndType(0, 0, false);
386         continue;
387       }
388 
389       if (Config->IsRela) {
390         P->r_addend += Body.getVA() - Section->getOutputSection()->Addr;
391       } else if (Config->Relocatable) {
392         const uint8_t *BufLoc = RelocatedSection->Data.begin() + Rel.r_offset;
393         RelocatedSection->Relocations.push_back(
394             {R_ABS, Type, Rel.r_offset, Target->getImplicitAddend(BufLoc, Type),
395              &Body});
396       }
397     }
398 
399   }
400 }
401 
402 static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A,
403                                               uint32_t P) {
404   switch (Type) {
405   case R_ARM_THM_JUMP11:
406     return P + 2 + A;
407   case R_ARM_CALL:
408   case R_ARM_JUMP24:
409   case R_ARM_PC24:
410   case R_ARM_PLT32:
411   case R_ARM_PREL31:
412   case R_ARM_THM_JUMP19:
413   case R_ARM_THM_JUMP24:
414     return P + 4 + A;
415   case R_ARM_THM_CALL:
416     // We don't want an interworking BLX to ARM
417     return P + 5 + A;
418   default:
419     return P + A;
420   }
421 }
422 
423 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
424                                                   uint64_t P) {
425   switch (Type) {
426   case R_AARCH64_CALL26:
427   case R_AARCH64_CONDBR19:
428   case R_AARCH64_JUMP26:
429   case R_AARCH64_TSTBR14:
430     return P + 4 + A;
431   default:
432     return P + A;
433   }
434 }
435 
436 // ARM SBREL relocations are of the form S + A - B where B is the static base
437 // The ARM ABI defines base to be "addressing origin of the output segment
438 // defining the symbol S". We defined the "addressing origin"/static base to be
439 // the base of the PT_LOAD segment containing the Body.
440 // The procedure call standard only defines a Read Write Position Independent
441 // RWPI variant so in practice we should expect the static base to be the base
442 // of the RW segment.
443 static uint64_t getARMStaticBase(const SymbolBody &Body) {
444   OutputSection *OS = Body.getOutputSection();
445   if (!OS || !OS->FirstInPtLoad)
446     fatal("SBREL relocation to " + Body.getName() + " without static base\n");
447   return OS->FirstInPtLoad->Addr;
448 }
449 
450 static uint64_t getRelocTargetVA(uint32_t Type, int64_t A, uint64_t P,
451                                  const SymbolBody &Body, RelExpr Expr) {
452   switch (Expr) {
453   case R_ABS:
454   case R_RELAX_GOT_PC_NOPIC:
455     return Body.getVA(A);
456   case R_ARM_SBREL:
457     return Body.getVA(A) - getARMStaticBase(Body);
458   case R_GOT:
459   case R_RELAX_TLS_GD_TO_IE_ABS:
460     return Body.getGotVA() + A;
461   case R_GOTONLY_PC:
462     return InX::Got->getVA() + A - P;
463   case R_GOTONLY_PC_FROM_END:
464     return InX::Got->getVA() + A - P + InX::Got->getSize();
465   case R_GOTREL:
466     return Body.getVA(A) - InX::Got->getVA();
467   case R_GOTREL_FROM_END:
468     return Body.getVA(A) - InX::Got->getVA() - InX::Got->getSize();
469   case R_GOT_FROM_END:
470   case R_RELAX_TLS_GD_TO_IE_END:
471     return Body.getGotOffset() + A - InX::Got->getSize();
472   case R_GOT_OFF:
473     return Body.getGotOffset() + A;
474   case R_GOT_PAGE_PC:
475   case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
476     return getAArch64Page(Body.getGotVA() + A) - getAArch64Page(P);
477   case R_GOT_PC:
478   case R_RELAX_TLS_GD_TO_IE:
479     return Body.getGotVA() + A - P;
480   case R_HINT:
481   case R_NONE:
482   case R_TLSDESC_CALL:
483     llvm_unreachable("cannot relocate hint relocs");
484   case R_MIPS_GOTREL:
485     return Body.getVA(A) - InX::MipsGot->getGp();
486   case R_MIPS_GOT_GP:
487     return InX::MipsGot->getGp() + A;
488   case R_MIPS_GOT_GP_PC: {
489     // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
490     // is _gp_disp symbol. In that case we should use the following
491     // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
492     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
493     uint64_t V = InX::MipsGot->getGp() + A - P;
494     if (Type == R_MIPS_LO16)
495       V += 4;
496     return V;
497   }
498   case R_MIPS_GOT_LOCAL_PAGE:
499     // If relocation against MIPS local symbol requires GOT entry, this entry
500     // should be initialized by 'page address'. This address is high 16-bits
501     // of sum the symbol's value and the addend.
502     return InX::MipsGot->getVA() + InX::MipsGot->getPageEntryOffset(Body, A) -
503            InX::MipsGot->getGp();
504   case R_MIPS_GOT_OFF:
505   case R_MIPS_GOT_OFF32:
506     // In case of MIPS if a GOT relocation has non-zero addend this addend
507     // should be applied to the GOT entry content not to the GOT entry offset.
508     // That is why we use separate expression type.
509     return InX::MipsGot->getVA() + InX::MipsGot->getBodyEntryOffset(Body, A) -
510            InX::MipsGot->getGp();
511   case R_MIPS_TLSGD:
512     return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
513            InX::MipsGot->getGlobalDynOffset(Body) - InX::MipsGot->getGp();
514   case R_MIPS_TLSLD:
515     return InX::MipsGot->getVA() + InX::MipsGot->getTlsOffset() +
516            InX::MipsGot->getTlsIndexOff() - InX::MipsGot->getGp();
517   case R_PAGE_PC:
518   case R_PLT_PAGE_PC: {
519     uint64_t Dest;
520     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
521       Dest = getAArch64Page(A);
522     else
523       Dest = getAArch64Page(Body.getVA(A));
524     return Dest - getAArch64Page(P);
525   }
526   case R_PC: {
527     uint64_t Dest;
528     if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) {
529       // On ARM and AArch64 a branch to an undefined weak resolves to the
530       // next instruction, otherwise the place.
531       if (Config->EMachine == EM_ARM)
532         Dest = getARMUndefinedRelativeWeakVA(Type, A, P);
533       else if (Config->EMachine == EM_AARCH64)
534         Dest = getAArch64UndefinedRelativeWeakVA(Type, A, P);
535       else
536         Dest = Body.getVA(A);
537     } else {
538       Dest = Body.getVA(A);
539     }
540     return Dest - P;
541   }
542   case R_PLT:
543     return Body.getPltVA() + A;
544   case R_PLT_PC:
545   case R_PPC_PLT_OPD:
546     return Body.getPltVA() + A - P;
547   case R_PPC_OPD: {
548     uint64_t SymVA = Body.getVA(A);
549     // If we have an undefined weak symbol, we might get here with a symbol
550     // address of zero. That could overflow, but the code must be unreachable,
551     // so don't bother doing anything at all.
552     if (!SymVA)
553       return 0;
554     if (Out::Opd) {
555       // If this is a local call, and we currently have the address of a
556       // function-descriptor, get the underlying code address instead.
557       uint64_t OpdStart = Out::Opd->Addr;
558       uint64_t OpdEnd = OpdStart + Out::Opd->Size;
559       bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
560       if (InOpd)
561         SymVA = read64be(&Out::OpdBuf[SymVA - OpdStart]);
562     }
563     return SymVA - P;
564   }
565   case R_PPC_TOC:
566     return getPPC64TocBase() + A;
567   case R_RELAX_GOT_PC:
568     return Body.getVA(A) - P;
569   case R_RELAX_TLS_GD_TO_LE:
570   case R_RELAX_TLS_IE_TO_LE:
571   case R_RELAX_TLS_LD_TO_LE:
572   case R_TLS:
573     // A weak undefined TLS symbol resolves to the base of the TLS
574     // block, i.e. gets a value of zero. If we pass --gc-sections to
575     // lld and .tbss is not referenced, it gets reclaimed and we don't
576     // create a TLS program header. Therefore, we resolve this
577     // statically to zero.
578     if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
579         Body.symbol()->isWeak())
580       return 0;
581     if (Target->TcbSize)
582       return Body.getVA(A) + alignTo(Target->TcbSize, Out::TlsPhdr->p_align);
583     return Body.getVA(A) - Out::TlsPhdr->p_memsz;
584   case R_RELAX_TLS_GD_TO_LE_NEG:
585   case R_NEG_TLS:
586     return Out::TlsPhdr->p_memsz - Body.getVA(A);
587   case R_SIZE:
588     return A; // Body.getSize was already folded into the addend.
589   case R_TLSDESC:
590     return InX::Got->getGlobalDynAddr(Body) + A;
591   case R_TLSDESC_PAGE:
592     return getAArch64Page(InX::Got->getGlobalDynAddr(Body) + A) -
593            getAArch64Page(P);
594   case R_TLSGD:
595     return InX::Got->getGlobalDynOffset(Body) + A - InX::Got->getSize();
596   case R_TLSGD_PC:
597     return InX::Got->getGlobalDynAddr(Body) + A - P;
598   case R_TLSLD:
599     return InX::Got->getTlsIndexOff() + A - InX::Got->getSize();
600   case R_TLSLD_PC:
601     return InX::Got->getTlsIndexVA() + A - P;
602   }
603   llvm_unreachable("Invalid expression");
604 }
605 
606 // This function applies relocations to sections without SHF_ALLOC bit.
607 // Such sections are never mapped to memory at runtime. Debug sections are
608 // an example. Relocations in non-alloc sections are much easier to
609 // handle than in allocated sections because it will never need complex
610 // treatement such as GOT or PLT (because at runtime no one refers them).
611 // So, we handle relocations for non-alloc sections directly in this
612 // function as a performance optimization.
613 template <class ELFT, class RelTy>
614 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
615   for (const RelTy &Rel : Rels) {
616     uint32_t Type = Rel.getType(Config->IsMips64EL);
617     uint64_t Offset = getOffset(Rel.r_offset);
618     uint8_t *BufLoc = Buf + Offset;
619     int64_t Addend = getAddend<ELFT>(Rel);
620     if (!RelTy::IsRela)
621       Addend += Target->getImplicitAddend(BufLoc, Type);
622 
623     SymbolBody &Sym = this->getFile<ELFT>()->getRelocTargetSym(Rel);
624     RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc);
625     if (Expr == R_NONE)
626       continue;
627     if (Expr != R_ABS) {
628       error(this->getLocation<ELFT>(Offset) + ": has non-ABS reloc");
629       return;
630     }
631 
632     uint64_t AddrLoc = getParent()->Addr + Offset;
633     uint64_t SymVA = 0;
634     if (!Sym.isTls() || Out::TlsPhdr)
635       SymVA = SignExtend64<sizeof(typename ELFT::uint) * 8>(
636           getRelocTargetVA(Type, Addend, AddrLoc, Sym, R_ABS));
637     Target->relocateOne(BufLoc, Type, SymVA);
638   }
639 }
640 
641 template <class ELFT> elf::ObjectFile<ELFT> *InputSectionBase::getFile() const {
642   return cast_or_null<elf::ObjectFile<ELFT>>(File);
643 }
644 
645 template <class ELFT>
646 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
647   if (Flags & SHF_ALLOC)
648     relocateAlloc(Buf, BufEnd);
649   else
650     relocateNonAlloc<ELFT>(Buf, BufEnd);
651 }
652 
653 template <class ELFT>
654 void InputSectionBase::relocateNonAlloc(uint8_t *Buf, uint8_t *BufEnd) {
655   // scanReloc function in Writer.cpp constructs Relocations
656   // vector only for SHF_ALLOC'ed sections. For other sections,
657   // we handle relocations directly here.
658   auto *IS = cast<InputSection>(this);
659   assert(!(IS->Flags & SHF_ALLOC));
660   if (IS->AreRelocsRela)
661     IS->relocateNonAlloc<ELFT>(Buf, IS->template relas<ELFT>());
662   else
663     IS->relocateNonAlloc<ELFT>(Buf, IS->template rels<ELFT>());
664 }
665 
666 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) {
667   assert(Flags & SHF_ALLOC);
668   const unsigned Bits = Config->Wordsize * 8;
669   for (const Relocation &Rel : Relocations) {
670     uint64_t Offset = getOffset(Rel.Offset);
671     uint8_t *BufLoc = Buf + Offset;
672     uint32_t Type = Rel.Type;
673 
674     uint64_t AddrLoc = getOutputSection()->Addr + Offset;
675     RelExpr Expr = Rel.Expr;
676     uint64_t TargetVA = SignExtend64(
677         getRelocTargetVA(Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr), Bits);
678 
679     switch (Expr) {
680     case R_RELAX_GOT_PC:
681     case R_RELAX_GOT_PC_NOPIC:
682       Target->relaxGot(BufLoc, TargetVA);
683       break;
684     case R_RELAX_TLS_IE_TO_LE:
685       Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
686       break;
687     case R_RELAX_TLS_LD_TO_LE:
688       Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
689       break;
690     case R_RELAX_TLS_GD_TO_LE:
691     case R_RELAX_TLS_GD_TO_LE_NEG:
692       Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
693       break;
694     case R_RELAX_TLS_GD_TO_IE:
695     case R_RELAX_TLS_GD_TO_IE_ABS:
696     case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
697     case R_RELAX_TLS_GD_TO_IE_END:
698       Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
699       break;
700     case R_PPC_PLT_OPD:
701       // Patch a nop (0x60000000) to a ld.
702       if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
703         write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
704       LLVM_FALLTHROUGH;
705     default:
706       Target->relocateOne(BufLoc, Type, TargetVA);
707       break;
708     }
709   }
710 }
711 
712 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
713   if (this->Type == SHT_NOBITS)
714     return;
715 
716   if (auto *S = dyn_cast<SyntheticSection>(this)) {
717     S->writeTo(Buf + OutSecOff);
718     return;
719   }
720 
721   // If -r or --emit-relocs is given, then an InputSection
722   // may be a relocation section.
723   if (this->Type == SHT_RELA) {
724     copyRelocations<ELFT>(Buf + OutSecOff,
725                           this->template getDataAs<typename ELFT::Rela>());
726     return;
727   }
728   if (this->Type == SHT_REL) {
729     copyRelocations<ELFT>(Buf + OutSecOff,
730                           this->template getDataAs<typename ELFT::Rel>());
731     return;
732   }
733 
734   // If -r is given, we may have a SHT_GROUP section.
735   if (this->Type == SHT_GROUP) {
736     copyShtGroup<ELFT>(Buf + OutSecOff);
737     return;
738   }
739 
740   // Copy section contents from source object file to output file
741   // and then apply relocations.
742   memcpy(Buf + OutSecOff, Data.data(), Data.size());
743   uint8_t *BufEnd = Buf + OutSecOff + Data.size();
744   this->relocate<ELFT>(Buf, BufEnd);
745 }
746 
747 void InputSection::replace(InputSection *Other) {
748   this->Alignment = std::max(this->Alignment, Other->Alignment);
749   Other->Repl = this->Repl;
750   Other->Live = false;
751 }
752 
753 template <class ELFT>
754 EhInputSection::EhInputSection(elf::ObjectFile<ELFT> *F,
755                                const typename ELFT::Shdr *Header,
756                                StringRef Name)
757     : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {
758   // Mark .eh_frame sections as live by default because there are
759   // usually no relocations that point to .eh_frames. Otherwise,
760   // the garbage collector would drop all .eh_frame sections.
761   this->Live = true;
762 }
763 
764 SyntheticSection *EhInputSection::getParent() const {
765   return cast_or_null<SyntheticSection>(Parent);
766 }
767 
768 bool EhInputSection::classof(const SectionBase *S) {
769   return S->kind() == InputSectionBase::EHFrame;
770 }
771 
772 // Returns the index of the first relocation that points to a region between
773 // Begin and Begin+Size.
774 template <class IntTy, class RelTy>
775 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
776                          unsigned &RelocI) {
777   // Start search from RelocI for fast access. That works because the
778   // relocations are sorted in .eh_frame.
779   for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
780     const RelTy &Rel = Rels[RelocI];
781     if (Rel.r_offset < Begin)
782       continue;
783 
784     if (Rel.r_offset < Begin + Size)
785       return RelocI;
786     return -1;
787   }
788   return -1;
789 }
790 
791 // .eh_frame is a sequence of CIE or FDE records.
792 // This function splits an input section into records and returns them.
793 template <class ELFT> void EhInputSection::split() {
794   // Early exit if already split.
795   if (!this->Pieces.empty())
796     return;
797 
798   if (this->NumRelocations) {
799     if (this->AreRelocsRela)
800       split<ELFT>(this->relas<ELFT>());
801     else
802       split<ELFT>(this->rels<ELFT>());
803     return;
804   }
805   split<ELFT>(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
806 }
807 
808 template <class ELFT, class RelTy>
809 void EhInputSection::split(ArrayRef<RelTy> Rels) {
810   ArrayRef<uint8_t> Data = this->Data;
811   unsigned RelI = 0;
812   for (size_t Off = 0, End = Data.size(); Off != End;) {
813     size_t Size = readEhRecordSize<ELFT>(this, Off);
814     this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
815     // The empty record is the end marker.
816     if (Size == 4)
817       break;
818     Off += Size;
819   }
820 }
821 
822 static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
823   // Optimize the common case.
824   StringRef S((const char *)A.data(), A.size());
825   if (EntSize == 1)
826     return S.find(0);
827 
828   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
829     const char *B = S.begin() + I;
830     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
831       return I;
832   }
833   return StringRef::npos;
834 }
835 
836 SyntheticSection *MergeInputSection::getParent() const {
837   return cast_or_null<SyntheticSection>(Parent);
838 }
839 
840 // Split SHF_STRINGS section. Such section is a sequence of
841 // null-terminated strings.
842 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
843   size_t Off = 0;
844   bool IsAlloc = this->Flags & SHF_ALLOC;
845   while (!Data.empty()) {
846     size_t End = findNull(Data, EntSize);
847     if (End == StringRef::npos)
848       fatal(toString(this) + ": string is not null terminated");
849     size_t Size = End + EntSize;
850     Pieces.emplace_back(Off, !IsAlloc);
851     Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
852     Data = Data.slice(Size);
853     Off += Size;
854   }
855 }
856 
857 // Split non-SHF_STRINGS section. Such section is a sequence of
858 // fixed size records.
859 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
860                                         size_t EntSize) {
861   size_t Size = Data.size();
862   assert((Size % EntSize) == 0);
863   bool IsAlloc = this->Flags & SHF_ALLOC;
864   for (unsigned I = 0, N = Size; I != N; I += EntSize) {
865     Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
866     Pieces.emplace_back(I, !IsAlloc);
867   }
868 }
869 
870 template <class ELFT>
871 MergeInputSection::MergeInputSection(elf::ObjectFile<ELFT> *F,
872                                      const typename ELFT::Shdr *Header,
873                                      StringRef Name)
874     : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
875 
876 // This function is called after we obtain a complete list of input sections
877 // that need to be linked. This is responsible to split section contents
878 // into small chunks for further processing.
879 //
880 // Note that this function is called from parallel_for_each. This must be
881 // thread-safe (i.e. no memory allocation from the pools).
882 void MergeInputSection::splitIntoPieces() {
883   ArrayRef<uint8_t> Data = this->Data;
884   uint64_t EntSize = this->Entsize;
885   if (this->Flags & SHF_STRINGS)
886     splitStrings(Data, EntSize);
887   else
888     splitNonStrings(Data, EntSize);
889 
890   if (Config->GcSections && (this->Flags & SHF_ALLOC))
891     for (uint64_t Off : LiveOffsets)
892       this->getSectionPiece(Off)->Live = true;
893 }
894 
895 bool MergeInputSection::classof(const SectionBase *S) {
896   return S->kind() == InputSectionBase::Merge;
897 }
898 
899 // Do binary search to get a section piece at a given input offset.
900 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) {
901   auto *This = static_cast<const MergeInputSection *>(this);
902   return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
903 }
904 
905 template <class It, class T, class Compare>
906 static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
907   size_t Size = std::distance(First, Last);
908   assert(Size != 0);
909   while (Size != 1) {
910     size_t H = Size / 2;
911     const It MI = First + H;
912     Size -= H;
913     First = Comp(Value, *MI) ? First : First + H;
914   }
915   return Comp(Value, *First) ? First : First + 1;
916 }
917 
918 const SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) const {
919   uint64_t Size = this->Data.size();
920   if (Offset >= Size)
921     fatal(toString(this) + ": entry is past the end of the section");
922 
923   // Find the element this offset points to.
924   auto I = fastUpperBound(
925       Pieces.begin(), Pieces.end(), Offset,
926       [](const uint64_t &A, const SectionPiece &B) { return A < B.InputOff; });
927   --I;
928   return &*I;
929 }
930 
931 // Returns the offset in an output section for a given input offset.
932 // Because contents of a mergeable section is not contiguous in output,
933 // it is not just an addition to a base output offset.
934 uint64_t MergeInputSection::getOffset(uint64_t Offset) const {
935   // Initialize OffsetMap lazily.
936   llvm::call_once(InitOffsetMap, [&] {
937     OffsetMap.reserve(Pieces.size());
938     for (const SectionPiece &Piece : Pieces)
939       OffsetMap[Piece.InputOff] = Piece.OutputOff;
940   });
941 
942   // Find a string starting at a given offset.
943   auto It = OffsetMap.find(Offset);
944   if (It != OffsetMap.end())
945     return It->second;
946 
947   if (!this->Live)
948     return 0;
949 
950   // If Offset is not at beginning of a section piece, it is not in the map.
951   // In that case we need to search from the original section piece vector.
952   const SectionPiece &Piece = *this->getSectionPiece(Offset);
953   if (!Piece.Live)
954     return 0;
955 
956   uint64_t Addend = Offset - Piece.InputOff;
957   return Piece.OutputOff + Addend;
958 }
959 
960 template InputSection::InputSection(elf::ObjectFile<ELF32LE> *,
961                                     const ELF32LE::Shdr *, StringRef);
962 template InputSection::InputSection(elf::ObjectFile<ELF32BE> *,
963                                     const ELF32BE::Shdr *, StringRef);
964 template InputSection::InputSection(elf::ObjectFile<ELF64LE> *,
965                                     const ELF64LE::Shdr *, StringRef);
966 template InputSection::InputSection(elf::ObjectFile<ELF64BE> *,
967                                     const ELF64BE::Shdr *, StringRef);
968 
969 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
970 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
971 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
972 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
973 
974 template std::string InputSectionBase::getSrcMsg<ELF32LE>(uint64_t);
975 template std::string InputSectionBase::getSrcMsg<ELF32BE>(uint64_t);
976 template std::string InputSectionBase::getSrcMsg<ELF64LE>(uint64_t);
977 template std::string InputSectionBase::getSrcMsg<ELF64BE>(uint64_t);
978 
979 template std::string InputSectionBase::getObjMsg<ELF32LE>(uint64_t);
980 template std::string InputSectionBase::getObjMsg<ELF32BE>(uint64_t);
981 template std::string InputSectionBase::getObjMsg<ELF64LE>(uint64_t);
982 template std::string InputSectionBase::getObjMsg<ELF64BE>(uint64_t);
983 
984 template void InputSection::writeTo<ELF32LE>(uint8_t *);
985 template void InputSection::writeTo<ELF32BE>(uint8_t *);
986 template void InputSection::writeTo<ELF64LE>(uint8_t *);
987 template void InputSection::writeTo<ELF64BE>(uint8_t *);
988 
989 template elf::ObjectFile<ELF32LE> *InputSectionBase::getFile<ELF32LE>() const;
990 template elf::ObjectFile<ELF32BE> *InputSectionBase::getFile<ELF32BE>() const;
991 template elf::ObjectFile<ELF64LE> *InputSectionBase::getFile<ELF64LE>() const;
992 template elf::ObjectFile<ELF64BE> *InputSectionBase::getFile<ELF64BE>() const;
993 
994 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF32LE> *,
995                                               const ELF32LE::Shdr *, StringRef);
996 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF32BE> *,
997                                               const ELF32BE::Shdr *, StringRef);
998 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF64LE> *,
999                                               const ELF64LE::Shdr *, StringRef);
1000 template MergeInputSection::MergeInputSection(elf::ObjectFile<ELF64BE> *,
1001                                               const ELF64BE::Shdr *, StringRef);
1002 
1003 template EhInputSection::EhInputSection(elf::ObjectFile<ELF32LE> *,
1004                                         const ELF32LE::Shdr *, StringRef);
1005 template EhInputSection::EhInputSection(elf::ObjectFile<ELF32BE> *,
1006                                         const ELF32BE::Shdr *, StringRef);
1007 template EhInputSection::EhInputSection(elf::ObjectFile<ELF64LE> *,
1008                                         const ELF64LE::Shdr *, StringRef);
1009 template EhInputSection::EhInputSection(elf::ObjectFile<ELF64BE> *,
1010                                         const ELF64BE::Shdr *, StringRef);
1011 
1012 template void EhInputSection::split<ELF32LE>();
1013 template void EhInputSection::split<ELF32BE>();
1014 template void EhInputSection::split<ELF64LE>();
1015 template void EhInputSection::split<ELF64BE>();
1016