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 "SymbolTable.h"
18 #include "Symbols.h"
19 #include "SyntheticSections.h"
20 #include "Target.h"
21 #include "Thunks.h"
22 #include "lld/Common/ErrorHandler.h"
23 #include "lld/Common/Memory.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Compression.h"
26 #include "llvm/Support/Endian.h"
27 #include "llvm/Support/Threading.h"
28 #include "llvm/Support/xxhash.h"
29 #include <algorithm>
30 #include <mutex>
31 #include <set>
32 #include <vector>
33 
34 using namespace llvm;
35 using namespace llvm::ELF;
36 using namespace llvm::object;
37 using namespace llvm::support;
38 using namespace llvm::support::endian;
39 using namespace llvm::sys;
40 
41 using namespace lld;
42 using namespace lld::elf;
43 
44 std::vector<InputSectionBase *> elf::InputSections;
45 
46 // Returns a string to construct an error message.
toString(const InputSectionBase * Sec)47 std::string lld::toString(const InputSectionBase *Sec) {
48   return (toString(Sec->File) + ":(" + Sec->Name + ")").str();
49 }
50 
51 template <class ELFT>
getSectionContents(ObjFile<ELFT> & File,const typename ELFT::Shdr & Hdr)52 static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &File,
53                                             const typename ELFT::Shdr &Hdr) {
54   if (Hdr.sh_type == SHT_NOBITS)
55     return makeArrayRef<uint8_t>(nullptr, Hdr.sh_size);
56   return check(File.getObj().getSectionContents(&Hdr));
57 }
58 
InputSectionBase(InputFile * File,uint64_t Flags,uint32_t Type,uint64_t Entsize,uint32_t Link,uint32_t Info,uint32_t Alignment,ArrayRef<uint8_t> Data,StringRef Name,Kind SectionKind)59 InputSectionBase::InputSectionBase(InputFile *File, uint64_t Flags,
60                                    uint32_t Type, uint64_t Entsize,
61                                    uint32_t Link, uint32_t Info,
62                                    uint32_t Alignment, ArrayRef<uint8_t> Data,
63                                    StringRef Name, Kind SectionKind)
64     : SectionBase(SectionKind, Name, Flags, Entsize, Alignment, Type, Info,
65                   Link),
66       File(File), RawData(Data) {
67   // In order to reduce memory allocation, we assume that mergeable
68   // sections are smaller than 4 GiB, which is not an unreasonable
69   // assumption as of 2017.
70   if (SectionKind == SectionBase::Merge && RawData.size() > UINT32_MAX)
71     error(toString(this) + ": section too large");
72 
73   NumRelocations = 0;
74   AreRelocsRela = false;
75 
76   // The ELF spec states that a value of 0 means the section has
77   // no alignment constraits.
78   uint32_t V = std::max<uint64_t>(Alignment, 1);
79   if (!isPowerOf2_64(V))
80     fatal(toString(File) + ": section sh_addralign is not a power of 2");
81   this->Alignment = V;
82 
83   // In ELF, each section can be compressed by zlib, and if compressed,
84   // section name may be mangled by appending "z" (e.g. ".zdebug_info").
85   // If that's the case, demangle section name so that we can handle a
86   // section as if it weren't compressed.
87   if ((Flags & SHF_COMPRESSED) || Name.startswith(".zdebug")) {
88     if (!zlib::isAvailable())
89       error(toString(File) + ": contains a compressed section, " +
90             "but zlib is not available");
91     parseCompressedHeader();
92   }
93 }
94 
95 // Drop SHF_GROUP bit unless we are producing a re-linkable object file.
96 // SHF_GROUP is a marker that a section belongs to some comdat group.
97 // That flag doesn't make sense in an executable.
getFlags(uint64_t Flags)98 static uint64_t getFlags(uint64_t Flags) {
99   Flags &= ~(uint64_t)SHF_INFO_LINK;
100   if (!Config->Relocatable)
101     Flags &= ~(uint64_t)SHF_GROUP;
102   return Flags;
103 }
104 
105 // GNU assembler 2.24 and LLVM 4.0.0's MC (the newest release as of
106 // March 2017) fail to infer section types for sections starting with
107 // ".init_array." or ".fini_array.". They set SHT_PROGBITS instead of
108 // SHF_INIT_ARRAY. As a result, the following assembler directive
109 // creates ".init_array.100" with SHT_PROGBITS, for example.
110 //
111 //   .section .init_array.100, "aw"
112 //
113 // This function forces SHT_{INIT,FINI}_ARRAY so that we can handle
114 // incorrect inputs as if they were correct from the beginning.
getType(uint64_t Type,StringRef Name)115 static uint64_t getType(uint64_t Type, StringRef Name) {
116   if (Type == SHT_PROGBITS && Name.startswith(".init_array."))
117     return SHT_INIT_ARRAY;
118   if (Type == SHT_PROGBITS && Name.startswith(".fini_array."))
119     return SHT_FINI_ARRAY;
120   return Type;
121 }
122 
123 template <class ELFT>
InputSectionBase(ObjFile<ELFT> & File,const typename ELFT::Shdr & Hdr,StringRef Name,Kind SectionKind)124 InputSectionBase::InputSectionBase(ObjFile<ELFT> &File,
125                                    const typename ELFT::Shdr &Hdr,
126                                    StringRef Name, Kind SectionKind)
127     : InputSectionBase(&File, getFlags(Hdr.sh_flags),
128                        getType(Hdr.sh_type, Name), Hdr.sh_entsize, Hdr.sh_link,
129                        Hdr.sh_info, Hdr.sh_addralign,
130                        getSectionContents(File, Hdr), Name, SectionKind) {
131   // We reject object files having insanely large alignments even though
132   // they are allowed by the spec. I think 4GB is a reasonable limitation.
133   // We might want to relax this in the future.
134   if (Hdr.sh_addralign > UINT32_MAX)
135     fatal(toString(&File) + ": section sh_addralign is too large");
136 }
137 
getSize() const138 size_t InputSectionBase::getSize() const {
139   if (auto *S = dyn_cast<SyntheticSection>(this))
140     return S->getSize();
141   if (UncompressedSize >= 0)
142     return UncompressedSize;
143   return RawData.size();
144 }
145 
uncompress() const146 void InputSectionBase::uncompress() const {
147   size_t Size = UncompressedSize;
148   UncompressedBuf.reset(new char[Size]);
149 
150   if (Error E =
151           zlib::uncompress(toStringRef(RawData), UncompressedBuf.get(), Size))
152     fatal(toString(this) +
153           ": uncompress failed: " + llvm::toString(std::move(E)));
154   RawData = makeArrayRef((uint8_t *)UncompressedBuf.get(), Size);
155 }
156 
getOffsetInFile() const157 uint64_t InputSectionBase::getOffsetInFile() const {
158   const uint8_t *FileStart = (const uint8_t *)File->MB.getBufferStart();
159   const uint8_t *SecStart = data().begin();
160   return SecStart - FileStart;
161 }
162 
getOffset(uint64_t Offset) const163 uint64_t SectionBase::getOffset(uint64_t Offset) const {
164   switch (kind()) {
165   case Output: {
166     auto *OS = cast<OutputSection>(this);
167     // For output sections we treat offset -1 as the end of the section.
168     return Offset == uint64_t(-1) ? OS->Size : Offset;
169   }
170   case Regular:
171   case Synthetic:
172     return cast<InputSection>(this)->getOffset(Offset);
173   case EHFrame:
174     // The file crtbeginT.o has relocations pointing to the start of an empty
175     // .eh_frame that is known to be the first in the link. It does that to
176     // identify the start of the output .eh_frame.
177     return Offset;
178   case Merge:
179     const MergeInputSection *MS = cast<MergeInputSection>(this);
180     if (InputSection *IS = MS->getParent())
181       return IS->getOffset(MS->getParentOffset(Offset));
182     return MS->getParentOffset(Offset);
183   }
184   llvm_unreachable("invalid section kind");
185 }
186 
getVA(uint64_t Offset) const187 uint64_t SectionBase::getVA(uint64_t Offset) const {
188   const OutputSection *Out = getOutputSection();
189   return (Out ? Out->Addr : 0) + getOffset(Offset);
190 }
191 
getOutputSection()192 OutputSection *SectionBase::getOutputSection() {
193   InputSection *Sec;
194   if (auto *IS = dyn_cast<InputSection>(this))
195     Sec = IS;
196   else if (auto *MS = dyn_cast<MergeInputSection>(this))
197     Sec = MS->getParent();
198   else if (auto *EH = dyn_cast<EhInputSection>(this))
199     Sec = EH->getParent();
200   else
201     return cast<OutputSection>(this);
202   return Sec ? Sec->getParent() : nullptr;
203 }
204 
205 // When a section is compressed, `RawData` consists with a header followed
206 // by zlib-compressed data. This function parses a header to initialize
207 // `UncompressedSize` member and remove the header from `RawData`.
parseCompressedHeader()208 void InputSectionBase::parseCompressedHeader() {
209   typedef typename ELF64LE::Chdr Chdr64;
210   typedef typename ELF32LE::Chdr Chdr32;
211 
212   // Old-style header
213   if (Name.startswith(".zdebug")) {
214     if (!toStringRef(RawData).startswith("ZLIB")) {
215       error(toString(this) + ": corrupted compressed section header");
216       return;
217     }
218     RawData = RawData.slice(4);
219 
220     if (RawData.size() < 8) {
221       error(toString(this) + ": corrupted compressed section header");
222       return;
223     }
224 
225     UncompressedSize = read64be(RawData.data());
226     RawData = RawData.slice(8);
227 
228     // Restore the original section name.
229     // (e.g. ".zdebug_info" -> ".debug_info")
230     Name = Saver.save("." + Name.substr(2));
231     return;
232   }
233 
234   assert(Flags & SHF_COMPRESSED);
235   Flags &= ~(uint64_t)SHF_COMPRESSED;
236 
237   // New-style 64-bit header
238   if (Config->Is64) {
239     if (RawData.size() < sizeof(Chdr64)) {
240       error(toString(this) + ": corrupted compressed section");
241       return;
242     }
243 
244     auto *Hdr = reinterpret_cast<const Chdr64 *>(RawData.data());
245     if (Hdr->ch_type != ELFCOMPRESS_ZLIB) {
246       error(toString(this) + ": unsupported compression type");
247       return;
248     }
249 
250     UncompressedSize = Hdr->ch_size;
251     Alignment = std::max<uint64_t>(Hdr->ch_addralign, 1);
252     RawData = RawData.slice(sizeof(*Hdr));
253     return;
254   }
255 
256   // New-style 32-bit header
257   if (RawData.size() < sizeof(Chdr32)) {
258     error(toString(this) + ": corrupted compressed section");
259     return;
260   }
261 
262   auto *Hdr = reinterpret_cast<const Chdr32 *>(RawData.data());
263   if (Hdr->ch_type != ELFCOMPRESS_ZLIB) {
264     error(toString(this) + ": unsupported compression type");
265     return;
266   }
267 
268   UncompressedSize = Hdr->ch_size;
269   Alignment = std::max<uint64_t>(Hdr->ch_addralign, 1);
270   RawData = RawData.slice(sizeof(*Hdr));
271 }
272 
getLinkOrderDep() const273 InputSection *InputSectionBase::getLinkOrderDep() const {
274   assert(Link);
275   assert(Flags & SHF_LINK_ORDER);
276   return cast<InputSection>(File->getSections()[Link]);
277 }
278 
279 // Find a function symbol that encloses a given location.
280 template <class ELFT>
getEnclosingFunction(uint64_t Offset)281 Defined *InputSectionBase::getEnclosingFunction(uint64_t Offset) {
282   for (Symbol *B : File->getSymbols())
283     if (Defined *D = dyn_cast<Defined>(B))
284       if (D->Section == this && D->Type == STT_FUNC && D->Value <= Offset &&
285           Offset < D->Value + D->Size)
286         return D;
287   return nullptr;
288 }
289 
290 // Returns a source location string. Used to construct an error message.
291 template <class ELFT>
getLocation(uint64_t Offset)292 std::string InputSectionBase::getLocation(uint64_t Offset) {
293   std::string SecAndOffset = (Name + "+0x" + utohexstr(Offset)).str();
294 
295   // We don't have file for synthetic sections.
296   if (getFile<ELFT>() == nullptr)
297     return (Config->OutputFile + ":(" + SecAndOffset + ")")
298         .str();
299 
300   // First check if we can get desired values from debugging information.
301   if (Optional<DILineInfo> Info = getFile<ELFT>()->getDILineInfo(this, Offset))
302     return Info->FileName + ":" + std::to_string(Info->Line) + ":(" +
303            SecAndOffset + ")";
304 
305   // File->SourceFile contains STT_FILE symbol that contains a
306   // source file name. If it's missing, we use an object file name.
307   std::string SrcFile = getFile<ELFT>()->SourceFile;
308   if (SrcFile.empty())
309     SrcFile = toString(File);
310 
311   if (Defined *D = getEnclosingFunction<ELFT>(Offset))
312     return SrcFile + ":(function " + toString(*D) + ": " + SecAndOffset + ")";
313 
314   // If there's no symbol, print out the offset in the section.
315   return (SrcFile + ":(" + SecAndOffset + ")");
316 }
317 
318 // This function is intended to be used for constructing an error message.
319 // The returned message looks like this:
320 //
321 //   foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
322 //
323 //  Returns an empty string if there's no way to get line info.
getSrcMsg(const Symbol & Sym,uint64_t Offset)324 std::string InputSectionBase::getSrcMsg(const Symbol &Sym, uint64_t Offset) {
325   return File->getSrcMsg(Sym, *this, Offset);
326 }
327 
328 // Returns a filename string along with an optional section name. This
329 // function is intended to be used for constructing an error
330 // message. The returned message looks like this:
331 //
332 //   path/to/foo.o:(function bar)
333 //
334 // or
335 //
336 //   path/to/foo.o:(function bar) in archive path/to/bar.a
getObjMsg(uint64_t Off)337 std::string InputSectionBase::getObjMsg(uint64_t Off) {
338   std::string Filename = File->getName();
339 
340   std::string Archive;
341   if (!File->ArchiveName.empty())
342     Archive = " in archive " + File->ArchiveName;
343 
344   // Find a symbol that encloses a given location.
345   for (Symbol *B : File->getSymbols())
346     if (auto *D = dyn_cast<Defined>(B))
347       if (D->Section == this && D->Value <= Off && Off < D->Value + D->Size)
348         return Filename + ":(" + toString(*D) + ")" + Archive;
349 
350   // If there's no symbol, print out the offset in the section.
351   return (Filename + ":(" + Name + "+0x" + utohexstr(Off) + ")" + Archive)
352       .str();
353 }
354 
355 InputSection InputSection::Discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), "");
356 
InputSection(InputFile * F,uint64_t Flags,uint32_t Type,uint32_t Alignment,ArrayRef<uint8_t> Data,StringRef Name,Kind K)357 InputSection::InputSection(InputFile *F, uint64_t Flags, uint32_t Type,
358                            uint32_t Alignment, ArrayRef<uint8_t> Data,
359                            StringRef Name, Kind K)
360     : InputSectionBase(F, Flags, Type,
361                        /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Alignment, Data,
362                        Name, K) {}
363 
364 template <class ELFT>
InputSection(ObjFile<ELFT> & F,const typename ELFT::Shdr & Header,StringRef Name)365 InputSection::InputSection(ObjFile<ELFT> &F, const typename ELFT::Shdr &Header,
366                            StringRef Name)
367     : InputSectionBase(F, Header, Name, InputSectionBase::Regular) {}
368 
classof(const SectionBase * S)369 bool InputSection::classof(const SectionBase *S) {
370   return S->kind() == SectionBase::Regular ||
371          S->kind() == SectionBase::Synthetic;
372 }
373 
getParent() const374 OutputSection *InputSection::getParent() const {
375   return cast_or_null<OutputSection>(Parent);
376 }
377 
378 // Copy SHT_GROUP section contents. Used only for the -r option.
copyShtGroup(uint8_t * Buf)379 template <class ELFT> void InputSection::copyShtGroup(uint8_t *Buf) {
380   // ELFT::Word is the 32-bit integral type in the target endianness.
381   typedef typename ELFT::Word u32;
382   ArrayRef<u32> From = getDataAs<u32>();
383   auto *To = reinterpret_cast<u32 *>(Buf);
384 
385   // The first entry is not a section number but a flag.
386   *To++ = From[0];
387 
388   // Adjust section numbers because section numbers in an input object
389   // files are different in the output.
390   ArrayRef<InputSectionBase *> Sections = File->getSections();
391   for (uint32_t Idx : From.slice(1))
392     *To++ = Sections[Idx]->getOutputSection()->SectionIndex;
393 }
394 
getRelocatedSection() const395 InputSectionBase *InputSection::getRelocatedSection() const {
396   if (!File || (Type != SHT_RELA && Type != SHT_REL))
397     return nullptr;
398   ArrayRef<InputSectionBase *> Sections = File->getSections();
399   return Sections[Info];
400 }
401 
402 // This is used for -r and --emit-relocs. We can't use memcpy to copy
403 // relocations because we need to update symbol table offset and section index
404 // for each relocation. So we copy relocations one by one.
405 template <class ELFT, class RelTy>
copyRelocations(uint8_t * Buf,ArrayRef<RelTy> Rels)406 void InputSection::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
407   InputSectionBase *Sec = getRelocatedSection();
408 
409   for (const RelTy &Rel : Rels) {
410     RelType Type = Rel.getType(Config->IsMips64EL);
411     Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel);
412 
413     auto *P = reinterpret_cast<typename ELFT::Rela *>(Buf);
414     Buf += sizeof(RelTy);
415 
416     if (RelTy::IsRela)
417       P->r_addend = getAddend<ELFT>(Rel);
418 
419     // Output section VA is zero for -r, so r_offset is an offset within the
420     // section, but for --emit-relocs it is an virtual address.
421     P->r_offset = Sec->getVA(Rel.r_offset);
422     P->setSymbolAndType(In.SymTab->getSymbolIndex(&Sym), Type,
423                         Config->IsMips64EL);
424 
425     if (Sym.Type == STT_SECTION) {
426       // We combine multiple section symbols into only one per
427       // section. This means we have to update the addend. That is
428       // trivial for Elf_Rela, but for Elf_Rel we have to write to the
429       // section data. We do that by adding to the Relocation vector.
430 
431       // .eh_frame is horribly special and can reference discarded sections. To
432       // avoid having to parse and recreate .eh_frame, we just replace any
433       // relocation in it pointing to discarded sections with R_*_NONE, which
434       // hopefully creates a frame that is ignored at runtime.
435       auto *D = dyn_cast<Defined>(&Sym);
436       if (!D) {
437         error("STT_SECTION symbol should be defined");
438         continue;
439       }
440       SectionBase *Section = D->Section->Repl;
441       if (!Section->Live) {
442         P->setSymbolAndType(0, 0, false);
443         continue;
444       }
445 
446       int64_t Addend = getAddend<ELFT>(Rel);
447       const uint8_t *BufLoc = Sec->data().begin() + Rel.r_offset;
448       if (!RelTy::IsRela)
449         Addend = Target->getImplicitAddend(BufLoc, Type);
450 
451       if (Config->EMachine == EM_MIPS && Config->Relocatable &&
452           Target->getRelExpr(Type, Sym, BufLoc) == R_MIPS_GOTREL) {
453         // Some MIPS relocations depend on "gp" value. By default,
454         // this value has 0x7ff0 offset from a .got section. But
455         // relocatable files produced by a complier or a linker
456         // might redefine this default value and we must use it
457         // for a calculation of the relocation result. When we
458         // generate EXE or DSO it's trivial. Generating a relocatable
459         // output is more difficult case because the linker does
460         // not calculate relocations in this mode and loses
461         // individual "gp" values used by each input object file.
462         // As a workaround we add the "gp" value to the relocation
463         // addend and save it back to the file.
464         Addend += Sec->getFile<ELFT>()->MipsGp0;
465       }
466 
467       if (RelTy::IsRela)
468         P->r_addend = Sym.getVA(Addend) - Section->getOutputSection()->Addr;
469       else if (Config->Relocatable)
470         Sec->Relocations.push_back({R_ABS, Type, Rel.r_offset, Addend, &Sym});
471     }
472   }
473 }
474 
475 // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
476 // references specially. The general rule is that the value of the symbol in
477 // this context is the address of the place P. A further special case is that
478 // branch relocations to an undefined weak reference resolve to the next
479 // instruction.
getARMUndefinedRelativeWeakVA(RelType Type,uint32_t A,uint32_t P)480 static uint32_t getARMUndefinedRelativeWeakVA(RelType Type, uint32_t A,
481                                               uint32_t P) {
482   switch (Type) {
483   // Unresolved branch relocations to weak references resolve to next
484   // instruction, this will be either 2 or 4 bytes on from P.
485   case R_ARM_THM_JUMP11:
486     return P + 2 + A;
487   case R_ARM_CALL:
488   case R_ARM_JUMP24:
489   case R_ARM_PC24:
490   case R_ARM_PLT32:
491   case R_ARM_PREL31:
492   case R_ARM_THM_JUMP19:
493   case R_ARM_THM_JUMP24:
494     return P + 4 + A;
495   case R_ARM_THM_CALL:
496     // We don't want an interworking BLX to ARM
497     return P + 5 + A;
498   // Unresolved non branch pc-relative relocations
499   // R_ARM_TARGET2 which can be resolved relatively is not present as it never
500   // targets a weak-reference.
501   case R_ARM_MOVW_PREL_NC:
502   case R_ARM_MOVT_PREL:
503   case R_ARM_REL32:
504   case R_ARM_THM_MOVW_PREL_NC:
505   case R_ARM_THM_MOVT_PREL:
506     return P + A;
507   }
508   llvm_unreachable("ARM pc-relative relocation expected\n");
509 }
510 
511 // The comment above getARMUndefinedRelativeWeakVA applies to this function.
getAArch64UndefinedRelativeWeakVA(uint64_t Type,uint64_t A,uint64_t P)512 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
513                                                   uint64_t P) {
514   switch (Type) {
515   // Unresolved branch relocations to weak references resolve to next
516   // instruction, this is 4 bytes on from P.
517   case R_AARCH64_CALL26:
518   case R_AARCH64_CONDBR19:
519   case R_AARCH64_JUMP26:
520   case R_AARCH64_TSTBR14:
521     return P + 4 + A;
522   // Unresolved non branch pc-relative relocations
523   case R_AARCH64_PREL16:
524   case R_AARCH64_PREL32:
525   case R_AARCH64_PREL64:
526   case R_AARCH64_ADR_PREL_LO21:
527   case R_AARCH64_LD_PREL_LO19:
528     return P + A;
529   }
530   llvm_unreachable("AArch64 pc-relative relocation expected\n");
531 }
532 
533 // ARM SBREL relocations are of the form S + A - B where B is the static base
534 // The ARM ABI defines base to be "addressing origin of the output segment
535 // defining the symbol S". We defined the "addressing origin"/static base to be
536 // the base of the PT_LOAD segment containing the Sym.
537 // The procedure call standard only defines a Read Write Position Independent
538 // RWPI variant so in practice we should expect the static base to be the base
539 // of the RW segment.
getARMStaticBase(const Symbol & Sym)540 static uint64_t getARMStaticBase(const Symbol &Sym) {
541   OutputSection *OS = Sym.getOutputSection();
542   if (!OS || !OS->PtLoad || !OS->PtLoad->FirstSec)
543     fatal("SBREL relocation to " + Sym.getName() + " without static base");
544   return OS->PtLoad->FirstSec->Addr;
545 }
546 
547 // For R_RISCV_PC_INDIRECT (R_RISCV_PCREL_LO12_{I,S}), the symbol actually
548 // points the corresponding R_RISCV_PCREL_HI20 relocation, and the target VA
549 // is calculated using PCREL_HI20's symbol.
550 //
551 // This function returns the R_RISCV_PCREL_HI20 relocation from
552 // R_RISCV_PCREL_LO12's symbol and addend.
getRISCVPCRelHi20(const Symbol * Sym,uint64_t Addend)553 static Relocation *getRISCVPCRelHi20(const Symbol *Sym, uint64_t Addend) {
554   const Defined *D = cast<Defined>(Sym);
555   InputSection *IS = cast<InputSection>(D->Section);
556 
557   if (Addend != 0)
558     warn("Non-zero addend in R_RISCV_PCREL_LO12 relocation to " +
559          IS->getObjMsg(D->Value) + " is ignored");
560 
561   // Relocations are sorted by offset, so we can use std::equal_range to do
562   // binary search.
563   auto Range = std::equal_range(IS->Relocations.begin(), IS->Relocations.end(),
564                                 D->Value, RelocationOffsetComparator{});
565   for (auto It = std::get<0>(Range); It != std::get<1>(Range); ++It)
566     if (isRelExprOneOf<R_PC>(It->Expr))
567       return &*It;
568 
569   error("R_RISCV_PCREL_LO12 relocation points to " + IS->getObjMsg(D->Value) +
570         " without an associated R_RISCV_PCREL_HI20 relocation");
571   return nullptr;
572 }
573 
574 // A TLS symbol's virtual address is relative to the TLS segment. Add a
575 // target-specific adjustment to produce a thread-pointer-relative offset.
getTlsTpOffset()576 static int64_t getTlsTpOffset() {
577   switch (Config->EMachine) {
578   case EM_ARM:
579   case EM_AARCH64:
580     // Variant 1. The thread pointer points to a TCB with a fixed 2-word size,
581     // followed by a variable amount of alignment padding, followed by the TLS
582     // segment.
583     return alignTo(Config->Wordsize * 2, Out::TlsPhdr->p_align);
584   case EM_386:
585   case EM_X86_64:
586     // Variant 2. The TLS segment is located just before the thread pointer.
587     return -Out::TlsPhdr->p_memsz;
588   case EM_PPC64:
589     // The thread pointer points to a fixed offset from the start of the
590     // executable's TLS segment. An offset of 0x7000 allows a signed 16-bit
591     // offset to reach 0x1000 of TCB/thread-library data and 0xf000 of the
592     // program's TLS segment.
593     return -0x7000;
594   default:
595     llvm_unreachable("unhandled Config->EMachine");
596   }
597 }
598 
getRelocTargetVA(const InputFile * File,RelType Type,int64_t A,uint64_t P,const Symbol & Sym,RelExpr Expr)599 static uint64_t getRelocTargetVA(const InputFile *File, RelType Type, int64_t A,
600                                  uint64_t P, const Symbol &Sym, RelExpr Expr) {
601   switch (Expr) {
602   case R_INVALID:
603     return 0;
604   case R_ABS:
605   case R_RELAX_TLS_LD_TO_LE_ABS:
606   case R_RELAX_GOT_PC_NOPIC:
607     return Sym.getVA(A);
608   case R_ADDEND:
609     return A;
610   case R_ARM_SBREL:
611     return Sym.getVA(A) - getARMStaticBase(Sym);
612   case R_GOT:
613   case R_GOT_PLT:
614   case R_RELAX_TLS_GD_TO_IE_ABS:
615     return Sym.getGotVA() + A;
616   case R_GOTONLY_PC:
617     return In.Got->getVA() + A - P;
618   case R_GOTONLY_PC_FROM_END:
619     return In.Got->getVA() + A - P + In.Got->getSize();
620   case R_GOTREL:
621     return Sym.getVA(A) - In.Got->getVA();
622   case R_GOTREL_FROM_END:
623     return Sym.getVA(A) - In.Got->getVA() - In.Got->getSize();
624   case R_GOT_FROM_END:
625   case R_RELAX_TLS_GD_TO_IE_END:
626     return Sym.getGotOffset() + A - In.Got->getSize();
627   case R_TLSLD_GOT_OFF:
628   case R_GOT_OFF:
629   case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
630     return Sym.getGotOffset() + A;
631   case R_AARCH64_GOT_PAGE_PC:
632   case R_AARCH64_GOT_PAGE_PC_PLT:
633   case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
634     return getAArch64Page(Sym.getGotVA() + A) - getAArch64Page(P);
635   case R_GOT_PC:
636   case R_RELAX_TLS_GD_TO_IE:
637     return Sym.getGotVA() + A - P;
638   case R_HEXAGON_GOT:
639     return Sym.getGotVA() - In.GotPlt->getVA();
640   case R_MIPS_GOTREL:
641     return Sym.getVA(A) - In.MipsGot->getGp(File);
642   case R_MIPS_GOT_GP:
643     return In.MipsGot->getGp(File) + A;
644   case R_MIPS_GOT_GP_PC: {
645     // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
646     // is _gp_disp symbol. In that case we should use the following
647     // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
648     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
649     // microMIPS variants of these relocations use slightly different
650     // expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi()
651     // to correctly handle less-sugnificant bit of the microMIPS symbol.
652     uint64_t V = In.MipsGot->getGp(File) + A - P;
653     if (Type == R_MIPS_LO16 || Type == R_MICROMIPS_LO16)
654       V += 4;
655     if (Type == R_MICROMIPS_LO16 || Type == R_MICROMIPS_HI16)
656       V -= 1;
657     return V;
658   }
659   case R_MIPS_GOT_LOCAL_PAGE:
660     // If relocation against MIPS local symbol requires GOT entry, this entry
661     // should be initialized by 'page address'. This address is high 16-bits
662     // of sum the symbol's value and the addend.
663     return In.MipsGot->getVA() + In.MipsGot->getPageEntryOffset(File, Sym, A) -
664            In.MipsGot->getGp(File);
665   case R_MIPS_GOT_OFF:
666   case R_MIPS_GOT_OFF32:
667     // In case of MIPS if a GOT relocation has non-zero addend this addend
668     // should be applied to the GOT entry content not to the GOT entry offset.
669     // That is why we use separate expression type.
670     return In.MipsGot->getVA() + In.MipsGot->getSymEntryOffset(File, Sym, A) -
671            In.MipsGot->getGp(File);
672   case R_MIPS_TLSGD:
673     return In.MipsGot->getVA() + In.MipsGot->getGlobalDynOffset(File, Sym) -
674            In.MipsGot->getGp(File);
675   case R_MIPS_TLSLD:
676     return In.MipsGot->getVA() + In.MipsGot->getTlsIndexOffset(File) -
677            In.MipsGot->getGp(File);
678   case R_AARCH64_PAGE_PC: {
679     uint64_t Val = Sym.isUndefWeak() ? P + A : Sym.getVA(A);
680     return getAArch64Page(Val) - getAArch64Page(P);
681   }
682   case R_AARCH64_PLT_PAGE_PC: {
683     uint64_t Val = Sym.isUndefWeak() ? P + A : Sym.getPltVA() + A;
684     return getAArch64Page(Val) - getAArch64Page(P);
685   }
686   case R_RISCV_PC_INDIRECT: {
687     if (const Relocation *HiRel = getRISCVPCRelHi20(&Sym, A))
688       return getRelocTargetVA(File, HiRel->Type, HiRel->Addend, Sym.getVA(),
689                               *HiRel->Sym, HiRel->Expr);
690     return 0;
691   }
692   case R_PC: {
693     uint64_t Dest;
694     if (Sym.isUndefWeak()) {
695       // On ARM and AArch64 a branch to an undefined weak resolves to the
696       // next instruction, otherwise the place.
697       if (Config->EMachine == EM_ARM)
698         Dest = getARMUndefinedRelativeWeakVA(Type, A, P);
699       else if (Config->EMachine == EM_AARCH64)
700         Dest = getAArch64UndefinedRelativeWeakVA(Type, A, P);
701       else
702         Dest = Sym.getVA(A);
703     } else {
704       Dest = Sym.getVA(A);
705     }
706     return Dest - P;
707   }
708   case R_PLT:
709     return Sym.getPltVA() + A;
710   case R_PLT_PC:
711   case R_PPC_CALL_PLT:
712     return Sym.getPltVA() + A - P;
713   case R_PPC_CALL: {
714     uint64_t SymVA = Sym.getVA(A);
715     // If we have an undefined weak symbol, we might get here with a symbol
716     // address of zero. That could overflow, but the code must be unreachable,
717     // so don't bother doing anything at all.
718     if (!SymVA)
719       return 0;
720 
721     // PPC64 V2 ABI describes two entry points to a function. The global entry
722     // point is used for calls where the caller and callee (may) have different
723     // TOC base pointers and r2 needs to be modified to hold the TOC base for
724     // the callee. For local calls the caller and callee share the same
725     // TOC base and so the TOC pointer initialization code should be skipped by
726     // branching to the local entry point.
727     return SymVA - P + getPPC64GlobalEntryToLocalEntryOffset(Sym.StOther);
728   }
729   case R_PPC_TOC:
730     return getPPC64TocBase() + A;
731   case R_RELAX_GOT_PC:
732     return Sym.getVA(A) - P;
733   case R_RELAX_TLS_GD_TO_LE:
734   case R_RELAX_TLS_IE_TO_LE:
735   case R_RELAX_TLS_LD_TO_LE:
736   case R_TLS:
737     // A weak undefined TLS symbol resolves to the base of the TLS
738     // block, i.e. gets a value of zero. If we pass --gc-sections to
739     // lld and .tbss is not referenced, it gets reclaimed and we don't
740     // create a TLS program header. Therefore, we resolve this
741     // statically to zero.
742     if (Sym.isTls() && Sym.isUndefWeak())
743       return 0;
744     return Sym.getVA(A) + getTlsTpOffset();
745   case R_RELAX_TLS_GD_TO_LE_NEG:
746   case R_NEG_TLS:
747     return Out::TlsPhdr->p_memsz - Sym.getVA(A);
748   case R_SIZE:
749     return Sym.getSize() + A;
750   case R_TLSDESC:
751     return In.Got->getGlobalDynAddr(Sym) + A;
752   case R_AARCH64_TLSDESC_PAGE:
753     return getAArch64Page(In.Got->getGlobalDynAddr(Sym) + A) -
754            getAArch64Page(P);
755   case R_TLSGD_GOT:
756     return In.Got->getGlobalDynOffset(Sym) + A;
757   case R_TLSGD_GOT_FROM_END:
758     return In.Got->getGlobalDynOffset(Sym) + A - In.Got->getSize();
759   case R_TLSGD_PC:
760     return In.Got->getGlobalDynAddr(Sym) + A - P;
761   case R_TLSLD_GOT_FROM_END:
762     return In.Got->getTlsIndexOff() + A - In.Got->getSize();
763   case R_TLSLD_GOT:
764     return In.Got->getTlsIndexOff() + A;
765   case R_TLSLD_PC:
766     return In.Got->getTlsIndexVA() + A - P;
767   default:
768     llvm_unreachable("invalid expression");
769   }
770 }
771 
772 // This function applies relocations to sections without SHF_ALLOC bit.
773 // Such sections are never mapped to memory at runtime. Debug sections are
774 // an example. Relocations in non-alloc sections are much easier to
775 // handle than in allocated sections because it will never need complex
776 // treatement such as GOT or PLT (because at runtime no one refers them).
777 // So, we handle relocations for non-alloc sections directly in this
778 // function as a performance optimization.
779 template <class ELFT, class RelTy>
relocateNonAlloc(uint8_t * Buf,ArrayRef<RelTy> Rels)780 void InputSection::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
781   const unsigned Bits = sizeof(typename ELFT::uint) * 8;
782 
783   for (const RelTy &Rel : Rels) {
784     RelType Type = Rel.getType(Config->IsMips64EL);
785 
786     // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations
787     // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed
788     // in 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we
789     // need to keep this bug-compatible code for a while.
790     if (Config->EMachine == EM_386 && Type == R_386_GOTPC)
791       continue;
792 
793     uint64_t Offset = getOffset(Rel.r_offset);
794     uint8_t *BufLoc = Buf + Offset;
795     int64_t Addend = getAddend<ELFT>(Rel);
796     if (!RelTy::IsRela)
797       Addend += Target->getImplicitAddend(BufLoc, Type);
798 
799     Symbol &Sym = getFile<ELFT>()->getRelocTargetSym(Rel);
800     RelExpr Expr = Target->getRelExpr(Type, Sym, BufLoc);
801     if (Expr == R_NONE)
802       continue;
803 
804     if (Expr != R_ABS) {
805       std::string Msg = getLocation<ELFT>(Offset) +
806                         ": has non-ABS relocation " + toString(Type) +
807                         " against symbol '" + toString(Sym) + "'";
808       if (Expr != R_PC) {
809         error(Msg);
810         return;
811       }
812 
813       // If the control reaches here, we found a PC-relative relocation in a
814       // non-ALLOC section. Since non-ALLOC section is not loaded into memory
815       // at runtime, the notion of PC-relative doesn't make sense here. So,
816       // this is a usage error. However, GNU linkers historically accept such
817       // relocations without any errors and relocate them as if they were at
818       // address 0. For bug-compatibilty, we accept them with warnings. We
819       // know Steel Bank Common Lisp as of 2018 have this bug.
820       warn(Msg);
821       Target->relocateOne(BufLoc, Type,
822                           SignExtend64<Bits>(Sym.getVA(Addend - Offset)));
823       continue;
824     }
825 
826     if (Sym.isTls() && !Out::TlsPhdr)
827       Target->relocateOne(BufLoc, Type, 0);
828     else
829       Target->relocateOne(BufLoc, Type, SignExtend64<Bits>(Sym.getVA(Addend)));
830   }
831 }
832 
833 // This is used when '-r' is given.
834 // For REL targets, InputSection::copyRelocations() may store artificial
835 // relocations aimed to update addends. They are handled in relocateAlloc()
836 // for allocatable sections, and this function does the same for
837 // non-allocatable sections, such as sections with debug information.
relocateNonAllocForRelocatable(InputSection * Sec,uint8_t * Buf)838 static void relocateNonAllocForRelocatable(InputSection *Sec, uint8_t *Buf) {
839   const unsigned Bits = Config->Is64 ? 64 : 32;
840 
841   for (const Relocation &Rel : Sec->Relocations) {
842     // InputSection::copyRelocations() adds only R_ABS relocations.
843     assert(Rel.Expr == R_ABS);
844     uint8_t *BufLoc = Buf + Rel.Offset + Sec->OutSecOff;
845     uint64_t TargetVA = SignExtend64(Rel.Sym->getVA(Rel.Addend), Bits);
846     Target->relocateOne(BufLoc, Rel.Type, TargetVA);
847   }
848 }
849 
850 template <class ELFT>
relocate(uint8_t * Buf,uint8_t * BufEnd)851 void InputSectionBase::relocate(uint8_t *Buf, uint8_t *BufEnd) {
852   if (Flags & SHF_EXECINSTR)
853     adjustSplitStackFunctionPrologues<ELFT>(Buf, BufEnd);
854 
855   if (Flags & SHF_ALLOC) {
856     relocateAlloc(Buf, BufEnd);
857     return;
858   }
859 
860   auto *Sec = cast<InputSection>(this);
861   if (Config->Relocatable)
862     relocateNonAllocForRelocatable(Sec, Buf);
863   else if (Sec->AreRelocsRela)
864     Sec->relocateNonAlloc<ELFT>(Buf, Sec->template relas<ELFT>());
865   else
866     Sec->relocateNonAlloc<ELFT>(Buf, Sec->template rels<ELFT>());
867 }
868 
relocateAlloc(uint8_t * Buf,uint8_t * BufEnd)869 void InputSectionBase::relocateAlloc(uint8_t *Buf, uint8_t *BufEnd) {
870   assert(Flags & SHF_ALLOC);
871   const unsigned Bits = Config->Wordsize * 8;
872 
873   for (const Relocation &Rel : Relocations) {
874     uint64_t Offset = Rel.Offset;
875     if (auto *Sec = dyn_cast<InputSection>(this))
876       Offset += Sec->OutSecOff;
877     uint8_t *BufLoc = Buf + Offset;
878     RelType Type = Rel.Type;
879 
880     uint64_t AddrLoc = getOutputSection()->Addr + Offset;
881     RelExpr Expr = Rel.Expr;
882     uint64_t TargetVA = SignExtend64(
883         getRelocTargetVA(File, Type, Rel.Addend, AddrLoc, *Rel.Sym, Expr),
884         Bits);
885 
886     switch (Expr) {
887     case R_RELAX_GOT_PC:
888     case R_RELAX_GOT_PC_NOPIC:
889       Target->relaxGot(BufLoc, TargetVA);
890       break;
891     case R_RELAX_TLS_IE_TO_LE:
892       Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
893       break;
894     case R_RELAX_TLS_LD_TO_LE:
895     case R_RELAX_TLS_LD_TO_LE_ABS:
896       Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
897       break;
898     case R_RELAX_TLS_GD_TO_LE:
899     case R_RELAX_TLS_GD_TO_LE_NEG:
900       Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
901       break;
902     case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
903     case R_RELAX_TLS_GD_TO_IE:
904     case R_RELAX_TLS_GD_TO_IE_ABS:
905     case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
906     case R_RELAX_TLS_GD_TO_IE_END:
907       Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
908       break;
909     case R_PPC_CALL:
910       // If this is a call to __tls_get_addr, it may be part of a TLS
911       // sequence that has been relaxed and turned into a nop. In this
912       // case, we don't want to handle it as a call.
913       if (read32(BufLoc) == 0x60000000) // nop
914         break;
915 
916       // Patch a nop (0x60000000) to a ld.
917       if (Rel.Sym->NeedsTocRestore) {
918         if (BufLoc + 8 > BufEnd || read32(BufLoc + 4) != 0x60000000) {
919           error(getErrorLocation(BufLoc) + "call lacks nop, can't restore toc");
920           break;
921         }
922         write32(BufLoc + 4, 0xe8410018); // ld %r2, 24(%r1)
923       }
924       Target->relocateOne(BufLoc, Type, TargetVA);
925       break;
926     default:
927       Target->relocateOne(BufLoc, Type, TargetVA);
928       break;
929     }
930   }
931 }
932 
933 // For each function-defining prologue, find any calls to __morestack,
934 // and replace them with calls to __morestack_non_split.
switchMorestackCallsToMorestackNonSplit(DenseSet<Defined * > & Prologues,std::vector<Relocation * > & MorestackCalls)935 static void switchMorestackCallsToMorestackNonSplit(
936     DenseSet<Defined *> &Prologues, std::vector<Relocation *> &MorestackCalls) {
937 
938   // If the target adjusted a function's prologue, all calls to
939   // __morestack inside that function should be switched to
940   // __morestack_non_split.
941   Symbol *MoreStackNonSplit = Symtab->find("__morestack_non_split");
942   if (!MoreStackNonSplit) {
943     error("Mixing split-stack objects requires a definition of "
944           "__morestack_non_split");
945     return;
946   }
947 
948   // Sort both collections to compare addresses efficiently.
949   llvm::sort(MorestackCalls, [](const Relocation *L, const Relocation *R) {
950     return L->Offset < R->Offset;
951   });
952   std::vector<Defined *> Functions(Prologues.begin(), Prologues.end());
953   llvm::sort(Functions, [](const Defined *L, const Defined *R) {
954     return L->Value < R->Value;
955   });
956 
957   auto It = MorestackCalls.begin();
958   for (Defined *F : Functions) {
959     // Find the first call to __morestack within the function.
960     while (It != MorestackCalls.end() && (*It)->Offset < F->Value)
961       ++It;
962     // Adjust all calls inside the function.
963     while (It != MorestackCalls.end() && (*It)->Offset < F->Value + F->Size) {
964       (*It)->Sym = MoreStackNonSplit;
965       ++It;
966     }
967   }
968 }
969 
enclosingPrologueAttempted(uint64_t Offset,const DenseSet<Defined * > & Prologues)970 static bool enclosingPrologueAttempted(uint64_t Offset,
971                                        const DenseSet<Defined *> &Prologues) {
972   for (Defined *F : Prologues)
973     if (F->Value <= Offset && Offset < F->Value + F->Size)
974       return true;
975   return false;
976 }
977 
978 // If a function compiled for split stack calls a function not
979 // compiled for split stack, then the caller needs its prologue
980 // adjusted to ensure that the called function will have enough stack
981 // available. Find those functions, and adjust their prologues.
982 template <class ELFT>
adjustSplitStackFunctionPrologues(uint8_t * Buf,uint8_t * End)983 void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *Buf,
984                                                          uint8_t *End) {
985   if (!getFile<ELFT>()->SplitStack)
986     return;
987   DenseSet<Defined *> Prologues;
988   std::vector<Relocation *> MorestackCalls;
989 
990   for (Relocation &Rel : Relocations) {
991     // Local symbols can't possibly be cross-calls, and should have been
992     // resolved long before this line.
993     if (Rel.Sym->isLocal())
994       continue;
995 
996     // Ignore calls into the split-stack api.
997     if (Rel.Sym->getName().startswith("__morestack")) {
998       if (Rel.Sym->getName().equals("__morestack"))
999         MorestackCalls.push_back(&Rel);
1000       continue;
1001     }
1002 
1003     // A relocation to non-function isn't relevant. Sometimes
1004     // __morestack is not marked as a function, so this check comes
1005     // after the name check.
1006     if (Rel.Sym->Type != STT_FUNC)
1007       continue;
1008 
1009     // If the callee's-file was compiled with split stack, nothing to do.  In
1010     // this context, a "Defined" symbol is one "defined by the binary currently
1011     // being produced". So an "undefined" symbol might be provided by a shared
1012     // library. It is not possible to tell how such symbols were compiled, so be
1013     // conservative.
1014     if (Defined *D = dyn_cast<Defined>(Rel.Sym))
1015       if (InputSection *IS = cast_or_null<InputSection>(D->Section))
1016         if (!IS || !IS->getFile<ELFT>() || IS->getFile<ELFT>()->SplitStack)
1017           continue;
1018 
1019     if (enclosingPrologueAttempted(Rel.Offset, Prologues))
1020       continue;
1021 
1022     if (Defined *F = getEnclosingFunction<ELFT>(Rel.Offset)) {
1023       Prologues.insert(F);
1024       if (Target->adjustPrologueForCrossSplitStack(Buf + getOffset(F->Value),
1025                                                    End, F->StOther))
1026         continue;
1027       if (!getFile<ELFT>()->SomeNoSplitStack)
1028         error(lld::toString(this) + ": " + F->getName() +
1029               " (with -fsplit-stack) calls " + Rel.Sym->getName() +
1030               " (without -fsplit-stack), but couldn't adjust its prologue");
1031     }
1032   }
1033 
1034   if (Target->NeedsMoreStackNonSplit)
1035     switchMorestackCallsToMorestackNonSplit(Prologues, MorestackCalls);
1036 }
1037 
writeTo(uint8_t * Buf)1038 template <class ELFT> void InputSection::writeTo(uint8_t *Buf) {
1039   if (Type == SHT_NOBITS)
1040     return;
1041 
1042   if (auto *S = dyn_cast<SyntheticSection>(this)) {
1043     S->writeTo(Buf + OutSecOff);
1044     return;
1045   }
1046 
1047   // If -r or --emit-relocs is given, then an InputSection
1048   // may be a relocation section.
1049   if (Type == SHT_RELA) {
1050     copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rela>());
1051     return;
1052   }
1053   if (Type == SHT_REL) {
1054     copyRelocations<ELFT>(Buf + OutSecOff, getDataAs<typename ELFT::Rel>());
1055     return;
1056   }
1057 
1058   // If -r is given, we may have a SHT_GROUP section.
1059   if (Type == SHT_GROUP) {
1060     copyShtGroup<ELFT>(Buf + OutSecOff);
1061     return;
1062   }
1063 
1064   // If this is a compressed section, uncompress section contents directly
1065   // to the buffer.
1066   if (UncompressedSize >= 0 && !UncompressedBuf) {
1067     size_t Size = UncompressedSize;
1068     if (Error E = zlib::uncompress(toStringRef(RawData),
1069                                    (char *)(Buf + OutSecOff), Size))
1070       fatal(toString(this) +
1071             ": uncompress failed: " + llvm::toString(std::move(E)));
1072     uint8_t *BufEnd = Buf + OutSecOff + Size;
1073     relocate<ELFT>(Buf, BufEnd);
1074     return;
1075   }
1076 
1077   // Copy section contents from source object file to output file
1078   // and then apply relocations.
1079   memcpy(Buf + OutSecOff, data().data(), data().size());
1080   uint8_t *BufEnd = Buf + OutSecOff + data().size();
1081   relocate<ELFT>(Buf, BufEnd);
1082 }
1083 
replace(InputSection * Other)1084 void InputSection::replace(InputSection *Other) {
1085   Alignment = std::max(Alignment, Other->Alignment);
1086   Other->Repl = Repl;
1087   Other->Live = false;
1088 }
1089 
1090 template <class ELFT>
EhInputSection(ObjFile<ELFT> & F,const typename ELFT::Shdr & Header,StringRef Name)1091 EhInputSection::EhInputSection(ObjFile<ELFT> &F,
1092                                const typename ELFT::Shdr &Header,
1093                                StringRef Name)
1094     : InputSectionBase(F, Header, Name, InputSectionBase::EHFrame) {}
1095 
getParent() const1096 SyntheticSection *EhInputSection::getParent() const {
1097   return cast_or_null<SyntheticSection>(Parent);
1098 }
1099 
1100 // Returns the index of the first relocation that points to a region between
1101 // Begin and Begin+Size.
1102 template <class IntTy, class RelTy>
getReloc(IntTy Begin,IntTy Size,const ArrayRef<RelTy> & Rels,unsigned & RelocI)1103 static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
1104                          unsigned &RelocI) {
1105   // Start search from RelocI for fast access. That works because the
1106   // relocations are sorted in .eh_frame.
1107   for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
1108     const RelTy &Rel = Rels[RelocI];
1109     if (Rel.r_offset < Begin)
1110       continue;
1111 
1112     if (Rel.r_offset < Begin + Size)
1113       return RelocI;
1114     return -1;
1115   }
1116   return -1;
1117 }
1118 
1119 // .eh_frame is a sequence of CIE or FDE records.
1120 // This function splits an input section into records and returns them.
split()1121 template <class ELFT> void EhInputSection::split() {
1122   if (AreRelocsRela)
1123     split<ELFT>(relas<ELFT>());
1124   else
1125     split<ELFT>(rels<ELFT>());
1126 }
1127 
1128 template <class ELFT, class RelTy>
split(ArrayRef<RelTy> Rels)1129 void EhInputSection::split(ArrayRef<RelTy> Rels) {
1130   unsigned RelI = 0;
1131   for (size_t Off = 0, End = data().size(); Off != End;) {
1132     size_t Size = readEhRecordSize(this, Off);
1133     Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
1134     // The empty record is the end marker.
1135     if (Size == 4)
1136       break;
1137     Off += Size;
1138   }
1139 }
1140 
findNull(StringRef S,size_t EntSize)1141 static size_t findNull(StringRef S, size_t EntSize) {
1142   // Optimize the common case.
1143   if (EntSize == 1)
1144     return S.find(0);
1145 
1146   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
1147     const char *B = S.begin() + I;
1148     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
1149       return I;
1150   }
1151   return StringRef::npos;
1152 }
1153 
getParent() const1154 SyntheticSection *MergeInputSection::getParent() const {
1155   return cast_or_null<SyntheticSection>(Parent);
1156 }
1157 
1158 // Split SHF_STRINGS section. Such section is a sequence of
1159 // null-terminated strings.
splitStrings(ArrayRef<uint8_t> Data,size_t EntSize)1160 void MergeInputSection::splitStrings(ArrayRef<uint8_t> Data, size_t EntSize) {
1161   size_t Off = 0;
1162   bool IsAlloc = Flags & SHF_ALLOC;
1163   StringRef S = toStringRef(Data);
1164 
1165   while (!S.empty()) {
1166     size_t End = findNull(S, EntSize);
1167     if (End == StringRef::npos)
1168       fatal(toString(this) + ": string is not null terminated");
1169     size_t Size = End + EntSize;
1170 
1171     Pieces.emplace_back(Off, xxHash64(S.substr(0, Size)), !IsAlloc);
1172     S = S.substr(Size);
1173     Off += Size;
1174   }
1175 }
1176 
1177 // Split non-SHF_STRINGS section. Such section is a sequence of
1178 // fixed size records.
splitNonStrings(ArrayRef<uint8_t> Data,size_t EntSize)1179 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> Data,
1180                                         size_t EntSize) {
1181   size_t Size = Data.size();
1182   assert((Size % EntSize) == 0);
1183   bool IsAlloc = Flags & SHF_ALLOC;
1184 
1185   for (size_t I = 0; I != Size; I += EntSize)
1186     Pieces.emplace_back(I, xxHash64(Data.slice(I, EntSize)), !IsAlloc);
1187 }
1188 
1189 template <class ELFT>
MergeInputSection(ObjFile<ELFT> & F,const typename ELFT::Shdr & Header,StringRef Name)1190 MergeInputSection::MergeInputSection(ObjFile<ELFT> &F,
1191                                      const typename ELFT::Shdr &Header,
1192                                      StringRef Name)
1193     : InputSectionBase(F, Header, Name, InputSectionBase::Merge) {}
1194 
MergeInputSection(uint64_t Flags,uint32_t Type,uint64_t Entsize,ArrayRef<uint8_t> Data,StringRef Name)1195 MergeInputSection::MergeInputSection(uint64_t Flags, uint32_t Type,
1196                                      uint64_t Entsize, ArrayRef<uint8_t> Data,
1197                                      StringRef Name)
1198     : InputSectionBase(nullptr, Flags, Type, Entsize, /*Link*/ 0, /*Info*/ 0,
1199                        /*Alignment*/ Entsize, Data, Name, SectionBase::Merge) {}
1200 
1201 // This function is called after we obtain a complete list of input sections
1202 // that need to be linked. This is responsible to split section contents
1203 // into small chunks for further processing.
1204 //
1205 // Note that this function is called from parallelForEach. This must be
1206 // thread-safe (i.e. no memory allocation from the pools).
splitIntoPieces()1207 void MergeInputSection::splitIntoPieces() {
1208   assert(Pieces.empty());
1209 
1210   if (Flags & SHF_STRINGS)
1211     splitStrings(data(), Entsize);
1212   else
1213     splitNonStrings(data(), Entsize);
1214 }
1215 
getSectionPiece(uint64_t Offset)1216 SectionPiece *MergeInputSection::getSectionPiece(uint64_t Offset) {
1217   if (this->data().size() <= Offset)
1218     fatal(toString(this) + ": offset is outside the section");
1219 
1220   // If Offset is not at beginning of a section piece, it is not in the map.
1221   // In that case we need to  do a binary search of the original section piece vector.
1222   auto It2 =
1223       llvm::upper_bound(Pieces, Offset, [](uint64_t Offset, SectionPiece P) {
1224         return Offset < P.InputOff;
1225       });
1226   return &It2[-1];
1227 }
1228 
1229 // Returns the offset in an output section for a given input offset.
1230 // Because contents of a mergeable section is not contiguous in output,
1231 // it is not just an addition to a base output offset.
getParentOffset(uint64_t Offset) const1232 uint64_t MergeInputSection::getParentOffset(uint64_t Offset) const {
1233   // If Offset is not at beginning of a section piece, it is not in the map.
1234   // In that case we need to search from the original section piece vector.
1235   const SectionPiece &Piece =
1236       *(const_cast<MergeInputSection *>(this)->getSectionPiece (Offset));
1237   uint64_t Addend = Offset - Piece.InputOff;
1238   return Piece.OutputOff + Addend;
1239 }
1240 
1241 template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
1242                                     StringRef);
1243 template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
1244                                     StringRef);
1245 template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
1246                                     StringRef);
1247 template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
1248                                     StringRef);
1249 
1250 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
1251 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
1252 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
1253 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
1254 
1255 template void InputSection::writeTo<ELF32LE>(uint8_t *);
1256 template void InputSection::writeTo<ELF32BE>(uint8_t *);
1257 template void InputSection::writeTo<ELF64LE>(uint8_t *);
1258 template void InputSection::writeTo<ELF64BE>(uint8_t *);
1259 
1260 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
1261                                               const ELF32LE::Shdr &, StringRef);
1262 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
1263                                               const ELF32BE::Shdr &, StringRef);
1264 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
1265                                               const ELF64LE::Shdr &, StringRef);
1266 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
1267                                               const ELF64BE::Shdr &, StringRef);
1268 
1269 template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
1270                                         const ELF32LE::Shdr &, StringRef);
1271 template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
1272                                         const ELF32BE::Shdr &, StringRef);
1273 template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
1274                                         const ELF64LE::Shdr &, StringRef);
1275 template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
1276                                         const ELF64BE::Shdr &, StringRef);
1277 
1278 template void EhInputSection::split<ELF32LE>();
1279 template void EhInputSection::split<ELF32BE>();
1280 template void EhInputSection::split<ELF64LE>();
1281 template void EhInputSection::split<ELF64BE>();
1282