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