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