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