1 //===- OutputSections.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 "OutputSections.h"
11 #include "Config.h"
12 #include "SymbolTable.h"
13 #include "Target.h"
14 
15 using namespace llvm;
16 using namespace llvm::object;
17 using namespace llvm::support::endian;
18 using namespace llvm::ELF;
19 
20 using namespace lld;
21 using namespace lld::elf2;
22 
23 template <bool Is64Bits>
24 OutputSectionBase<Is64Bits>::OutputSectionBase(StringRef Name, uint32_t sh_type,
25                                                uintX_t sh_flags)
26     : Name(Name) {
27   memset(&Header, 0, sizeof(HeaderT));
28   Header.sh_type = sh_type;
29   Header.sh_flags = sh_flags;
30 }
31 
32 template <class ELFT>
33 GotSection<ELFT>::GotSection()
34     : OutputSectionBase<ELFT::Is64Bits>(".got", llvm::ELF::SHT_PROGBITS,
35                                         llvm::ELF::SHF_ALLOC |
36                                             llvm::ELF::SHF_WRITE) {
37   this->Header.sh_addralign = sizeof(uintX_t);
38 }
39 
40 template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody *Sym) {
41   Sym->GotIndex = Entries.size();
42   Entries.push_back(Sym);
43 }
44 
45 template <class ELFT>
46 typename GotSection<ELFT>::uintX_t
47 GotSection<ELFT>::getEntryAddr(const SymbolBody &B) const {
48   return this->getVA() + B.GotIndex * sizeof(uintX_t);
49 }
50 
51 template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
52   for (const SymbolBody *B : Entries) {
53     uint8_t *Entry = Buf;
54     Buf += sizeof(uintX_t);
55     if (canBePreempted(B, false))
56       continue; // The dynamic linker will take care of it.
57     uintX_t VA = getSymVA<ELFT>(*B);
58     write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
59   }
60 }
61 
62 template <class ELFT>
63 PltSection<ELFT>::PltSection()
64     : OutputSectionBase<ELFT::Is64Bits>(".plt", llvm::ELF::SHT_PROGBITS,
65                                         llvm::ELF::SHF_ALLOC |
66                                             llvm::ELF::SHF_EXECINSTR) {
67   this->Header.sh_addralign = 16;
68 }
69 
70 template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
71   size_t Off = 0;
72   for (const SymbolBody *E : Entries) {
73     uint64_t Got = Out<ELFT>::Got->getEntryAddr(*E);
74     uint64_t Plt = this->getVA() + Off;
75     Target->writePltEntry(Buf + Off, Got, Plt);
76     Off += Target->getPltEntrySize();
77   }
78 }
79 
80 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody *Sym) {
81   Sym->PltIndex = Entries.size();
82   Entries.push_back(Sym);
83 }
84 
85 template <class ELFT>
86 typename PltSection<ELFT>::uintX_t
87 PltSection<ELFT>::getEntryAddr(const SymbolBody &B) const {
88   return this->getVA() + B.PltIndex * Target->getPltEntrySize();
89 }
90 
91 template <class ELFT>
92 void PltSection<ELFT>::finalize() {
93   this->Header.sh_size = Entries.size() * Target->getPltEntrySize();
94 }
95 
96 template <class ELFT>
97 RelocationSection<ELFT>::RelocationSection(bool IsRela)
98     : OutputSectionBase<ELFT::Is64Bits>(IsRela ? ".rela.dyn" : ".rel.dyn",
99                                         IsRela ? llvm::ELF::SHT_RELA
100                                                : llvm::ELF::SHT_REL,
101                                         llvm::ELF::SHF_ALLOC),
102       IsRela(IsRela) {
103   this->Header.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
104   this->Header.sh_addralign = ELFT::Is64Bits ? 8 : 4;
105 }
106 
107 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
108   const unsigned EntrySize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
109   bool IsMips64EL = Relocs[0].C.getFile()->getObj().isMips64EL();
110   for (const DynamicReloc<ELFT> &Rel : Relocs) {
111     auto *P = reinterpret_cast<Elf_Rel *>(Buf);
112     Buf += EntrySize;
113 
114     const InputSection<ELFT> &C = Rel.C;
115     const Elf_Rel &RI = Rel.RI;
116     uint32_t SymIndex = RI.getSymbol(IsMips64EL);
117     const ObjectFile<ELFT> &File = *C.getFile();
118     SymbolBody *Body = File.getSymbolBody(SymIndex);
119     if (Body)
120       Body = Body->repl();
121 
122     uint32_t Type = RI.getType(IsMips64EL);
123 
124     bool NeedsGot = Body && Target->relocNeedsGot(Type, *Body);
125     bool CanBePreempted = canBePreempted(Body, NeedsGot);
126     uintX_t Addend = 0;
127     if (!CanBePreempted) {
128       if (IsRela) {
129         if (Body)
130           Addend += getSymVA<ELFT>(cast<ELFSymbolBody<ELFT>>(*Body));
131         else
132           Addend += getLocalRelTarget(File, RI);
133       }
134       P->setSymbolAndType(0, Target->getRelativeReloc(), IsMips64EL);
135     }
136 
137     if (NeedsGot) {
138       P->r_offset = Out<ELFT>::Got->getEntryAddr(*Body);
139       if (CanBePreempted)
140         P->setSymbolAndType(Body->getDynamicSymbolTableIndex(),
141                             Target->getGotReloc(), IsMips64EL);
142     } else {
143       if (IsRela)
144         Addend += static_cast<const Elf_Rela &>(RI).r_addend;
145       P->r_offset = RI.r_offset + C.OutSec->getVA() + C.OutSecOff;
146       if (CanBePreempted)
147         P->setSymbolAndType(Body->getDynamicSymbolTableIndex(), Type,
148                             IsMips64EL);
149     }
150 
151     if (IsRela)
152       static_cast<Elf_Rela *>(P)->r_addend = Addend;
153   }
154 }
155 
156 template <class ELFT> void RelocationSection<ELFT>::finalize() {
157   this->Header.sh_link = Out<ELFT>::DynSymTab->getSectionIndex();
158   this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
159 }
160 
161 template <bool Is64Bits>
162 InterpSection<Is64Bits>::InterpSection()
163     : OutputSectionBase<Is64Bits>(".interp", llvm::ELF::SHT_PROGBITS,
164                                   llvm::ELF::SHF_ALLOC) {
165   this->Header.sh_size = Config->DynamicLinker.size() + 1;
166   this->Header.sh_addralign = 1;
167 }
168 
169 template <bool Is64Bits>
170 template <endianness E>
171 void OutputSectionBase<Is64Bits>::writeHeaderTo(
172     typename ELFFile<ELFType<E, Is64Bits>>::Elf_Shdr *SHdr) {
173   SHdr->sh_name = Header.sh_name;
174   SHdr->sh_type = Header.sh_type;
175   SHdr->sh_flags = Header.sh_flags;
176   SHdr->sh_addr = Header.sh_addr;
177   SHdr->sh_offset = Header.sh_offset;
178   SHdr->sh_size = Header.sh_size;
179   SHdr->sh_link = Header.sh_link;
180   SHdr->sh_info = Header.sh_info;
181   SHdr->sh_addralign = Header.sh_addralign;
182   SHdr->sh_entsize = Header.sh_entsize;
183 }
184 
185 template <bool Is64Bits> void InterpSection<Is64Bits>::writeTo(uint8_t *Buf) {
186   memcpy(Buf, Config->DynamicLinker.data(), Config->DynamicLinker.size());
187 }
188 
189 template <class ELFT>
190 HashTableSection<ELFT>::HashTableSection()
191     : OutputSectionBase<ELFT::Is64Bits>(".hash", llvm::ELF::SHT_HASH,
192                                         llvm::ELF::SHF_ALLOC) {
193   this->Header.sh_entsize = sizeof(Elf_Word);
194   this->Header.sh_addralign = sizeof(Elf_Word);
195 }
196 
197 template <class ELFT> void HashTableSection<ELFT>::addSymbol(SymbolBody *S) {
198   StringRef Name = S->getName();
199   Out<ELFT>::DynSymTab->addSymbol(Name);
200   Hashes.push_back(hash(Name));
201   S->setDynamicSymbolTableIndex(Hashes.size());
202 }
203 
204 template <class ELFT> void HashTableSection<ELFT>::finalize() {
205   this->Header.sh_link = Out<ELFT>::DynSymTab->getSectionIndex();
206 
207   assert(Out<ELFT>::DynSymTab->getNumSymbols() == Hashes.size() + 1);
208   unsigned NumEntries = 2;                 // nbucket and nchain.
209   NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
210 
211   // Create as many buckets as there are symbols.
212   // FIXME: This is simplistic. We can try to optimize it, but implementing
213   // support for SHT_GNU_HASH is probably even more profitable.
214   NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
215   this->Header.sh_size = NumEntries * sizeof(Elf_Word);
216 }
217 
218 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
219   unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
220   auto *P = reinterpret_cast<Elf_Word *>(Buf);
221   *P++ = NumSymbols; // nbucket
222   *P++ = NumSymbols; // nchain
223 
224   Elf_Word *Buckets = P;
225   Elf_Word *Chains = P + NumSymbols;
226 
227   for (unsigned I = 1; I < NumSymbols; ++I) {
228     uint32_t Hash = Hashes[I - 1] % NumSymbols;
229     Chains[I] = Buckets[Hash];
230     Buckets[Hash] = I;
231   }
232 }
233 
234 template <class ELFT>
235 DynamicSection<ELFT>::DynamicSection(SymbolTable<ELFT> &SymTab)
236     : OutputSectionBase<ELFT::Is64Bits>(".dynamic", llvm::ELF::SHT_DYNAMIC,
237                                         llvm::ELF::SHF_ALLOC |
238                                             llvm::ELF::SHF_WRITE),
239       SymTab(SymTab) {
240   typename Base::HeaderT &Header = this->Header;
241   Header.sh_addralign = ELFT::Is64Bits ? 8 : 4;
242   Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
243 }
244 
245 template <class ELFT> void DynamicSection<ELFT>::finalize() {
246   if (this->Header.sh_size)
247     return; // Already finalized.
248 
249   typename Base::HeaderT &Header = this->Header;
250   Header.sh_link = Out<ELFT>::DynStrTab->getSectionIndex();
251 
252   unsigned NumEntries = 0;
253   if (Out<ELFT>::RelaDyn->hasRelocs()) {
254     ++NumEntries; // DT_RELA / DT_REL
255     ++NumEntries; // DT_RELASZ / DT_RELSZ
256     ++NumEntries; // DT_RELAENT / DT_RELENT
257   }
258   ++NumEntries; // DT_SYMTAB
259   ++NumEntries; // DT_SYMENT
260   ++NumEntries; // DT_STRTAB
261   ++NumEntries; // DT_STRSZ
262   ++NumEntries; // DT_HASH
263 
264   if (!Config->RPath.empty()) {
265     ++NumEntries; // DT_RUNPATH / DT_RPATH
266     Out<ELFT>::DynStrTab->add(Config->RPath);
267   }
268 
269   if (!Config->SoName.empty()) {
270     ++NumEntries; // DT_SONAME
271     Out<ELFT>::DynStrTab->add(Config->SoName);
272   }
273 
274   if (PreInitArraySec)
275     NumEntries += 2;
276   if (InitArraySec)
277     NumEntries += 2;
278   if (FiniArraySec)
279     NumEntries += 2;
280 
281   for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles()) {
282     if (!F->isNeeded())
283       continue;
284     Out<ELFT>::DynStrTab->add(F->getSoName());
285     ++NumEntries;
286   }
287 
288   if (Symbol *S = SymTab.getSymbols().lookup(Config->Init))
289     InitSym = dyn_cast<ELFSymbolBody<ELFT>>(S->Body);
290   if (Symbol *S = SymTab.getSymbols().lookup(Config->Fini))
291     FiniSym = dyn_cast<ELFSymbolBody<ELFT>>(S->Body);
292   if (InitSym)
293     ++NumEntries; // DT_INIT
294   if (FiniSym)
295     ++NumEntries; // DT_FINI
296   if (Config->ZNow || Config->Bsymbolic)
297     ++NumEntries; // DT_FLAGS_1
298   ++NumEntries; // DT_NULL
299 
300   Header.sh_size = NumEntries * Header.sh_entsize;
301 }
302 
303 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
304   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
305 
306   auto WritePtr = [&](int32_t Tag, uint64_t Val) {
307     P->d_tag = Tag;
308     P->d_un.d_ptr = Val;
309     ++P;
310   };
311 
312   auto WriteVal = [&](int32_t Tag, uint32_t Val) {
313     P->d_tag = Tag;
314     P->d_un.d_val = Val;
315     ++P;
316   };
317 
318   if (Out<ELFT>::RelaDyn->hasRelocs()) {
319     bool IsRela = Out<ELFT>::RelaDyn->isRela();
320     WritePtr(IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn->getVA());
321     WriteVal(IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize());
322     WriteVal(IsRela ? DT_RELAENT : DT_RELENT,
323              IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
324   }
325 
326   WritePtr(DT_SYMTAB, Out<ELFT>::DynSymTab->getVA());
327   WritePtr(DT_SYMENT, sizeof(Elf_Sym));
328   WritePtr(DT_STRTAB, Out<ELFT>::DynStrTab->getVA());
329   WriteVal(DT_STRSZ, Out<ELFT>::DynStrTab->data().size());
330   WritePtr(DT_HASH, Out<ELFT>::HashTab->getVA());
331 
332   if (!Config->RPath.empty())
333 
334     // If --enable-new-dtags is set lld emits DT_RUNPATH
335     // instead of DT_RPATH. The two tags are functionally
336     // equivalent except for the following:
337     // - DT_RUNPATH is searched after LD_LIBRARY_PATH, while
338     // DT_RPATH is searched before.
339     // - DT_RUNPATH is used only to search for direct
340     // dependencies of the object it's contained in, while
341     // DT_RPATH is used for indirect dependencies as well.
342     WriteVal(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
343              Out<ELFT>::DynStrTab->getFileOff(Config->RPath));
344 
345   if (!Config->SoName.empty())
346     WriteVal(DT_SONAME, Out<ELFT>::DynStrTab->getFileOff(Config->SoName));
347 
348   auto WriteArray = [&](int32_t T1, int32_t T2,
349                         const OutputSectionBase<ELFT::Is64Bits> *Sec) {
350     if (!Sec)
351       return;
352     WritePtr(T1, Sec->getVA());
353     WriteVal(T2, Sec->getSize());
354   };
355   WriteArray(DT_PREINIT_ARRAY, DT_PREINIT_ARRAYSZ, PreInitArraySec);
356   WriteArray(DT_INIT_ARRAY, DT_INIT_ARRAYSZ, InitArraySec);
357   WriteArray(DT_FINI_ARRAY, DT_FINI_ARRAYSZ, FiniArraySec);
358 
359   for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles())
360     if (F->isNeeded())
361       WriteVal(DT_NEEDED, Out<ELFT>::DynStrTab->getFileOff(F->getSoName()));
362 
363   if (InitSym)
364     WritePtr(DT_INIT, getSymVA<ELFT>(*InitSym));
365   if (FiniSym)
366     WritePtr(DT_FINI, getSymVA<ELFT>(*FiniSym));
367 
368   uint32_t Flags = 0;
369   if (Config->Bsymbolic)
370     Flags |= DF_SYMBOLIC;
371   if (Config->ZNow)
372     Flags |= DF_1_NOW;
373   if (Flags)
374     WriteVal(DT_FLAGS_1, Flags);
375 
376   WriteVal(DT_NULL, 0);
377 }
378 
379 template <class ELFT>
380 OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t sh_type,
381                                    uintX_t sh_flags)
382     : OutputSectionBase<ELFT::Is64Bits>(Name, sh_type, sh_flags) {}
383 
384 template <class ELFT>
385 void OutputSection<ELFT>::addSection(InputSection<ELFT> *C) {
386   Sections.push_back(C);
387   C->OutSec = this;
388   uint32_t Align = C->getAlign();
389   if (Align > this->Header.sh_addralign)
390     this->Header.sh_addralign = Align;
391 
392   uintX_t Off = this->Header.sh_size;
393   Off = RoundUpToAlignment(Off, Align);
394   C->OutSecOff = Off;
395   Off += C->getSize();
396   this->Header.sh_size = Off;
397 }
398 
399 template <class ELFT>
400 typename ELFFile<ELFT>::uintX_t lld::elf2::getSymVA(const SymbolBody &S) {
401   switch (S.kind()) {
402   case SymbolBody::DefinedSyntheticKind: {
403     auto &D = cast<DefinedSynthetic<ELFT>>(S);
404     return D.Section.getVA() + D.Sym.st_value;
405   }
406   case SymbolBody::DefinedAbsoluteKind:
407     return cast<DefinedAbsolute<ELFT>>(S).Sym.st_value;
408   case SymbolBody::DefinedRegularKind: {
409     const auto &DR = cast<DefinedRegular<ELFT>>(S);
410     const InputSection<ELFT> *SC = &DR.Section;
411     return SC->OutSec->getVA() + SC->OutSecOff + DR.Sym.st_value;
412   }
413   case SymbolBody::DefinedCommonKind:
414     return Out<ELFT>::Bss->getVA() + cast<DefinedCommon<ELFT>>(S).OffsetInBSS;
415   case SymbolBody::SharedKind:
416   case SymbolBody::UndefinedKind:
417     return 0;
418   case SymbolBody::LazyKind:
419     assert(S.isUsedInRegularObj() && "Lazy symbol reached writer");
420     return 0;
421   }
422   llvm_unreachable("Invalid symbol kind");
423 }
424 
425 // Returns a VA which a relocatin RI refers to. Used only for local symbols.
426 // For non-local symbols, use getSymVA instead.
427 template <class ELFT>
428 typename ELFFile<ELFT>::uintX_t
429 lld::elf2::getLocalRelTarget(const ObjectFile<ELFT> &File,
430                              const typename ELFFile<ELFT>::Elf_Rel &RI) {
431   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
432   const Elf_Sym *Sym =
433       File.getObj().getRelocationSymbol(&RI, File.getSymbolTable());
434 
435   // For certain special relocations, such as R_PPC64_TOC, there's no
436   // corresponding symbol. Just return 0 in that case.
437   if (!Sym)
438     return 0;
439 
440   uint32_t SecIndex = Sym->st_shndx;
441   if (SecIndex == SHN_XINDEX)
442     SecIndex = File.getObj().getExtendedSymbolTableIndex(
443         Sym, File.getSymbolTable(), File.getSymbolTableShndx());
444   ArrayRef<InputSection<ELFT> *> Sections = File.getSections();
445   InputSection<ELFT> *Section = Sections[SecIndex];
446 
447   // According to the ELF spec reference to a local symbol from outside
448   // the group are not allowed. Unfortunately .eh_frame breaks that rule
449   // and must be treated specially. For now we just replace the symbol with
450   // 0.
451   if (Section == &InputSection<ELFT>::Discarded)
452     return 0;
453 
454   return Section->OutSec->getVA() + Section->OutSecOff + Sym->st_value;
455 }
456 
457 // Returns true if a symbol can be replaced at load-time by a symbol
458 // with the same name defined in other ELF executable or DSO.
459 bool lld::elf2::canBePreempted(const SymbolBody *Body, bool NeedsGot) {
460   if (!Body)
461     return false;  // Body is a local symbol.
462   if (Body->isShared())
463     return true;
464 
465   if (Body->isUndefined()) {
466     if (!Body->isWeak())
467       return true;
468 
469     // This is an horrible corner case. Ideally we would like to say that any
470     // undefined symbol can be preempted so that the dynamic linker has a
471     // chance of finding it at runtime.
472     //
473     // The problem is that the code sequence used to test for weak undef
474     // functions looks like
475     // if (func) func()
476     // If the code is -fPIC the first reference is a load from the got and
477     // everything works.
478     // If the code is not -fPIC there is no reasonable way to solve it:
479     // * A relocation writing to the text segment will fail (it is ro).
480     // * A copy relocation doesn't work for functions.
481     // * The trick of using a plt entry as the address would fail here since
482     //   the plt entry would have a non zero address.
483     // Since we cannot do anything better, we just resolve the symbol to 0 and
484     // don't produce a dynamic relocation.
485     return NeedsGot;
486   }
487   if (!Config->Shared)
488     return false;
489   return Body->getMostConstrainingVisibility() == STV_DEFAULT;
490 }
491 
492 template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
493   for (InputSection<ELFT> *C : Sections)
494     C->writeTo(Buf);
495 }
496 
497 template <bool Is64Bits>
498 StringTableSection<Is64Bits>::StringTableSection(bool Dynamic)
499     : OutputSectionBase<Is64Bits>(Dynamic ? ".dynstr" : ".strtab",
500                                   llvm::ELF::SHT_STRTAB,
501                                   Dynamic ? (uintX_t)llvm::ELF::SHF_ALLOC : 0),
502       Dynamic(Dynamic) {
503   this->Header.sh_addralign = 1;
504 }
505 
506 template <bool Is64Bits>
507 void StringTableSection<Is64Bits>::writeTo(uint8_t *Buf) {
508   StringRef Data = StrTabBuilder.data();
509   memcpy(Buf, Data.data(), Data.size());
510 }
511 
512 template <class ELFT> bool lld::elf2::includeInSymtab(const SymbolBody &B) {
513   if (!B.isUsedInRegularObj())
514     return false;
515 
516   // Don't include synthetic symbols like __init_array_start in every output.
517   if (auto *U = dyn_cast<DefinedAbsolute<ELFT>>(&B))
518     if (&U->Sym == &DefinedAbsolute<ELFT>::IgnoreUndef)
519       return false;
520 
521   return true;
522 }
523 
524 bool lld::elf2::includeInDynamicSymtab(const SymbolBody &B) {
525   uint8_t V = B.getMostConstrainingVisibility();
526   if (V != STV_DEFAULT && V != STV_PROTECTED)
527     return false;
528 
529   if (Config->ExportDynamic || Config->Shared)
530     return true;
531   return B.isUsedInDynamicReloc();
532 }
533 
534 template <class ELFT>
535 bool lld::elf2::shouldKeepInSymtab(const ObjectFile<ELFT> &File,
536                                    StringRef SymName,
537                                    const typename ELFFile<ELFT>::Elf_Sym &Sym) {
538   if (Sym.getType() == STT_SECTION)
539     return false;
540 
541   // If sym references a section in a discarded group, don't keep it.
542   uint32_t SecIndex = Sym.st_shndx;
543   if (SecIndex != SHN_ABS) {
544     if (SecIndex == SHN_XINDEX)
545       SecIndex = File.getObj().getExtendedSymbolTableIndex(
546           &Sym, File.getSymbolTable(), File.getSymbolTableShndx());
547     ArrayRef<InputSection<ELFT> *> Sections = File.getSections();
548     const InputSection<ELFT> *Section = Sections[SecIndex];
549     if (Section == &InputSection<ELFT>::Discarded)
550       return false;
551   }
552 
553   if (Config->DiscardNone)
554     return true;
555 
556   // ELF defines dynamic locals as symbols which name starts with ".L".
557   return !(Config->DiscardLocals && SymName.startswith(".L"));
558 }
559 
560 template <class ELFT>
561 SymbolTableSection<ELFT>::SymbolTableSection(
562     SymbolTable<ELFT> &Table, StringTableSection<ELFT::Is64Bits> &StrTabSec)
563     : OutputSectionBase<ELFT::Is64Bits>(
564           StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
565           StrTabSec.isDynamic() ? llvm::ELF::SHT_DYNSYM : llvm::ELF::SHT_SYMTAB,
566           StrTabSec.isDynamic() ? (uintX_t)llvm::ELF::SHF_ALLOC : 0),
567       Table(Table), StrTabSec(StrTabSec) {
568   typedef OutputSectionBase<ELFT::Is64Bits> Base;
569   typename Base::HeaderT &Header = this->Header;
570 
571   Header.sh_entsize = sizeof(Elf_Sym);
572   Header.sh_addralign = ELFT::Is64Bits ? 8 : 4;
573 }
574 
575 template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
576   this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
577   this->Header.sh_link = StrTabSec.getSectionIndex();
578   this->Header.sh_info = NumLocals + 1;
579 }
580 
581 template <class ELFT>
582 void SymbolTableSection<ELFT>::addSymbol(StringRef Name, bool isLocal) {
583   StrTabSec.add(Name);
584   ++NumVisible;
585   if (isLocal)
586     ++NumLocals;
587 }
588 
589 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
590   Buf += sizeof(Elf_Sym);
591 
592   // All symbols with STB_LOCAL binding precede the weak and global symbols.
593   // .dynsym only contains global symbols.
594   if (!Config->DiscardAll && !StrTabSec.isDynamic())
595     writeLocalSymbols(Buf);
596 
597   writeGlobalSymbols(Buf);
598 }
599 
600 template <class ELFT>
601 void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
602   // Iterate over all input object files to copy their local symbols
603   // to the output symbol table pointed by Buf.
604   for (const std::unique_ptr<ObjectFile<ELFT>> &File : Table.getObjectFiles()) {
605     Elf_Sym_Range Syms = File->getLocalSymbols();
606     for (const Elf_Sym &Sym : Syms) {
607       ErrorOr<StringRef> SymNameOrErr = Sym.getName(File->getStringTable());
608       error(SymNameOrErr);
609       StringRef SymName = *SymNameOrErr;
610       if (!shouldKeepInSymtab<ELFT>(*File, SymName, Sym))
611         continue;
612 
613       auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
614       Buf += sizeof(*ESym);
615       ESym->st_name = StrTabSec.getFileOff(SymName);
616       ESym->st_size = Sym.st_size;
617       ESym->setBindingAndType(Sym.getBinding(), Sym.getType());
618       uint32_t SecIndex = Sym.st_shndx;
619       uintX_t VA = Sym.st_value;
620       if (SecIndex == SHN_ABS) {
621         ESym->st_shndx = SHN_ABS;
622       } else {
623         if (SecIndex == SHN_XINDEX)
624           SecIndex = File->getObj().getExtendedSymbolTableIndex(
625               &Sym, File->getSymbolTable(), File->getSymbolTableShndx());
626         ArrayRef<InputSection<ELFT> *> Sections = File->getSections();
627         const InputSection<ELFT> *Sec = Sections[SecIndex];
628         ESym->st_shndx = Sec->OutSec->getSectionIndex();
629         VA += Sec->OutSec->getVA() + Sec->OutSecOff;
630       }
631       ESym->st_value = VA;
632     }
633   }
634 }
635 
636 template <class ELFT>
637 void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *&Buf) {
638   // Write the internal symbol table contents to the output symbol table
639   // pointed by Buf.
640   uint8_t *Start = Buf;
641   for (const std::pair<StringRef, Symbol *> &P : Table.getSymbols()) {
642     StringRef Name = P.first;
643     Symbol *Sym = P.second;
644     SymbolBody *Body = Sym->Body;
645     if (!includeInSymtab<ELFT>(*Body))
646       continue;
647     if (StrTabSec.isDynamic() && !includeInDynamicSymtab(*Body))
648       continue;
649 
650     auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
651     Buf += sizeof(*ESym);
652 
653     ESym->st_name = StrTabSec.getFileOff(Name);
654 
655     const OutputSectionBase<ELFT::Is64Bits> *OutSec = nullptr;
656     const InputSection<ELFT> *Section = nullptr;
657 
658     switch (Body->kind()) {
659     case SymbolBody::DefinedSyntheticKind:
660       OutSec = &cast<DefinedSynthetic<ELFT>>(Body)->Section;
661       break;
662     case SymbolBody::DefinedRegularKind:
663       Section = &cast<DefinedRegular<ELFT>>(Body)->Section;
664       break;
665     case SymbolBody::DefinedCommonKind:
666       OutSec = Out<ELFT>::Bss;
667       break;
668     case SymbolBody::UndefinedKind:
669     case SymbolBody::DefinedAbsoluteKind:
670     case SymbolBody::SharedKind:
671     case SymbolBody::LazyKind:
672       break;
673     }
674 
675     unsigned char Binding = Body->isWeak() ? STB_WEAK : STB_GLOBAL;
676     unsigned char Type = STT_NOTYPE;
677     uintX_t Size = 0;
678     if (const auto *EBody = dyn_cast<ELFSymbolBody<ELFT>>(Body)) {
679       const Elf_Sym &InputSym = EBody->Sym;
680       Binding = InputSym.getBinding();
681       Type = InputSym.getType();
682       Size = InputSym.st_size;
683     }
684 
685     unsigned char Visibility = Body->getMostConstrainingVisibility();
686     if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
687       Binding = STB_LOCAL;
688 
689     ESym->setBindingAndType(Binding, Type);
690     ESym->st_size = Size;
691     ESym->setVisibility(Visibility);
692     ESym->st_value = getSymVA<ELFT>(*Body);
693 
694     if (Section)
695       OutSec = Section->OutSec;
696 
697     if (isa<DefinedAbsolute<ELFT>>(Body))
698       ESym->st_shndx = SHN_ABS;
699     else if (OutSec)
700       ESym->st_shndx = OutSec->getSectionIndex();
701   }
702   if (!StrTabSec.isDynamic())
703     std::stable_sort(
704         reinterpret_cast<Elf_Sym *>(Start), reinterpret_cast<Elf_Sym *>(Buf),
705         [](const Elf_Sym &A, const Elf_Sym &B) -> bool {
706           return A.getBinding() == STB_LOCAL && B.getBinding() != STB_LOCAL;
707         });
708 }
709 
710 namespace lld {
711 namespace elf2 {
712 template class OutputSectionBase<false>;
713 template class OutputSectionBase<true>;
714 
715 template void OutputSectionBase<false>::writeHeaderTo<support::little>(
716     ELFFile<ELFType<support::little, false>>::Elf_Shdr *SHdr);
717 template void OutputSectionBase<true>::writeHeaderTo<support::little>(
718     ELFFile<ELFType<support::little, true>>::Elf_Shdr *SHdr);
719 template void OutputSectionBase<false>::writeHeaderTo<support::big>(
720     ELFFile<ELFType<support::big, false>>::Elf_Shdr *SHdr);
721 template void OutputSectionBase<true>::writeHeaderTo<support::big>(
722     ELFFile<ELFType<support::big, true>>::Elf_Shdr *SHdr);
723 
724 template class GotSection<ELF32LE>;
725 template class GotSection<ELF32BE>;
726 template class GotSection<ELF64LE>;
727 template class GotSection<ELF64BE>;
728 
729 template class PltSection<ELF32LE>;
730 template class PltSection<ELF32BE>;
731 template class PltSection<ELF64LE>;
732 template class PltSection<ELF64BE>;
733 
734 template class RelocationSection<ELF32LE>;
735 template class RelocationSection<ELF32BE>;
736 template class RelocationSection<ELF64LE>;
737 template class RelocationSection<ELF64BE>;
738 
739 template class InterpSection<false>;
740 template class InterpSection<true>;
741 
742 template class HashTableSection<ELF32LE>;
743 template class HashTableSection<ELF32BE>;
744 template class HashTableSection<ELF64LE>;
745 template class HashTableSection<ELF64BE>;
746 
747 template class DynamicSection<ELF32LE>;
748 template class DynamicSection<ELF32BE>;
749 template class DynamicSection<ELF64LE>;
750 template class DynamicSection<ELF64BE>;
751 
752 template class OutputSection<ELF32LE>;
753 template class OutputSection<ELF32BE>;
754 template class OutputSection<ELF64LE>;
755 template class OutputSection<ELF64BE>;
756 
757 template class StringTableSection<false>;
758 template class StringTableSection<true>;
759 
760 template class SymbolTableSection<ELF32LE>;
761 template class SymbolTableSection<ELF32BE>;
762 template class SymbolTableSection<ELF64LE>;
763 template class SymbolTableSection<ELF64BE>;
764 
765 template ELFFile<ELF32LE>::uintX_t getSymVA<ELF32LE>(const SymbolBody &);
766 template ELFFile<ELF32BE>::uintX_t getSymVA<ELF32BE>(const SymbolBody &);
767 template ELFFile<ELF64LE>::uintX_t getSymVA<ELF64LE>(const SymbolBody &);
768 template ELFFile<ELF64BE>::uintX_t getSymVA<ELF64BE>(const SymbolBody &);
769 
770 template ELFFile<ELF32LE>::uintX_t
771 getLocalRelTarget(const ObjectFile<ELF32LE> &,
772                   const ELFFile<ELF32LE>::Elf_Rel &);
773 
774 template ELFFile<ELF32BE>::uintX_t
775 getLocalRelTarget(const ObjectFile<ELF32BE> &,
776                   const ELFFile<ELF32BE>::Elf_Rel &);
777 
778 template ELFFile<ELF64LE>::uintX_t
779 getLocalRelTarget(const ObjectFile<ELF64LE> &,
780                   const ELFFile<ELF64LE>::Elf_Rel &);
781 
782 template ELFFile<ELF64BE>::uintX_t
783 getLocalRelTarget(const ObjectFile<ELF64BE> &,
784                   const ELFFile<ELF64BE>::Elf_Rel &);
785 
786 template bool includeInSymtab<ELF32LE>(const SymbolBody &);
787 template bool includeInSymtab<ELF32BE>(const SymbolBody &);
788 template bool includeInSymtab<ELF64LE>(const SymbolBody &);
789 template bool includeInSymtab<ELF64BE>(const SymbolBody &);
790 
791 template bool shouldKeepInSymtab<ELF32LE>(const ObjectFile<ELF32LE> &,
792                                           StringRef,
793                                           const ELFFile<ELF32LE>::Elf_Sym &);
794 template bool shouldKeepInSymtab<ELF32BE>(const ObjectFile<ELF32BE> &,
795                                           StringRef,
796                                           const ELFFile<ELF32BE>::Elf_Sym &);
797 template bool shouldKeepInSymtab<ELF64LE>(const ObjectFile<ELF64LE> &,
798                                           StringRef,
799                                           const ELFFile<ELF64LE>::Elf_Sym &);
800 template bool shouldKeepInSymtab<ELF64BE>(const ObjectFile<ELF64BE> &,
801                                           StringRef,
802                                           const ELFFile<ELF64BE>::Elf_Sym &);
803 }
804 }
805