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