InputSection.cpp revision 319955
1//===- InputSection.cpp ---------------------------------------------------===//
2//
3//                             The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "InputSection.h"
11#include "Config.h"
12#include "EhFrame.h"
13#include "Error.h"
14#include "InputFiles.h"
15#include "LinkerScript.h"
16#include "Memory.h"
17#include "OutputSections.h"
18#include "Relocations.h"
19#include "SyntheticSections.h"
20#include "Target.h"
21#include "Thunks.h"
22#include "llvm/Object/Decompressor.h"
23#include "llvm/Support/Compression.h"
24#include "llvm/Support/Endian.h"
25#include <mutex>
26
27using namespace llvm;
28using namespace llvm::ELF;
29using namespace llvm::object;
30using namespace llvm::support;
31using namespace llvm::support::endian;
32
33using namespace lld;
34using namespace lld::elf;
35
36// Returns a string to construct an error message.
37template <class ELFT>
38std::string lld::toString(const InputSectionBase<ELFT> *Sec) {
39  // File can be absent if section is synthetic.
40  std::string FileName =
41      Sec->getFile() ? Sec->getFile()->getName() : "<internal>";
42  return (FileName + ":(" + Sec->Name + ")").str();
43}
44
45template <class ELFT>
46static ArrayRef<uint8_t> getSectionContents(elf::ObjectFile<ELFT> *File,
47                                            const typename ELFT::Shdr *Hdr) {
48  if (!File || Hdr->sh_type == SHT_NOBITS)
49    return makeArrayRef<uint8_t>(nullptr, Hdr->sh_size);
50  return check(File->getObj().getSectionContents(Hdr));
51}
52
53template <class ELFT>
54InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
55                                         uintX_t Flags, uint32_t Type,
56                                         uintX_t Entsize, uint32_t Link,
57                                         uint32_t Info, uintX_t Addralign,
58                                         ArrayRef<uint8_t> Data, StringRef Name,
59                                         Kind SectionKind)
60    : InputSectionData(SectionKind, Name, Data,
61                       !Config->GcSections || !(Flags & SHF_ALLOC)),
62      File(File), Flags(Flags), Entsize(Entsize), Type(Type), Link(Link),
63      Info(Info), Repl(this) {
64  NumRelocations = 0;
65  AreRelocsRela = false;
66
67  // The ELF spec states that a value of 0 means the section has
68  // no alignment constraits.
69  uint64_t V = std::max<uint64_t>(Addralign, 1);
70  if (!isPowerOf2_64(V))
71    fatal(toString(File) + ": section sh_addralign is not a power of 2");
72
73  // We reject object files having insanely large alignments even though
74  // they are allowed by the spec. I think 4GB is a reasonable limitation.
75  // We might want to relax this in the future.
76  if (V > UINT32_MAX)
77    fatal(toString(File) + ": section sh_addralign is too large");
78  Alignment = V;
79
80  // If it is not a mergeable section, overwrite the flag so that the flag
81  // is consistent with the class. This inconsistency could occur when
82  // string merging is disabled using -O0 flag.
83  if (!Config->Relocatable && !isa<MergeInputSection<ELFT>>(this))
84    this->Flags &= ~(SHF_MERGE | SHF_STRINGS);
85}
86
87template <class ELFT>
88InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
89                                         const Elf_Shdr *Hdr, StringRef Name,
90                                         Kind SectionKind)
91    : InputSectionBase(File, Hdr->sh_flags & ~SHF_INFO_LINK, Hdr->sh_type,
92                       Hdr->sh_entsize, Hdr->sh_link, Hdr->sh_info,
93                       Hdr->sh_addralign, getSectionContents(File, Hdr), Name,
94                       SectionKind) {
95  this->Offset = Hdr->sh_offset;
96}
97
98template <class ELFT> size_t InputSectionBase<ELFT>::getSize() const {
99  if (auto *S = dyn_cast<SyntheticSection<ELFT>>(this))
100    return S->getSize();
101
102  if (auto *D = dyn_cast<InputSection<ELFT>>(this))
103    if (D->getThunksSize() > 0)
104      return D->getThunkOff() + D->getThunksSize();
105
106  return Data.size();
107}
108
109template <class ELFT>
110typename ELFT::uint InputSectionBase<ELFT>::getOffset(uintX_t Offset) const {
111  switch (kind()) {
112  case Regular:
113    return cast<InputSection<ELFT>>(this)->OutSecOff + Offset;
114  case Synthetic:
115    // For synthetic sections we treat offset -1 as the end of the section.
116    // The same approach is used for synthetic symbols (DefinedSynthetic).
117    return cast<InputSection<ELFT>>(this)->OutSecOff +
118           (Offset == uintX_t(-1) ? getSize() : Offset);
119  case EHFrame:
120    // The file crtbeginT.o has relocations pointing to the start of an empty
121    // .eh_frame that is known to be the first in the link. It does that to
122    // identify the start of the output .eh_frame.
123    return Offset;
124  case Merge:
125    return cast<MergeInputSection<ELFT>>(this)->getOffset(Offset);
126  }
127  llvm_unreachable("invalid section kind");
128}
129
130// Uncompress section contents. Note that this function is called
131// from parallel_for_each, so it must be thread-safe.
132template <class ELFT> void InputSectionBase<ELFT>::uncompress() {
133  Decompressor Decompressor = check(Decompressor::create(
134      Name, toStringRef(Data), ELFT::TargetEndianness == llvm::support::little,
135      ELFT::Is64Bits));
136
137  size_t Size = Decompressor.getDecompressedSize();
138  char *OutputBuf;
139  {
140    static std::mutex Mu;
141    std::lock_guard<std::mutex> Lock(Mu);
142    OutputBuf = BAlloc.Allocate<char>(Size);
143  }
144
145  if (Error E = Decompressor.decompress({OutputBuf, Size}))
146    fatal(E, toString(this));
147  Data = ArrayRef<uint8_t>((uint8_t *)OutputBuf, Size);
148}
149
150template <class ELFT>
151typename ELFT::uint
152InputSectionBase<ELFT>::getOffset(const DefinedRegular<ELFT> &Sym) const {
153  return getOffset(Sym.Value);
154}
155
156template <class ELFT>
157InputSectionBase<ELFT> *InputSectionBase<ELFT>::getLinkOrderDep() const {
158  if ((Flags & SHF_LINK_ORDER) && Link != 0)
159    return getFile()->getSections()[Link];
160  return nullptr;
161}
162
163// Returns a source location string. Used to construct an error message.
164template <class ELFT>
165std::string InputSectionBase<ELFT>::getLocation(typename ELFT::uint Offset) {
166  // First check if we can get desired values from debugging information.
167  std::string LineInfo = File->getLineInfo(this, Offset);
168  if (!LineInfo.empty())
169    return LineInfo;
170
171  // File->SourceFile contains STT_FILE symbol that contains a
172  // source file name. If it's missing, we use an object file name.
173  std::string SrcFile = File->SourceFile;
174  if (SrcFile.empty())
175    SrcFile = toString(File);
176
177  // Find a function symbol that encloses a given location.
178  for (SymbolBody *B : File->getSymbols())
179    if (auto *D = dyn_cast<DefinedRegular<ELFT>>(B))
180      if (D->Section == this && D->Type == STT_FUNC)
181        if (D->Value <= Offset && Offset < D->Value + D->Size)
182          return SrcFile + ":(function " + toString(*D) + ")";
183
184  // If there's no symbol, print out the offset in the section.
185  return (SrcFile + ":(" + Name + "+0x" + utohexstr(Offset) + ")").str();
186}
187
188template <class ELFT>
189InputSection<ELFT>::InputSection() : InputSectionBase<ELFT>() {}
190
191template <class ELFT>
192InputSection<ELFT>::InputSection(uintX_t Flags, uint32_t Type,
193                                 uintX_t Addralign, ArrayRef<uint8_t> Data,
194                                 StringRef Name, Kind K)
195    : InputSectionBase<ELFT>(nullptr, Flags, Type,
196                             /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, Addralign,
197                             Data, Name, K) {}
198
199template <class ELFT>
200InputSection<ELFT>::InputSection(elf::ObjectFile<ELFT> *F,
201                                 const Elf_Shdr *Header, StringRef Name)
202    : InputSectionBase<ELFT>(F, Header, Name, Base::Regular) {}
203
204template <class ELFT>
205bool InputSection<ELFT>::classof(const InputSectionData *S) {
206  return S->kind() == Base::Regular || S->kind() == Base::Synthetic;
207}
208
209template <class ELFT>
210InputSectionBase<ELFT> *InputSection<ELFT>::getRelocatedSection() {
211  assert(this->Type == SHT_RELA || this->Type == SHT_REL);
212  ArrayRef<InputSectionBase<ELFT> *> Sections = this->File->getSections();
213  return Sections[this->Info];
214}
215
216template <class ELFT> void InputSection<ELFT>::addThunk(const Thunk<ELFT> *T) {
217  Thunks.push_back(T);
218}
219
220template <class ELFT> uint64_t InputSection<ELFT>::getThunkOff() const {
221  return this->Data.size();
222}
223
224template <class ELFT> uint64_t InputSection<ELFT>::getThunksSize() const {
225  uint64_t Total = 0;
226  for (const Thunk<ELFT> *T : Thunks)
227    Total += T->size();
228  return Total;
229}
230
231// This is used for -r. We can't use memcpy to copy relocations because we need
232// to update symbol table offset and section index for each relocation. So we
233// copy relocations one by one.
234template <class ELFT>
235template <class RelTy>
236void InputSection<ELFT>::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
237  InputSectionBase<ELFT> *RelocatedSection = getRelocatedSection();
238
239  for (const RelTy &Rel : Rels) {
240    uint32_t Type = Rel.getType(Config->Mips64EL);
241    SymbolBody &Body = this->File->getRelocTargetSym(Rel);
242
243    Elf_Rela *P = reinterpret_cast<Elf_Rela *>(Buf);
244    Buf += sizeof(RelTy);
245
246    if (Config->Rela)
247      P->r_addend = getAddend<ELFT>(Rel);
248    P->r_offset = RelocatedSection->getOffset(Rel.r_offset);
249    P->setSymbolAndType(In<ELFT>::SymTab->getSymbolIndex(&Body), Type,
250                        Config->Mips64EL);
251  }
252}
253
254static uint32_t getARMUndefinedRelativeWeakVA(uint32_t Type, uint32_t A,
255                                              uint32_t P) {
256  switch (Type) {
257  case R_ARM_THM_JUMP11:
258    return P + 2;
259  case R_ARM_CALL:
260  case R_ARM_JUMP24:
261  case R_ARM_PC24:
262  case R_ARM_PLT32:
263  case R_ARM_PREL31:
264  case R_ARM_THM_JUMP19:
265  case R_ARM_THM_JUMP24:
266    return P + 4;
267  case R_ARM_THM_CALL:
268    // We don't want an interworking BLX to ARM
269    return P + 5;
270  default:
271    return A;
272  }
273}
274
275static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t Type, uint64_t A,
276                                                  uint64_t P) {
277  switch (Type) {
278  case R_AARCH64_CALL26:
279  case R_AARCH64_CONDBR19:
280  case R_AARCH64_JUMP26:
281  case R_AARCH64_TSTBR14:
282    return P + 4;
283  default:
284    return A;
285  }
286}
287
288template <class ELFT>
289static typename ELFT::uint
290getRelocTargetVA(uint32_t Type, typename ELFT::uint A, typename ELFT::uint P,
291                 const SymbolBody &Body, RelExpr Expr) {
292  switch (Expr) {
293  case R_ABS:
294  case R_RELAX_GOT_PC_NOPIC:
295    return Body.getVA<ELFT>(A);
296  case R_GOT:
297  case R_RELAX_TLS_GD_TO_IE_ABS:
298    return Body.getGotVA<ELFT>() + A;
299  case R_GOTONLY_PC:
300    return In<ELFT>::Got->getVA() + A - P;
301  case R_GOTONLY_PC_FROM_END:
302    return In<ELFT>::Got->getVA() + A - P + In<ELFT>::Got->getSize();
303  case R_GOTREL:
304    return Body.getVA<ELFT>(A) - In<ELFT>::Got->getVA();
305  case R_GOTREL_FROM_END:
306    return Body.getVA<ELFT>(A) - In<ELFT>::Got->getVA() -
307           In<ELFT>::Got->getSize();
308  case R_GOT_FROM_END:
309  case R_RELAX_TLS_GD_TO_IE_END:
310    return Body.getGotOffset<ELFT>() + A - In<ELFT>::Got->getSize();
311  case R_GOT_OFF:
312    return Body.getGotOffset<ELFT>() + A;
313  case R_GOT_PAGE_PC:
314  case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
315    return getAArch64Page(Body.getGotVA<ELFT>() + A) - getAArch64Page(P);
316  case R_GOT_PC:
317  case R_RELAX_TLS_GD_TO_IE:
318    return Body.getGotVA<ELFT>() + A - P;
319  case R_HINT:
320  case R_TLSDESC_CALL:
321    llvm_unreachable("cannot relocate hint relocs");
322  case R_MIPS_GOTREL:
323    return Body.getVA<ELFT>(A) - In<ELFT>::MipsGot->getGp();
324  case R_MIPS_GOT_LOCAL_PAGE:
325    // If relocation against MIPS local symbol requires GOT entry, this entry
326    // should be initialized by 'page address'. This address is high 16-bits
327    // of sum the symbol's value and the addend.
328    return In<ELFT>::MipsGot->getVA() +
329           In<ELFT>::MipsGot->getPageEntryOffset(Body, A) -
330           In<ELFT>::MipsGot->getGp();
331  case R_MIPS_GOT_OFF:
332  case R_MIPS_GOT_OFF32:
333    // In case of MIPS if a GOT relocation has non-zero addend this addend
334    // should be applied to the GOT entry content not to the GOT entry offset.
335    // That is why we use separate expression type.
336    return In<ELFT>::MipsGot->getVA() +
337           In<ELFT>::MipsGot->getBodyEntryOffset(Body, A) -
338           In<ELFT>::MipsGot->getGp();
339  case R_MIPS_TLSGD:
340    return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() +
341           In<ELFT>::MipsGot->getGlobalDynOffset(Body) -
342           In<ELFT>::MipsGot->getGp();
343  case R_MIPS_TLSLD:
344    return In<ELFT>::MipsGot->getVA() + In<ELFT>::MipsGot->getTlsOffset() +
345           In<ELFT>::MipsGot->getTlsIndexOff() - In<ELFT>::MipsGot->getGp();
346  case R_PAGE_PC:
347  case R_PLT_PAGE_PC:
348    if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
349      return getAArch64Page(A);
350    return getAArch64Page(Body.getVA<ELFT>(A)) - getAArch64Page(P);
351  case R_PC:
352    if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak()) {
353      // On ARM and AArch64 a branch to an undefined weak resolves to the
354      // next instruction, otherwise the place.
355      if (Config->EMachine == EM_ARM)
356        return getARMUndefinedRelativeWeakVA(Type, A, P);
357      if (Config->EMachine == EM_AARCH64)
358        return getAArch64UndefinedRelativeWeakVA(Type, A, P);
359    }
360    return Body.getVA<ELFT>(A) - P;
361  case R_PLT:
362    return Body.getPltVA<ELFT>() + A;
363  case R_PLT_PC:
364  case R_PPC_PLT_OPD:
365    return Body.getPltVA<ELFT>() + A - P;
366  case R_PPC_OPD: {
367    uint64_t SymVA = Body.getVA<ELFT>(A);
368    // If we have an undefined weak symbol, we might get here with a symbol
369    // address of zero. That could overflow, but the code must be unreachable,
370    // so don't bother doing anything at all.
371    if (!SymVA)
372      return 0;
373    if (Out<ELF64BE>::Opd) {
374      // If this is a local call, and we currently have the address of a
375      // function-descriptor, get the underlying code address instead.
376      uint64_t OpdStart = Out<ELF64BE>::Opd->Addr;
377      uint64_t OpdEnd = OpdStart + Out<ELF64BE>::Opd->Size;
378      bool InOpd = OpdStart <= SymVA && SymVA < OpdEnd;
379      if (InOpd)
380        SymVA = read64be(&Out<ELF64BE>::OpdBuf[SymVA - OpdStart]);
381    }
382    return SymVA - P;
383  }
384  case R_PPC_TOC:
385    return getPPC64TocBase() + A;
386  case R_RELAX_GOT_PC:
387    return Body.getVA<ELFT>(A) - P;
388  case R_RELAX_TLS_GD_TO_LE:
389  case R_RELAX_TLS_IE_TO_LE:
390  case R_RELAX_TLS_LD_TO_LE:
391  case R_TLS:
392    // A weak undefined TLS symbol resolves to the base of the TLS
393    // block, i.e. gets a value of zero. If we pass --gc-sections to
394    // lld and .tbss is not referenced, it gets reclaimed and we don't
395    // create a TLS program header. Therefore, we resolve this
396    // statically to zero.
397    if (Body.isTls() && (Body.isLazy() || Body.isUndefined()) &&
398        Body.symbol()->isWeak())
399      return 0;
400    if (Target->TcbSize)
401      return Body.getVA<ELFT>(A) +
402             alignTo(Target->TcbSize, Out<ELFT>::TlsPhdr->p_align);
403    return Body.getVA<ELFT>(A) - Out<ELFT>::TlsPhdr->p_memsz;
404  case R_RELAX_TLS_GD_TO_LE_NEG:
405  case R_NEG_TLS:
406    return Out<ELF32LE>::TlsPhdr->p_memsz - Body.getVA<ELFT>(A);
407  case R_SIZE:
408    return Body.getSize<ELFT>() + A;
409  case R_THUNK_ABS:
410    return Body.getThunkVA<ELFT>() + A;
411  case R_THUNK_PC:
412  case R_THUNK_PLT_PC:
413    return Body.getThunkVA<ELFT>() + A - P;
414  case R_TLSDESC:
415    return In<ELFT>::Got->getGlobalDynAddr(Body) + A;
416  case R_TLSDESC_PAGE:
417    return getAArch64Page(In<ELFT>::Got->getGlobalDynAddr(Body) + A) -
418           getAArch64Page(P);
419  case R_TLSGD:
420    return In<ELFT>::Got->getGlobalDynOffset(Body) + A -
421           In<ELFT>::Got->getSize();
422  case R_TLSGD_PC:
423    return In<ELFT>::Got->getGlobalDynAddr(Body) + A - P;
424  case R_TLSLD:
425    return In<ELFT>::Got->getTlsIndexOff() + A - In<ELFT>::Got->getSize();
426  case R_TLSLD_PC:
427    return In<ELFT>::Got->getTlsIndexVA() + A - P;
428  }
429  llvm_unreachable("Invalid expression");
430}
431
432// This function applies relocations to sections without SHF_ALLOC bit.
433// Such sections are never mapped to memory at runtime. Debug sections are
434// an example. Relocations in non-alloc sections are much easier to
435// handle than in allocated sections because it will never need complex
436// treatement such as GOT or PLT (because at runtime no one refers them).
437// So, we handle relocations for non-alloc sections directly in this
438// function as a performance optimization.
439template <class ELFT>
440template <class RelTy>
441void InputSection<ELFT>::relocateNonAlloc(uint8_t *Buf, ArrayRef<RelTy> Rels) {
442  for (const RelTy &Rel : Rels) {
443    uint32_t Type = Rel.getType(Config->Mips64EL);
444    uintX_t Offset = this->getOffset(Rel.r_offset);
445    uint8_t *BufLoc = Buf + Offset;
446    uintX_t Addend = getAddend<ELFT>(Rel);
447    if (!RelTy::IsRela)
448      Addend += Target->getImplicitAddend(BufLoc, Type);
449
450    SymbolBody &Sym = this->File->getRelocTargetSym(Rel);
451    if (Target->getRelExpr(Type, Sym) != R_ABS) {
452      error(this->getLocation(Offset) + ": has non-ABS reloc");
453      return;
454    }
455
456    uintX_t AddrLoc = this->OutSec->Addr + Offset;
457    uint64_t SymVA = 0;
458    if (!Sym.isTls() || Out<ELFT>::TlsPhdr)
459      SymVA = SignExtend64<sizeof(uintX_t) * 8>(
460          getRelocTargetVA<ELFT>(Type, Addend, AddrLoc, Sym, R_ABS));
461    Target->relocateOne(BufLoc, Type, SymVA);
462  }
463}
464
465template <class ELFT>
466void InputSectionBase<ELFT>::relocate(uint8_t *Buf, uint8_t *BufEnd) {
467  // scanReloc function in Writer.cpp constructs Relocations
468  // vector only for SHF_ALLOC'ed sections. For other sections,
469  // we handle relocations directly here.
470  auto *IS = dyn_cast<InputSection<ELFT>>(this);
471  if (IS && !(IS->Flags & SHF_ALLOC)) {
472    if (IS->AreRelocsRela)
473      IS->relocateNonAlloc(Buf, IS->relas());
474    else
475      IS->relocateNonAlloc(Buf, IS->rels());
476    return;
477  }
478
479  const unsigned Bits = sizeof(uintX_t) * 8;
480  for (const Relocation &Rel : Relocations) {
481    uintX_t Offset = getOffset(Rel.Offset);
482    uint8_t *BufLoc = Buf + Offset;
483    uint32_t Type = Rel.Type;
484    uintX_t A = Rel.Addend;
485
486    uintX_t AddrLoc = OutSec->Addr + Offset;
487    RelExpr Expr = Rel.Expr;
488    uint64_t TargetVA = SignExtend64<Bits>(
489        getRelocTargetVA<ELFT>(Type, A, AddrLoc, *Rel.Sym, Expr));
490
491    switch (Expr) {
492    case R_RELAX_GOT_PC:
493    case R_RELAX_GOT_PC_NOPIC:
494      Target->relaxGot(BufLoc, TargetVA);
495      break;
496    case R_RELAX_TLS_IE_TO_LE:
497      Target->relaxTlsIeToLe(BufLoc, Type, TargetVA);
498      break;
499    case R_RELAX_TLS_LD_TO_LE:
500      Target->relaxTlsLdToLe(BufLoc, Type, TargetVA);
501      break;
502    case R_RELAX_TLS_GD_TO_LE:
503    case R_RELAX_TLS_GD_TO_LE_NEG:
504      Target->relaxTlsGdToLe(BufLoc, Type, TargetVA);
505      break;
506    case R_RELAX_TLS_GD_TO_IE:
507    case R_RELAX_TLS_GD_TO_IE_ABS:
508    case R_RELAX_TLS_GD_TO_IE_PAGE_PC:
509    case R_RELAX_TLS_GD_TO_IE_END:
510      Target->relaxTlsGdToIe(BufLoc, Type, TargetVA);
511      break;
512    case R_PPC_PLT_OPD:
513      // Patch a nop (0x60000000) to a ld.
514      if (BufLoc + 8 <= BufEnd && read32be(BufLoc + 4) == 0x60000000)
515        write32be(BufLoc + 4, 0xe8410028); // ld %r2, 40(%r1)
516    // fallthrough
517    default:
518      Target->relocateOne(BufLoc, Type, TargetVA);
519      break;
520    }
521  }
522}
523
524template <class ELFT> void InputSection<ELFT>::writeTo(uint8_t *Buf) {
525  if (this->Type == SHT_NOBITS)
526    return;
527
528  if (auto *S = dyn_cast<SyntheticSection<ELFT>>(this)) {
529    S->writeTo(Buf + OutSecOff);
530    return;
531  }
532
533  // If -r is given, then an InputSection may be a relocation section.
534  if (this->Type == SHT_RELA) {
535    copyRelocations(Buf + OutSecOff, this->template getDataAs<Elf_Rela>());
536    return;
537  }
538  if (this->Type == SHT_REL) {
539    copyRelocations(Buf + OutSecOff, this->template getDataAs<Elf_Rel>());
540    return;
541  }
542
543  // Copy section contents from source object file to output file.
544  ArrayRef<uint8_t> Data = this->Data;
545  memcpy(Buf + OutSecOff, Data.data(), Data.size());
546
547  // Iterate over all relocation sections that apply to this section.
548  uint8_t *BufEnd = Buf + OutSecOff + Data.size();
549  this->relocate(Buf, BufEnd);
550
551  // The section might have a data/code generated by the linker and need
552  // to be written after the section. Usually these are thunks - small piece
553  // of code used to jump between "incompatible" functions like PIC and non-PIC
554  // or if the jump target too far and its address does not fit to the short
555  // jump istruction.
556  if (!Thunks.empty()) {
557    Buf += OutSecOff + getThunkOff();
558    for (const Thunk<ELFT> *T : Thunks) {
559      T->writeTo(Buf);
560      Buf += T->size();
561    }
562  }
563}
564
565template <class ELFT>
566void InputSection<ELFT>::replace(InputSection<ELFT> *Other) {
567  this->Alignment = std::max(this->Alignment, Other->Alignment);
568  Other->Repl = this->Repl;
569  Other->Live = false;
570}
571
572template <class ELFT>
573EhInputSection<ELFT>::EhInputSection(elf::ObjectFile<ELFT> *F,
574                                     const Elf_Shdr *Header, StringRef Name)
575    : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::EHFrame) {
576  // Mark .eh_frame sections as live by default because there are
577  // usually no relocations that point to .eh_frames. Otherwise,
578  // the garbage collector would drop all .eh_frame sections.
579  this->Live = true;
580}
581
582template <class ELFT>
583bool EhInputSection<ELFT>::classof(const InputSectionData *S) {
584  return S->kind() == InputSectionBase<ELFT>::EHFrame;
585}
586
587// Returns the index of the first relocation that points to a region between
588// Begin and Begin+Size.
589template <class IntTy, class RelTy>
590static unsigned getReloc(IntTy Begin, IntTy Size, const ArrayRef<RelTy> &Rels,
591                         unsigned &RelocI) {
592  // Start search from RelocI for fast access. That works because the
593  // relocations are sorted in .eh_frame.
594  for (unsigned N = Rels.size(); RelocI < N; ++RelocI) {
595    const RelTy &Rel = Rels[RelocI];
596    if (Rel.r_offset < Begin)
597      continue;
598
599    if (Rel.r_offset < Begin + Size)
600      return RelocI;
601    return -1;
602  }
603  return -1;
604}
605
606// .eh_frame is a sequence of CIE or FDE records.
607// This function splits an input section into records and returns them.
608template <class ELFT> void EhInputSection<ELFT>::split() {
609  // Early exit if already split.
610  if (!this->Pieces.empty())
611    return;
612
613  if (this->NumRelocations) {
614    if (this->AreRelocsRela)
615      split(this->relas());
616    else
617      split(this->rels());
618    return;
619  }
620  split(makeArrayRef<typename ELFT::Rela>(nullptr, nullptr));
621}
622
623template <class ELFT>
624template <class RelTy>
625void EhInputSection<ELFT>::split(ArrayRef<RelTy> Rels) {
626  ArrayRef<uint8_t> Data = this->Data;
627  unsigned RelI = 0;
628  for (size_t Off = 0, End = Data.size(); Off != End;) {
629    size_t Size = readEhRecordSize<ELFT>(this, Off);
630    this->Pieces.emplace_back(Off, this, Size, getReloc(Off, Size, Rels, RelI));
631    // The empty record is the end marker.
632    if (Size == 4)
633      break;
634    Off += Size;
635  }
636}
637
638static size_t findNull(ArrayRef<uint8_t> A, size_t EntSize) {
639  // Optimize the common case.
640  StringRef S((const char *)A.data(), A.size());
641  if (EntSize == 1)
642    return S.find(0);
643
644  for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
645    const char *B = S.begin() + I;
646    if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
647      return I;
648  }
649  return StringRef::npos;
650}
651
652// Split SHF_STRINGS section. Such section is a sequence of
653// null-terminated strings.
654template <class ELFT>
655void MergeInputSection<ELFT>::splitStrings(ArrayRef<uint8_t> Data,
656                                           size_t EntSize) {
657  size_t Off = 0;
658  bool IsAlloc = this->Flags & SHF_ALLOC;
659  while (!Data.empty()) {
660    size_t End = findNull(Data, EntSize);
661    if (End == StringRef::npos)
662      fatal(toString(this) + ": string is not null terminated");
663    size_t Size = End + EntSize;
664    Pieces.emplace_back(Off, !IsAlloc);
665    Hashes.push_back(hash_value(toStringRef(Data.slice(0, Size))));
666    Data = Data.slice(Size);
667    Off += Size;
668  }
669}
670
671// Split non-SHF_STRINGS section. Such section is a sequence of
672// fixed size records.
673template <class ELFT>
674void MergeInputSection<ELFT>::splitNonStrings(ArrayRef<uint8_t> Data,
675                                              size_t EntSize) {
676  size_t Size = Data.size();
677  assert((Size % EntSize) == 0);
678  bool IsAlloc = this->Flags & SHF_ALLOC;
679  for (unsigned I = 0, N = Size; I != N; I += EntSize) {
680    Hashes.push_back(hash_value(toStringRef(Data.slice(I, EntSize))));
681    Pieces.emplace_back(I, !IsAlloc);
682  }
683}
684
685template <class ELFT>
686MergeInputSection<ELFT>::MergeInputSection(elf::ObjectFile<ELFT> *F,
687                                           const Elf_Shdr *Header,
688                                           StringRef Name)
689    : InputSectionBase<ELFT>(F, Header, Name, InputSectionBase<ELFT>::Merge) {}
690
691// This function is called after we obtain a complete list of input sections
692// that need to be linked. This is responsible to split section contents
693// into small chunks for further processing.
694//
695// Note that this function is called from parallel_for_each. This must be
696// thread-safe (i.e. no memory allocation from the pools).
697template <class ELFT> void MergeInputSection<ELFT>::splitIntoPieces() {
698  ArrayRef<uint8_t> Data = this->Data;
699  uintX_t EntSize = this->Entsize;
700  if (this->Flags & SHF_STRINGS)
701    splitStrings(Data, EntSize);
702  else
703    splitNonStrings(Data, EntSize);
704
705  if (Config->GcSections && (this->Flags & SHF_ALLOC))
706    for (uintX_t Off : LiveOffsets)
707      this->getSectionPiece(Off)->Live = true;
708}
709
710template <class ELFT>
711bool MergeInputSection<ELFT>::classof(const InputSectionData *S) {
712  return S->kind() == InputSectionBase<ELFT>::Merge;
713}
714
715// Do binary search to get a section piece at a given input offset.
716template <class ELFT>
717SectionPiece *MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) {
718  auto *This = static_cast<const MergeInputSection<ELFT> *>(this);
719  return const_cast<SectionPiece *>(This->getSectionPiece(Offset));
720}
721
722template <class It, class T, class Compare>
723static It fastUpperBound(It First, It Last, const T &Value, Compare Comp) {
724  size_t Size = std::distance(First, Last);
725  assert(Size != 0);
726  while (Size != 1) {
727    size_t H = Size / 2;
728    const It MI = First + H;
729    Size -= H;
730    First = Comp(Value, *MI) ? First : First + H;
731  }
732  return Comp(Value, *First) ? First : First + 1;
733}
734
735template <class ELFT>
736const SectionPiece *
737MergeInputSection<ELFT>::getSectionPiece(uintX_t Offset) const {
738  uintX_t Size = this->Data.size();
739  if (Offset >= Size)
740    fatal(toString(this) + ": entry is past the end of the section");
741
742  // Find the element this offset points to.
743  auto I = fastUpperBound(
744      Pieces.begin(), Pieces.end(), Offset,
745      [](const uintX_t &A, const SectionPiece &B) { return A < B.InputOff; });
746  --I;
747  return &*I;
748}
749
750// Returns the offset in an output section for a given input offset.
751// Because contents of a mergeable section is not contiguous in output,
752// it is not just an addition to a base output offset.
753template <class ELFT>
754typename ELFT::uint MergeInputSection<ELFT>::getOffset(uintX_t Offset) const {
755  // Initialize OffsetMap lazily.
756  std::call_once(InitOffsetMap, [&] {
757    OffsetMap.reserve(Pieces.size());
758    for (const SectionPiece &Piece : Pieces)
759      OffsetMap[Piece.InputOff] = Piece.OutputOff;
760  });
761
762  // Find a string starting at a given offset.
763  auto It = OffsetMap.find(Offset);
764  if (It != OffsetMap.end())
765    return It->second;
766
767  if (!this->Live)
768    return 0;
769
770  // If Offset is not at beginning of a section piece, it is not in the map.
771  // In that case we need to search from the original section piece vector.
772  const SectionPiece &Piece = *this->getSectionPiece(Offset);
773  if (!Piece.Live)
774    return 0;
775
776  uintX_t Addend = Offset - Piece.InputOff;
777  return Piece.OutputOff + Addend;
778}
779
780template class elf::InputSectionBase<ELF32LE>;
781template class elf::InputSectionBase<ELF32BE>;
782template class elf::InputSectionBase<ELF64LE>;
783template class elf::InputSectionBase<ELF64BE>;
784
785template class elf::InputSection<ELF32LE>;
786template class elf::InputSection<ELF32BE>;
787template class elf::InputSection<ELF64LE>;
788template class elf::InputSection<ELF64BE>;
789
790template class elf::EhInputSection<ELF32LE>;
791template class elf::EhInputSection<ELF32BE>;
792template class elf::EhInputSection<ELF64LE>;
793template class elf::EhInputSection<ELF64BE>;
794
795template class elf::MergeInputSection<ELF32LE>;
796template class elf::MergeInputSection<ELF32BE>;
797template class elf::MergeInputSection<ELF64LE>;
798template class elf::MergeInputSection<ELF64BE>;
799
800template std::string lld::toString(const InputSectionBase<ELF32LE> *);
801template std::string lld::toString(const InputSectionBase<ELF32BE> *);
802template std::string lld::toString(const InputSectionBase<ELF64LE> *);
803template std::string lld::toString(const InputSectionBase<ELF64BE> *);
804