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