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