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 #include "llvm/Support/MathExtras.h"
15 
16 using namespace llvm;
17 using namespace llvm::object;
18 using namespace llvm::support::endian;
19 using namespace llvm::ELF;
20 
21 using namespace lld;
22 using namespace lld::elf2;
23 
24 template <class ELFT>
25 OutputSectionBase<ELFT>::OutputSectionBase(StringRef Name, uint32_t sh_type,
26                                            uintX_t sh_flags)
27     : Name(Name) {
28   memset(&Header, 0, sizeof(Elf_Shdr));
29   Header.sh_type = sh_type;
30   Header.sh_flags = sh_flags;
31 }
32 
33 template <class ELFT>
34 GotPltSection<ELFT>::GotPltSection()
35     : OutputSectionBase<ELFT>(".got.plt", llvm::ELF::SHT_PROGBITS,
36                               llvm::ELF::SHF_ALLOC | llvm::ELF::SHF_WRITE) {
37   this->Header.sh_addralign = sizeof(uintX_t);
38 }
39 
40 template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody *Sym) {
41   Sym->GotPltIndex = Target->getGotPltHeaderEntriesNum() + Entries.size();
42   Entries.push_back(Sym);
43 }
44 
45 template <class ELFT> bool GotPltSection<ELFT>::empty() const {
46   return Entries.empty();
47 }
48 
49 template <class ELFT>
50 typename GotPltSection<ELFT>::uintX_t
51 GotPltSection<ELFT>::getEntryAddr(const SymbolBody &B) const {
52   return this->getVA() + B.GotPltIndex * sizeof(uintX_t);
53 }
54 
55 template <class ELFT> void GotPltSection<ELFT>::finalize() {
56   this->Header.sh_size =
57       (Target->getGotPltHeaderEntriesNum() + Entries.size()) * sizeof(uintX_t);
58 }
59 
60 template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
61   Target->writeGotPltHeaderEntries(Buf);
62   Buf += Target->getGotPltHeaderEntriesNum() * sizeof(uintX_t);
63   for (const SymbolBody *B : Entries) {
64     Target->writeGotPltEntry(Buf, Out<ELFT>::Plt->getEntryAddr(*B));
65     Buf += sizeof(uintX_t);
66   }
67 }
68 
69 template <class ELFT>
70 GotSection<ELFT>::GotSection()
71     : OutputSectionBase<ELFT>(".got", llvm::ELF::SHT_PROGBITS,
72                               llvm::ELF::SHF_ALLOC | llvm::ELF::SHF_WRITE) {
73   if (Config->EMachine == EM_MIPS)
74     this->Header.sh_flags |= llvm::ELF::SHF_MIPS_GPREL;
75   this->Header.sh_addralign = sizeof(uintX_t);
76 }
77 
78 template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody *Sym) {
79   Sym->GotIndex = Target->getGotHeaderEntriesNum() + Entries.size();
80   Entries.push_back(Sym);
81 }
82 
83 template <class ELFT> void GotSection<ELFT>::addDynTlsEntry(SymbolBody *Sym) {
84   Sym->GotIndex = Target->getGotHeaderEntriesNum() + Entries.size();
85   // Global Dynamic TLS entries take two GOT slots.
86   Entries.push_back(Sym);
87   Entries.push_back(nullptr);
88 }
89 
90 template <class ELFT> uint32_t GotSection<ELFT>::addLocalModuleTlsIndex() {
91   Entries.push_back(nullptr);
92   Entries.push_back(nullptr);
93   return (Entries.size() - 2) * sizeof(uintX_t);
94 }
95 
96 template <class ELFT>
97 typename GotSection<ELFT>::uintX_t
98 GotSection<ELFT>::getEntryAddr(const SymbolBody &B) const {
99   return this->getVA() + B.GotIndex * sizeof(uintX_t);
100 }
101 
102 template <class ELFT>
103 const SymbolBody *GotSection<ELFT>::getMipsFirstGlobalEntry() const {
104   return Entries.empty() ? nullptr : Entries.front();
105 }
106 
107 template <class ELFT>
108 unsigned GotSection<ELFT>::getMipsLocalEntriesNum() const {
109   // TODO: Update when the suppoort of GOT entries for local symbols is added.
110   return Target->getGotHeaderEntriesNum();
111 }
112 
113 template <class ELFT> void GotSection<ELFT>::finalize() {
114   this->Header.sh_size =
115       (Target->getGotHeaderEntriesNum() + Entries.size()) * sizeof(uintX_t);
116 }
117 
118 template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
119   Target->writeGotHeaderEntries(Buf);
120   Buf += Target->getGotHeaderEntriesNum() * sizeof(uintX_t);
121   for (const SymbolBody *B : Entries) {
122     uint8_t *Entry = Buf;
123     Buf += sizeof(uintX_t);
124     if (!B)
125       continue;
126     // MIPS has special rules to fill up GOT entries.
127     // See "Global Offset Table" in Chapter 5 in the following document
128     // for detailed description:
129     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
130     // As the first approach, we can just store addresses for all symbols.
131     if (Config->EMachine != EM_MIPS && canBePreempted(B, false))
132       continue; // The dynamic linker will take care of it.
133     uintX_t VA = getSymVA<ELFT>(*B);
134     write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
135   }
136 }
137 
138 template <class ELFT>
139 PltSection<ELFT>::PltSection()
140     : OutputSectionBase<ELFT>(".plt", llvm::ELF::SHT_PROGBITS,
141                               llvm::ELF::SHF_ALLOC | llvm::ELF::SHF_EXECINSTR) {
142   this->Header.sh_addralign = 16;
143 }
144 
145 template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
146   size_t Off = 0;
147   bool LazyReloc = Target->supportsLazyRelocations();
148   if (LazyReloc) {
149     // First write PLT[0] entry which is special.
150     Target->writePltZeroEntry(Buf, Out<ELFT>::GotPlt->getVA(), this->getVA());
151     Off += Target->getPltZeroEntrySize();
152   }
153   for (const SymbolBody *E : Entries) {
154     uint64_t Got = LazyReloc ? Out<ELFT>::GotPlt->getEntryAddr(*E)
155                              : Out<ELFT>::Got->getEntryAddr(*E);
156     uint64_t Plt = this->getVA() + Off;
157     Target->writePltEntry(Buf + Off, Got, Plt, E->PltIndex);
158     Off += Target->getPltEntrySize();
159   }
160 }
161 
162 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody *Sym) {
163   Sym->PltIndex = Entries.size();
164   Entries.push_back(Sym);
165 }
166 
167 template <class ELFT>
168 typename PltSection<ELFT>::uintX_t
169 PltSection<ELFT>::getEntryAddr(const SymbolBody &B) const {
170   return this->getVA() + Target->getPltZeroEntrySize() +
171          B.PltIndex * Target->getPltEntrySize();
172 }
173 
174 template <class ELFT> void PltSection<ELFT>::finalize() {
175   this->Header.sh_size = Target->getPltZeroEntrySize() +
176                          Entries.size() * Target->getPltEntrySize();
177 }
178 
179 template <class ELFT>
180 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool IsRela)
181     : OutputSectionBase<ELFT>(Name,
182                               IsRela ? llvm::ELF::SHT_RELA : llvm::ELF::SHT_REL,
183                               llvm::ELF::SHF_ALLOC),
184       IsRela(IsRela) {
185   this->Header.sh_entsize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
186   this->Header.sh_addralign = ELFT::Is64Bits ? 8 : 4;
187 }
188 
189 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
190   const unsigned EntrySize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
191   for (const DynamicReloc<ELFT> &Rel : Relocs) {
192     auto *P = reinterpret_cast<Elf_Rel *>(Buf);
193     Buf += EntrySize;
194 
195     // Skip placeholder for global dynamic TLS relocation pair. It was already
196     // handled by the previous relocation.
197     if (!Rel.C || !Rel.RI)
198       continue;
199 
200     InputSectionBase<ELFT> &C = *Rel.C;
201     const Elf_Rel &RI = *Rel.RI;
202     uint32_t SymIndex = RI.getSymbol(Config->Mips64EL);
203     const ObjectFile<ELFT> &File = *C.getFile();
204     SymbolBody *Body = File.getSymbolBody(SymIndex);
205     if (Body)
206       Body = Body->repl();
207 
208     uint32_t Type = RI.getType(Config->Mips64EL);
209 
210     if (Target->isTlsLocalDynamicReloc(Type)) {
211       P->setSymbolAndType(0, Target->getTlsModuleIndexReloc(),
212                           Config->Mips64EL);
213       P->r_offset =
214           Out<ELFT>::Got->getVA() + Out<ELFT>::LocalModuleTlsIndexOffset;
215       continue;
216     }
217 
218     if (Body && Target->isTlsGlobalDynamicReloc(Type)) {
219       P->setSymbolAndType(Body->getDynamicSymbolTableIndex(),
220                           Target->getTlsModuleIndexReloc(), Config->Mips64EL);
221       P->r_offset = Out<ELFT>::Got->getEntryAddr(*Body);
222       auto *PNext = reinterpret_cast<Elf_Rel *>(Buf);
223       PNext->setSymbolAndType(Body->getDynamicSymbolTableIndex(),
224                               Target->getTlsOffsetReloc(), Config->Mips64EL);
225       PNext->r_offset = Out<ELFT>::Got->getEntryAddr(*Body) + sizeof(uintX_t);
226       continue;
227     }
228 
229     bool NeedsCopy = Body && Target->relocNeedsCopy(Type, *Body);
230     bool NeedsGot = Body && Target->relocNeedsGot(Type, *Body);
231     bool CanBePreempted = canBePreempted(Body, NeedsGot);
232     bool LazyReloc = Body && Target->supportsLazyRelocations() &&
233                      Target->relocNeedsPlt(Type, *Body);
234 
235     if (CanBePreempted) {
236       unsigned GotReloc =
237           Body->isTLS() ? Target->getTlsGotReloc() : Target->getGotReloc();
238       if (NeedsGot)
239         P->setSymbolAndType(Body->getDynamicSymbolTableIndex(),
240                             LazyReloc ? Target->getPltReloc() : GotReloc,
241                             Config->Mips64EL);
242       else
243         P->setSymbolAndType(Body->getDynamicSymbolTableIndex(),
244                             NeedsCopy ? Target->getCopyReloc() : Type,
245                             Config->Mips64EL);
246     } else {
247       P->setSymbolAndType(0, Target->getRelativeReloc(), Config->Mips64EL);
248     }
249 
250     if (NeedsGot) {
251       if (LazyReloc)
252         P->r_offset = Out<ELFT>::GotPlt->getEntryAddr(*Body);
253       else
254         P->r_offset = Out<ELFT>::Got->getEntryAddr(*Body);
255     } else if (NeedsCopy) {
256       P->r_offset = Out<ELFT>::Bss->getVA() +
257                     dyn_cast<SharedSymbol<ELFT>>(Body)->OffsetInBSS;
258     } else {
259       P->r_offset = C.getOffset(RI.r_offset) + C.OutSec->getVA();
260     }
261 
262     uintX_t OrigAddend = 0;
263     if (IsRela && !NeedsGot)
264       OrigAddend = static_cast<const Elf_Rela &>(RI).r_addend;
265 
266     uintX_t Addend;
267     if (NeedsCopy)
268       Addend = 0;
269     else if (CanBePreempted)
270       Addend = OrigAddend;
271     else if (Body)
272       Addend = getSymVA<ELFT>(cast<ELFSymbolBody<ELFT>>(*Body)) + OrigAddend;
273     else if (IsRela)
274       Addend = getLocalRelTarget(File, static_cast<const Elf_Rela &>(RI));
275     else
276       Addend = getLocalRelTarget(File, RI);
277 
278     if (IsRela)
279       static_cast<Elf_Rela *>(P)->r_addend = Addend;
280   }
281 }
282 
283 template <class ELFT> void RelocationSection<ELFT>::finalize() {
284   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
285   this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
286 }
287 
288 template <class ELFT>
289 InterpSection<ELFT>::InterpSection()
290     : OutputSectionBase<ELFT>(".interp", llvm::ELF::SHT_PROGBITS,
291                               llvm::ELF::SHF_ALLOC) {
292   this->Header.sh_size = Config->DynamicLinker.size() + 1;
293   this->Header.sh_addralign = 1;
294 }
295 
296 template <class ELFT>
297 void OutputSectionBase<ELFT>::writeHeaderTo(Elf_Shdr *SHdr) {
298   Header.sh_name = Out<ELFT>::ShStrTab->getOffset(Name);
299   *SHdr = Header;
300 }
301 
302 template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) {
303   memcpy(Buf, Config->DynamicLinker.data(), Config->DynamicLinker.size());
304 }
305 
306 template <class ELFT>
307 HashTableSection<ELFT>::HashTableSection()
308     : OutputSectionBase<ELFT>(".hash", llvm::ELF::SHT_HASH,
309                               llvm::ELF::SHF_ALLOC) {
310   this->Header.sh_entsize = sizeof(Elf_Word);
311   this->Header.sh_addralign = sizeof(Elf_Word);
312 }
313 
314 static uint32_t hashSysv(StringRef Name) {
315   uint32_t H = 0;
316   for (char C : Name) {
317     H = (H << 4) + C;
318     uint32_t G = H & 0xf0000000;
319     if (G)
320       H ^= G >> 24;
321     H &= ~G;
322   }
323   return H;
324 }
325 
326 template <class ELFT> void HashTableSection<ELFT>::finalize() {
327   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
328 
329   unsigned NumEntries = 2;                 // nbucket and nchain.
330   NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
331 
332   // Create as many buckets as there are symbols.
333   // FIXME: This is simplistic. We can try to optimize it, but implementing
334   // support for SHT_GNU_HASH is probably even more profitable.
335   NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
336   this->Header.sh_size = NumEntries * sizeof(Elf_Word);
337 }
338 
339 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
340   unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
341   auto *P = reinterpret_cast<Elf_Word *>(Buf);
342   *P++ = NumSymbols; // nbucket
343   *P++ = NumSymbols; // nchain
344 
345   Elf_Word *Buckets = P;
346   Elf_Word *Chains = P + NumSymbols;
347 
348   for (SymbolBody *Body : Out<ELFT>::DynSymTab->getSymbols()) {
349     StringRef Name = Body->getName();
350     unsigned I = Body->getDynamicSymbolTableIndex();
351     uint32_t Hash = hashSysv(Name) % NumSymbols;
352     Chains[I] = Buckets[Hash];
353     Buckets[Hash] = I;
354   }
355 }
356 
357 static uint32_t hashGnu(StringRef Name) {
358   uint32_t H = 5381;
359   for (uint8_t C : Name)
360     H = (H << 5) + H + C;
361   return H;
362 }
363 
364 template <class ELFT>
365 GnuHashTableSection<ELFT>::GnuHashTableSection()
366     : OutputSectionBase<ELFT>(".gnu.hash", llvm::ELF::SHT_GNU_HASH,
367                               llvm::ELF::SHF_ALLOC) {
368   this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4;
369   this->Header.sh_addralign = ELFT::Is64Bits ? 8 : 4;
370 }
371 
372 template <class ELFT>
373 unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
374   if (!NumHashed)
375     return 0;
376 
377   // These values are prime numbers which are not greater than 2^(N-1) + 1.
378   // In result, for any particular NumHashed we return a prime number
379   // which is not greater than NumHashed.
380   static const unsigned Primes[] = {
381       1,   1,    3,    3,    7,    13,    31,    61,    127,   251,
382       509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
383 
384   return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
385                                    array_lengthof(Primes) - 1)];
386 }
387 
388 // Bloom filter estimation: at least 8 bits for each hashed symbol.
389 // GNU Hash table requirement: it should be a power of 2,
390 //   the minimum value is 1, even for an empty table.
391 // Expected results for a 32-bit target:
392 //   calcMaskWords(0..4)   = 1
393 //   calcMaskWords(5..8)   = 2
394 //   calcMaskWords(9..16)  = 4
395 // For a 64-bit target:
396 //   calcMaskWords(0..8)   = 1
397 //   calcMaskWords(9..16)  = 2
398 //   calcMaskWords(17..32) = 4
399 template <class ELFT>
400 unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
401   if (!NumHashed)
402     return 1;
403   return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
404 }
405 
406 template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
407   unsigned NumHashed = HashedSymbols.size();
408   NBuckets = calcNBuckets(NumHashed);
409   MaskWords = calcMaskWords(NumHashed);
410   // Second hash shift estimation: just predefined values.
411   Shift2 = ELFT::Is64Bits ? 6 : 5;
412 
413   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
414   this->Header.sh_size = sizeof(Elf_Word) * 4            // Header
415                          + sizeof(Elf_Off) * MaskWords   // Bloom Filter
416                          + sizeof(Elf_Word) * NBuckets   // Hash Buckets
417                          + sizeof(Elf_Word) * NumHashed; // Hash Values
418 }
419 
420 template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
421   writeHeader(Buf);
422   if (HashedSymbols.empty())
423     return;
424   writeBloomFilter(Buf);
425   writeHashTable(Buf);
426 }
427 
428 template <class ELFT>
429 void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
430   auto *P = reinterpret_cast<Elf_Word *>(Buf);
431   *P++ = NBuckets;
432   *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - HashedSymbols.size();
433   *P++ = MaskWords;
434   *P++ = Shift2;
435   Buf = reinterpret_cast<uint8_t *>(P);
436 }
437 
438 template <class ELFT>
439 void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
440   unsigned C = sizeof(Elf_Off) * 8;
441 
442   auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
443   for (const HashedSymbolData &Item : HashedSymbols) {
444     size_t Pos = (Item.Hash / C) & (MaskWords - 1);
445     uintX_t V = (uintX_t(1) << (Item.Hash % C)) |
446                 (uintX_t(1) << ((Item.Hash >> Shift2) % C));
447     Masks[Pos] |= V;
448   }
449   Buf += sizeof(Elf_Off) * MaskWords;
450 }
451 
452 template <class ELFT>
453 void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
454   Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
455   Elf_Word *Values = Buckets + NBuckets;
456 
457   int PrevBucket = -1;
458   int I = 0;
459   for (const HashedSymbolData &Item : HashedSymbols) {
460     int Bucket = Item.Hash % NBuckets;
461     assert(PrevBucket <= Bucket);
462     if (Bucket != PrevBucket) {
463       Buckets[Bucket] = Item.Body->getDynamicSymbolTableIndex();
464       PrevBucket = Bucket;
465       if (I > 0)
466         Values[I - 1] |= 1;
467     }
468     Values[I] = Item.Hash & ~1;
469     ++I;
470   }
471   if (I > 0)
472     Values[I - 1] |= 1;
473 }
474 
475 static bool includeInGnuHashTable(SymbolBody *B) {
476   // Assume that includeInDynamicSymtab() is already checked.
477   return !B->isUndefined();
478 }
479 
480 template <class ELFT>
481 void GnuHashTableSection<ELFT>::addSymbols(std::vector<SymbolBody *> &Symbols) {
482   std::vector<SymbolBody *> NotHashed;
483   NotHashed.reserve(Symbols.size());
484   HashedSymbols.reserve(Symbols.size());
485   for (SymbolBody *B : Symbols) {
486     if (includeInGnuHashTable(B))
487       HashedSymbols.push_back(HashedSymbolData{B, hashGnu(B->getName())});
488     else
489       NotHashed.push_back(B);
490   }
491   if (HashedSymbols.empty())
492     return;
493 
494   unsigned NBuckets = calcNBuckets(HashedSymbols.size());
495   std::stable_sort(HashedSymbols.begin(), HashedSymbols.end(),
496                    [&](const HashedSymbolData &L, const HashedSymbolData &R) {
497                      return L.Hash % NBuckets < R.Hash % NBuckets;
498                    });
499 
500   Symbols = std::move(NotHashed);
501   for (const HashedSymbolData &Item : HashedSymbols)
502     Symbols.push_back(Item.Body);
503 }
504 
505 template <class ELFT>
506 DynamicSection<ELFT>::DynamicSection(SymbolTable<ELFT> &SymTab)
507     : OutputSectionBase<ELFT>(".dynamic", llvm::ELF::SHT_DYNAMIC,
508                               llvm::ELF::SHF_ALLOC | llvm::ELF::SHF_WRITE),
509       SymTab(SymTab) {
510   Elf_Shdr &Header = this->Header;
511   Header.sh_addralign = ELFT::Is64Bits ? 8 : 4;
512   Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
513 
514   // .dynamic section is not writable on MIPS.
515   // See "Special Section" in Chapter 4 in the following document:
516   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
517   if (Config->EMachine == EM_MIPS)
518     Header.sh_flags = llvm::ELF::SHF_ALLOC;
519 }
520 
521 template <class ELFT> void DynamicSection<ELFT>::finalize() {
522   if (this->Header.sh_size)
523     return; // Already finalized.
524 
525   Elf_Shdr &Header = this->Header;
526   Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
527 
528   unsigned NumEntries = 0;
529   if (Out<ELFT>::RelaDyn->hasRelocs()) {
530     ++NumEntries; // DT_RELA / DT_REL
531     ++NumEntries; // DT_RELASZ / DT_RELSZ
532     ++NumEntries; // DT_RELAENT / DT_RELENT
533   }
534   if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
535     ++NumEntries; // DT_JMPREL
536     ++NumEntries; // DT_PLTRELSZ
537     ++NumEntries; // DT_PLTGOT / DT_MIPS_PLTGOT
538     ++NumEntries; // DT_PLTREL
539   }
540 
541   ++NumEntries; // DT_SYMTAB
542   ++NumEntries; // DT_SYMENT
543   ++NumEntries; // DT_STRTAB
544   ++NumEntries; // DT_STRSZ
545   if (Out<ELFT>::GnuHashTab)
546     ++NumEntries; // DT_GNU_HASH
547   if (Out<ELFT>::HashTab)
548     ++NumEntries; // DT_HASH
549 
550   if (!Config->RPath.empty()) {
551     ++NumEntries; // DT_RUNPATH / DT_RPATH
552     Out<ELFT>::DynStrTab->add(Config->RPath);
553   }
554 
555   if (!Config->SoName.empty()) {
556     ++NumEntries; // DT_SONAME
557     Out<ELFT>::DynStrTab->add(Config->SoName);
558   }
559 
560   if (PreInitArraySec)
561     NumEntries += 2;
562   if (InitArraySec)
563     NumEntries += 2;
564   if (FiniArraySec)
565     NumEntries += 2;
566 
567   for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles()) {
568     if (!F->isNeeded())
569       continue;
570     Out<ELFT>::DynStrTab->add(F->getSoName());
571     ++NumEntries;
572   }
573 
574   if (Symbol *S = SymTab.getSymbols().lookup(Config->Init))
575     InitSym = dyn_cast<ELFSymbolBody<ELFT>>(S->Body);
576   if (Symbol *S = SymTab.getSymbols().lookup(Config->Fini))
577     FiniSym = dyn_cast<ELFSymbolBody<ELFT>>(S->Body);
578   if (InitSym)
579     ++NumEntries; // DT_INIT
580   if (FiniSym)
581     ++NumEntries; // DT_FINI
582 
583   if (Config->Bsymbolic)
584     DtFlags |= DF_SYMBOLIC;
585   if (Config->ZNodelete)
586     DtFlags1 |= DF_1_NODELETE;
587   if (Config->ZNow) {
588     DtFlags |= DF_BIND_NOW;
589     DtFlags1 |= DF_1_NOW;
590   }
591   if (Config->ZOrigin) {
592     DtFlags |= DF_ORIGIN;
593     DtFlags1 |= DF_1_ORIGIN;
594   }
595 
596   if (DtFlags)
597     ++NumEntries; // DT_FLAGS
598   if (DtFlags1)
599     ++NumEntries; // DT_FLAGS_1
600 
601   if (Config->EMachine == EM_MIPS) {
602     ++NumEntries; // DT_MIPS_RLD_VERSION
603     ++NumEntries; // DT_MIPS_FLAGS
604     ++NumEntries; // DT_MIPS_BASE_ADDRESS
605     ++NumEntries; // DT_MIPS_SYMTABNO
606     ++NumEntries; // DT_MIPS_LOCAL_GOTNO
607     ++NumEntries; // DT_MIPS_GOTSYM;
608     ++NumEntries; // DT_PLTGOT
609     if (Out<ELFT>::MipsRldMap)
610       ++NumEntries; // DT_MIPS_RLD_MAP
611   }
612 
613   ++NumEntries; // DT_NULL
614 
615   Header.sh_size = NumEntries * Header.sh_entsize;
616 }
617 
618 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
619   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
620 
621   auto WritePtr = [&](int32_t Tag, uint64_t Val) {
622     P->d_tag = Tag;
623     P->d_un.d_ptr = Val;
624     ++P;
625   };
626 
627   auto WriteVal = [&](int32_t Tag, uint32_t Val) {
628     P->d_tag = Tag;
629     P->d_un.d_val = Val;
630     ++P;
631   };
632 
633   if (Out<ELFT>::RelaDyn->hasRelocs()) {
634     bool IsRela = Out<ELFT>::RelaDyn->isRela();
635     WritePtr(IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn->getVA());
636     WriteVal(IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize());
637     WriteVal(IsRela ? DT_RELAENT : DT_RELENT,
638              IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel));
639   }
640   if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
641     WritePtr(DT_JMPREL, Out<ELFT>::RelaPlt->getVA());
642     WriteVal(DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize());
643     // On MIPS, the address of the .got.plt section is stored in
644     // the DT_MIPS_PLTGOT entry because the DT_PLTGOT entry points to
645     // the .got section. See "Dynamic Section" in the following document:
646     // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
647     WritePtr((Config->EMachine == EM_MIPS) ? DT_MIPS_PLTGOT : DT_PLTGOT,
648              Out<ELFT>::GotPlt->getVA());
649     WriteVal(DT_PLTREL, Out<ELFT>::RelaPlt->isRela() ? DT_RELA : DT_REL);
650   }
651 
652   WritePtr(DT_SYMTAB, Out<ELFT>::DynSymTab->getVA());
653   WritePtr(DT_SYMENT, sizeof(Elf_Sym));
654   WritePtr(DT_STRTAB, Out<ELFT>::DynStrTab->getVA());
655   WriteVal(DT_STRSZ, Out<ELFT>::DynStrTab->data().size());
656   if (Out<ELFT>::GnuHashTab)
657     WritePtr(DT_GNU_HASH, Out<ELFT>::GnuHashTab->getVA());
658   if (Out<ELFT>::HashTab)
659     WritePtr(DT_HASH, Out<ELFT>::HashTab->getVA());
660 
661   // If --enable-new-dtags is set, lld emits DT_RUNPATH
662   // instead of DT_RPATH. The two tags are functionally
663   // equivalent except for the following:
664   // - DT_RUNPATH is searched after LD_LIBRARY_PATH, while
665   //   DT_RPATH is searched before.
666   // - DT_RUNPATH is used only to search for direct
667   //   dependencies of the object it's contained in, while
668   //   DT_RPATH is used for indirect dependencies as well.
669   if (!Config->RPath.empty())
670     WriteVal(Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
671              Out<ELFT>::DynStrTab->getOffset(Config->RPath));
672 
673   if (!Config->SoName.empty())
674     WriteVal(DT_SONAME, Out<ELFT>::DynStrTab->getOffset(Config->SoName));
675 
676   auto WriteArray = [&](int32_t T1, int32_t T2,
677                         const OutputSectionBase<ELFT> *Sec) {
678     if (!Sec)
679       return;
680     WritePtr(T1, Sec->getVA());
681     WriteVal(T2, Sec->getSize());
682   };
683   WriteArray(DT_PREINIT_ARRAY, DT_PREINIT_ARRAYSZ, PreInitArraySec);
684   WriteArray(DT_INIT_ARRAY, DT_INIT_ARRAYSZ, InitArraySec);
685   WriteArray(DT_FINI_ARRAY, DT_FINI_ARRAYSZ, FiniArraySec);
686 
687   for (const std::unique_ptr<SharedFile<ELFT>> &F : SymTab.getSharedFiles())
688     if (F->isNeeded())
689       WriteVal(DT_NEEDED, Out<ELFT>::DynStrTab->getOffset(F->getSoName()));
690 
691   if (InitSym)
692     WritePtr(DT_INIT, getSymVA<ELFT>(*InitSym));
693   if (FiniSym)
694     WritePtr(DT_FINI, getSymVA<ELFT>(*FiniSym));
695   if (DtFlags)
696     WriteVal(DT_FLAGS, DtFlags);
697   if (DtFlags1)
698     WriteVal(DT_FLAGS_1, DtFlags1);
699 
700   // See "Dynamic Section" in Chapter 5 in the following document
701   // for detailed description:
702   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
703   if (Config->EMachine == EM_MIPS) {
704     WriteVal(DT_MIPS_RLD_VERSION, 1);
705     WriteVal(DT_MIPS_FLAGS, RHF_NOTPOT);
706     WritePtr(DT_MIPS_BASE_ADDRESS, Target->getVAStart());
707     WriteVal(DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols());
708     WriteVal(DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum());
709     if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
710       WriteVal(DT_MIPS_GOTSYM, B->getDynamicSymbolTableIndex());
711     else
712       WriteVal(DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols());
713     WritePtr(DT_PLTGOT, Out<ELFT>::Got->getVA());
714     if (Out<ELFT>::MipsRldMap)
715       WritePtr(DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap->getVA());
716   }
717 
718   WriteVal(DT_NULL, 0);
719 }
720 
721 template <class ELFT>
722 OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t sh_type,
723                                    uintX_t sh_flags)
724     : OutputSectionBase<ELFT>(Name, sh_type, sh_flags) {}
725 
726 template <class ELFT>
727 void OutputSection<ELFT>::addSection(InputSection<ELFT> *C) {
728   Sections.push_back(C);
729   C->OutSec = this;
730   uint32_t Align = C->getAlign();
731   if (Align > this->Header.sh_addralign)
732     this->Header.sh_addralign = Align;
733 
734   uintX_t Off = this->Header.sh_size;
735   Off = RoundUpToAlignment(Off, Align);
736   C->OutSecOff = Off;
737   Off += C->getSize();
738   this->Header.sh_size = Off;
739 }
740 
741 template <class ELFT>
742 typename ELFFile<ELFT>::uintX_t lld::elf2::getSymVA(const SymbolBody &S) {
743   switch (S.kind()) {
744   case SymbolBody::DefinedSyntheticKind: {
745     auto &D = cast<DefinedSynthetic<ELFT>>(S);
746     return D.Section.getVA() + D.Sym.st_value;
747   }
748   case SymbolBody::DefinedAbsoluteKind:
749     return cast<DefinedAbsolute<ELFT>>(S).Sym.st_value;
750   case SymbolBody::DefinedRegularKind: {
751     const auto &DR = cast<DefinedRegular<ELFT>>(S);
752     InputSectionBase<ELFT> &SC = DR.Section;
753     if (DR.Sym.getType() == STT_TLS)
754       return SC.OutSec->getVA() + SC.getOffset(DR.Sym) -
755              Out<ELFT>::TlsPhdr->p_vaddr;
756     return SC.OutSec->getVA() + SC.getOffset(DR.Sym);
757   }
758   case SymbolBody::DefinedCommonKind:
759     return Out<ELFT>::Bss->getVA() + cast<DefinedCommon<ELFT>>(S).OffsetInBSS;
760   case SymbolBody::SharedKind: {
761     auto &SS = cast<SharedSymbol<ELFT>>(S);
762     if (SS.needsCopy())
763       return Out<ELFT>::Bss->getVA() + SS.OffsetInBSS;
764     return 0;
765   }
766   case SymbolBody::UndefinedKind:
767     return 0;
768   case SymbolBody::LazyKind:
769     assert(S.isUsedInRegularObj() && "Lazy symbol reached writer");
770     return 0;
771   }
772   llvm_unreachable("Invalid symbol kind");
773 }
774 
775 // Returns a VA which a relocatin RI refers to. Used only for local symbols.
776 // For non-local symbols, use getSymVA instead.
777 template <class ELFT, bool IsRela>
778 typename ELFFile<ELFT>::uintX_t
779 lld::elf2::getLocalRelTarget(const ObjectFile<ELFT> &File,
780                              const Elf_Rel_Impl<ELFT, IsRela> &RI) {
781   typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
782   typedef typename ELFFile<ELFT>::uintX_t uintX_t;
783 
784   uintX_t Addend = getAddend<ELFT>(RI);
785 
786   // PPC64 has a special relocation representing the TOC base pointer
787   // that does not have a corresponding symbol.
788   if (Config->EMachine == EM_PPC64 && RI.getType(false) == R_PPC64_TOC)
789     return getPPC64TocBase() + Addend;
790 
791   const Elf_Sym *Sym =
792       File.getObj().getRelocationSymbol(&RI, File.getSymbolTable());
793 
794   if (!Sym)
795     error("Unsupported relocation without symbol");
796 
797   InputSectionBase<ELFT> *Section = File.getSection(*Sym);
798 
799   if (Sym->getType() == STT_TLS)
800     return (Section->OutSec->getVA() + Section->getOffset(*Sym) + Addend) -
801            Out<ELF64LE>::TlsPhdr->p_vaddr;
802 
803   // According to the ELF spec reference to a local symbol from outside
804   // the group are not allowed. Unfortunately .eh_frame breaks that rule
805   // and must be treated specially. For now we just replace the symbol with
806   // 0.
807   if (Section == &InputSection<ELFT>::Discarded || !Section->isLive())
808     return Addend;
809 
810   uintX_t VA = Section->OutSec->getVA();
811   if (isa<InputSection<ELFT>>(Section))
812     return VA + Section->getOffset(*Sym) + Addend;
813 
814   uintX_t Offset = Sym->st_value;
815   if (Sym->getType() == STT_SECTION) {
816     Offset += Addend;
817     Addend = 0;
818   }
819   return VA + cast<MergeInputSection<ELFT>>(Section)->getOffset(Offset) +
820          Addend;
821 }
822 
823 // Returns true if a symbol can be replaced at load-time by a symbol
824 // with the same name defined in other ELF executable or DSO.
825 bool lld::elf2::canBePreempted(const SymbolBody *Body, bool NeedsGot) {
826   if (!Body)
827     return false;  // Body is a local symbol.
828   if (Body->isShared())
829     return true;
830 
831   if (Body->isUndefined()) {
832     if (!Body->isWeak())
833       return true;
834 
835     // This is an horrible corner case. Ideally we would like to say that any
836     // undefined symbol can be preempted so that the dynamic linker has a
837     // chance of finding it at runtime.
838     //
839     // The problem is that the code sequence used to test for weak undef
840     // functions looks like
841     // if (func) func()
842     // If the code is -fPIC the first reference is a load from the got and
843     // everything works.
844     // If the code is not -fPIC there is no reasonable way to solve it:
845     // * A relocation writing to the text segment will fail (it is ro).
846     // * A copy relocation doesn't work for functions.
847     // * The trick of using a plt entry as the address would fail here since
848     //   the plt entry would have a non zero address.
849     // Since we cannot do anything better, we just resolve the symbol to 0 and
850     // don't produce a dynamic relocation.
851     //
852     // As an extra hack, assume that if we are producing a shared library the
853     // user knows what he or she is doing and can handle a dynamic relocation.
854     return Config->Shared || NeedsGot;
855   }
856   if (!Config->Shared)
857     return false;
858   return Body->getVisibility() == STV_DEFAULT;
859 }
860 
861 template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
862   for (InputSection<ELFT> *C : Sections)
863     C->writeTo(Buf);
864 }
865 
866 template <class ELFT>
867 EHOutputSection<ELFT>::EHOutputSection(StringRef Name, uint32_t sh_type,
868                                        uintX_t sh_flags)
869     : OutputSectionBase<ELFT>(Name, sh_type, sh_flags) {}
870 
871 template <class ELFT>
872 EHRegion<ELFT>::EHRegion(EHInputSection<ELFT> *S, unsigned Index)
873     : S(S), Index(Index) {}
874 
875 template <class ELFT> StringRef EHRegion<ELFT>::data() const {
876   ArrayRef<uint8_t> SecData = S->getSectionData();
877   ArrayRef<std::pair<uintX_t, uintX_t>> Offsets = S->Offsets;
878   size_t Start = Offsets[Index].first;
879   size_t End =
880       Index == Offsets.size() - 1 ? SecData.size() : Offsets[Index + 1].first;
881   return StringRef((const char *)SecData.data() + Start, End - Start);
882 }
883 
884 template <class ELFT>
885 Cie<ELFT>::Cie(EHInputSection<ELFT> *S, unsigned Index)
886     : EHRegion<ELFT>(S, Index) {}
887 
888 template <class ELFT>
889 template <bool IsRela>
890 void EHOutputSection<ELFT>::addSectionAux(
891     EHInputSection<ELFT> *S,
892     iterator_range<const Elf_Rel_Impl<ELFT, IsRela> *> Rels) {
893   const endianness E = ELFT::TargetEndianness;
894 
895   S->OutSec = this;
896   uint32_t Align = S->getAlign();
897   if (Align > this->Header.sh_addralign)
898     this->Header.sh_addralign = Align;
899 
900   Sections.push_back(S);
901 
902   ArrayRef<uint8_t> SecData = S->getSectionData();
903   ArrayRef<uint8_t> D = SecData;
904   uintX_t Offset = 0;
905   auto RelI = Rels.begin();
906   auto RelE = Rels.end();
907 
908   DenseMap<unsigned, unsigned> OffsetToIndex;
909   while (!D.empty()) {
910     if (D.size() < 4)
911       error("Truncated CIE/FDE length");
912     uint32_t Length = read32<E>(D.data());
913     Length += 4;
914 
915     unsigned Index = S->Offsets.size();
916     S->Offsets.push_back(std::make_pair(Offset, -1));
917 
918     if (Length > D.size())
919       error("CIE/FIE ends past the end of the section");
920     StringRef Entry((const char *)D.data(), Length);
921 
922     while (RelI != RelE && RelI->r_offset < Offset)
923       ++RelI;
924     uintX_t NextOffset = Offset + Length;
925     bool HasReloc = RelI != RelE && RelI->r_offset < NextOffset;
926 
927     uint32_t ID = read32<E>(D.data() + 4);
928     if (ID == 0) {
929       // CIE
930       Cie<ELFT> C(S, Index);
931 
932       StringRef Personality;
933       if (HasReloc) {
934         uint32_t SymIndex = RelI->getSymbol(Config->Mips64EL);
935         SymbolBody &Body = *S->getFile()->getSymbolBody(SymIndex)->repl();
936         Personality = Body.getName();
937       }
938 
939       std::pair<StringRef, StringRef> CieInfo(Entry, Personality);
940       auto P = CieMap.insert(std::make_pair(CieInfo, Cies.size()));
941       if (P.second) {
942         Cies.push_back(C);
943         this->Header.sh_size += Length;
944       }
945       OffsetToIndex[Offset] = P.first->second;
946     } else {
947       if (!HasReloc)
948         error("FDE doesn't reference another section");
949       InputSectionBase<ELFT> *Target = S->getRelocTarget(*RelI);
950       if (Target != &InputSection<ELFT>::Discarded && Target->isLive()) {
951         uint32_t CieOffset = Offset + 4 - ID;
952         auto I = OffsetToIndex.find(CieOffset);
953         if (I == OffsetToIndex.end())
954           error("Invalid CIE reference");
955         Cies[I->second].Fdes.push_back(EHRegion<ELFT>(S, Index));
956         this->Header.sh_size += Length;
957       }
958     }
959 
960     Offset = NextOffset;
961     D = D.slice(Length);
962   }
963 }
964 
965 template <class ELFT>
966 void EHOutputSection<ELFT>::addSection(EHInputSection<ELFT> *S) {
967   const Elf_Shdr *RelSec = S->RelocSection;
968   if (!RelSec)
969     return addSectionAux(
970         S, make_range((const Elf_Rela *)nullptr, (const Elf_Rela *)nullptr));
971   ELFFile<ELFT> &Obj = S->getFile()->getObj();
972   if (RelSec->sh_type == SHT_RELA)
973     return addSectionAux(S, Obj.relas(RelSec));
974   return addSectionAux(S, Obj.rels(RelSec));
975 }
976 
977 template <class ELFT> void EHOutputSection<ELFT>::writeTo(uint8_t *Buf) {
978   const endianness E = ELFT::TargetEndianness;
979   size_t Offset = 0;
980   for (const Cie<ELFT> &C : Cies) {
981     size_t CieOffset = Offset;
982 
983     StringRef CieData = C.data();
984     memcpy(Buf + Offset, CieData.data(), CieData.size());
985     C.S->Offsets[C.Index].second = Offset;
986     Offset += CieData.size();
987 
988     for (const EHRegion<ELFT> &F : C.Fdes) {
989       StringRef FdeData = F.data();
990       memcpy(Buf + Offset, FdeData.data(), 4);              // Legnth
991       write32<E>(Buf + Offset + 4, Offset + 4 - CieOffset); // Pointer
992       memcpy(Buf + Offset + 8, FdeData.data() + 8, FdeData.size() - 8);
993       F.S->Offsets[F.Index].second = Offset;
994       Offset += FdeData.size();
995     }
996   }
997 
998   for (EHInputSection<ELFT> *S : Sections) {
999     const Elf_Shdr *RelSec = S->RelocSection;
1000     if (!RelSec)
1001       continue;
1002     ELFFile<ELFT> &EObj = S->getFile()->getObj();
1003     if (RelSec->sh_type == SHT_RELA)
1004       S->relocate(Buf, nullptr, EObj.relas(RelSec));
1005     else
1006       S->relocate(Buf, nullptr, EObj.rels(RelSec));
1007   }
1008 }
1009 
1010 template <class ELFT>
1011 MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t sh_type,
1012                                              uintX_t sh_flags)
1013     : OutputSectionBase<ELFT>(Name, sh_type, sh_flags) {}
1014 
1015 template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1016   if (shouldTailMerge()) {
1017     StringRef Data = Builder.data();
1018     memcpy(Buf, Data.data(), Data.size());
1019     return;
1020   }
1021   for (const std::pair<StringRef, size_t> &P : Builder.getMap()) {
1022     StringRef Data = P.first;
1023     memcpy(Buf + P.second, Data.data(), Data.size());
1024   }
1025 }
1026 
1027 static size_t findNull(StringRef S, size_t EntSize) {
1028   // Optimize the common case.
1029   if (EntSize == 1)
1030     return S.find(0);
1031 
1032   for (unsigned I = 0, N = S.size(); I != N; I += EntSize) {
1033     const char *B = S.begin() + I;
1034     if (std::all_of(B, B + EntSize, [](char C) { return C == 0; }))
1035       return I;
1036   }
1037   return StringRef::npos;
1038 }
1039 
1040 template <class ELFT>
1041 void MergeOutputSection<ELFT>::addSection(MergeInputSection<ELFT> *S) {
1042   S->OutSec = this;
1043   uint32_t Align = S->getAlign();
1044   if (Align > this->Header.sh_addralign)
1045     this->Header.sh_addralign = Align;
1046 
1047   ArrayRef<uint8_t> D = S->getSectionData();
1048   StringRef Data((const char *)D.data(), D.size());
1049   uintX_t EntSize = S->getSectionHdr()->sh_entsize;
1050   uintX_t Offset = 0;
1051 
1052   if (this->Header.sh_flags & SHF_STRINGS) {
1053     while (!Data.empty()) {
1054       size_t End = findNull(Data, EntSize);
1055       if (End == StringRef::npos)
1056         error("String is not null terminated");
1057       StringRef Entry = Data.substr(0, End + EntSize);
1058       uintX_t OutputOffset = Builder.add(Entry);
1059       if (shouldTailMerge())
1060         OutputOffset = -1;
1061       S->Offsets.push_back(std::make_pair(Offset, OutputOffset));
1062       uintX_t Size = End + EntSize;
1063       Data = Data.substr(Size);
1064       Offset += Size;
1065     }
1066   } else {
1067     for (unsigned I = 0, N = Data.size(); I != N; I += EntSize) {
1068       StringRef Entry = Data.substr(I, EntSize);
1069       size_t OutputOffset = Builder.add(Entry);
1070       S->Offsets.push_back(std::make_pair(Offset, OutputOffset));
1071       Offset += EntSize;
1072     }
1073   }
1074 }
1075 
1076 template <class ELFT>
1077 unsigned MergeOutputSection<ELFT>::getOffset(StringRef Val) {
1078   return Builder.getOffset(Val);
1079 }
1080 
1081 template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
1082   return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS;
1083 }
1084 
1085 template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1086   if (shouldTailMerge())
1087     Builder.finalize();
1088   this->Header.sh_size = Builder.getSize();
1089 }
1090 
1091 template <class ELFT>
1092 StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
1093     : OutputSectionBase<ELFT>(Name, llvm::ELF::SHT_STRTAB,
1094                               Dynamic ? (uintX_t)llvm::ELF::SHF_ALLOC : 0),
1095       Dynamic(Dynamic) {
1096   this->Header.sh_addralign = 1;
1097 }
1098 
1099 template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
1100   StringRef Data = StrTabBuilder.data();
1101   memcpy(Buf, Data.data(), Data.size());
1102 }
1103 
1104 template <class ELFT> bool lld::elf2::includeInSymtab(const SymbolBody &B) {
1105   if (!B.isUsedInRegularObj())
1106     return false;
1107 
1108   // Don't include synthetic symbols like __init_array_start in every output.
1109   if (auto *U = dyn_cast<DefinedAbsolute<ELFT>>(&B))
1110     if (&U->Sym == &DefinedAbsolute<ELFT>::IgnoreUndef)
1111       return false;
1112 
1113   return true;
1114 }
1115 
1116 bool lld::elf2::includeInDynamicSymtab(const SymbolBody &B) {
1117   uint8_t V = B.getVisibility();
1118   if (V != STV_DEFAULT && V != STV_PROTECTED)
1119     return false;
1120 
1121   if (Config->ExportDynamic || Config->Shared)
1122     return true;
1123   return B.isUsedInDynamicReloc();
1124 }
1125 
1126 template <class ELFT>
1127 bool lld::elf2::shouldKeepInSymtab(const ObjectFile<ELFT> &File,
1128                                    StringRef SymName,
1129                                    const typename ELFFile<ELFT>::Elf_Sym &Sym) {
1130   if (Sym.getType() == STT_SECTION)
1131     return false;
1132 
1133   // If sym references a section in a discarded group, don't keep it.
1134   if (File.getSection(Sym) == &InputSection<ELFT>::Discarded)
1135     return false;
1136 
1137   if (Config->DiscardNone)
1138     return true;
1139 
1140   // ELF defines dynamic locals as symbols which name starts with ".L".
1141   return !(Config->DiscardLocals && SymName.startswith(".L"));
1142 }
1143 
1144 template <class ELFT>
1145 SymbolTableSection<ELFT>::SymbolTableSection(
1146     SymbolTable<ELFT> &Table, StringTableSection<ELFT> &StrTabSec)
1147     : OutputSectionBase<ELFT>(
1148           StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1149           StrTabSec.isDynamic() ? llvm::ELF::SHT_DYNSYM : llvm::ELF::SHT_SYMTAB,
1150           StrTabSec.isDynamic() ? (uintX_t)llvm::ELF::SHF_ALLOC : 0),
1151       Table(Table), StrTabSec(StrTabSec) {
1152   typedef OutputSectionBase<ELFT> Base;
1153   typename Base::Elf_Shdr &Header = this->Header;
1154 
1155   Header.sh_entsize = sizeof(Elf_Sym);
1156   Header.sh_addralign = ELFT::Is64Bits ? 8 : 4;
1157 }
1158 
1159 // Orders symbols according to their positions in the GOT,
1160 // in compliance with MIPS ABI rules.
1161 // See "Global Offset Table" in Chapter 5 in the following document
1162 // for detailed description:
1163 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1164 static bool sortMipsSymbols(SymbolBody *L, SymbolBody *R) {
1165   if (!L->isInGot() || !R->isInGot())
1166     return R->isInGot();
1167   return L->GotIndex < R->GotIndex;
1168 }
1169 
1170 template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
1171   if (this->Header.sh_size)
1172     return; // Already finalized.
1173 
1174   this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
1175   this->Header.sh_link = StrTabSec.SectionIndex;
1176   this->Header.sh_info = NumLocals + 1;
1177 
1178   if (!StrTabSec.isDynamic()) {
1179     std::stable_sort(Symbols.begin(), Symbols.end(),
1180                      [](SymbolBody *L, SymbolBody *R) {
1181                        return getSymbolBinding(L) == STB_LOCAL &&
1182                               getSymbolBinding(R) != STB_LOCAL;
1183                      });
1184     return;
1185   }
1186   if (Out<ELFT>::GnuHashTab)
1187     // NB: It also sorts Symbols to meet the GNU hash table requirements.
1188     Out<ELFT>::GnuHashTab->addSymbols(Symbols);
1189   else if (Config->EMachine == EM_MIPS)
1190     std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1191   size_t I = 0;
1192   for (SymbolBody *B : Symbols)
1193     B->setDynamicSymbolTableIndex(++I);
1194 }
1195 
1196 template <class ELFT>
1197 void SymbolTableSection<ELFT>::addLocalSymbol(StringRef Name) {
1198   StrTabSec.add(Name);
1199   ++NumVisible;
1200   ++NumLocals;
1201 }
1202 
1203 template <class ELFT>
1204 void SymbolTableSection<ELFT>::addSymbol(SymbolBody *Body) {
1205   StrTabSec.add(Body->getName());
1206   Symbols.push_back(Body);
1207   ++NumVisible;
1208 }
1209 
1210 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1211   Buf += sizeof(Elf_Sym);
1212 
1213   // All symbols with STB_LOCAL binding precede the weak and global symbols.
1214   // .dynsym only contains global symbols.
1215   if (!Config->DiscardAll && !StrTabSec.isDynamic())
1216     writeLocalSymbols(Buf);
1217 
1218   writeGlobalSymbols(Buf);
1219 }
1220 
1221 template <class ELFT>
1222 void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1223   // Iterate over all input object files to copy their local symbols
1224   // to the output symbol table pointed by Buf.
1225   for (const std::unique_ptr<ObjectFile<ELFT>> &File : Table.getObjectFiles()) {
1226     Elf_Sym_Range Syms = File->getLocalSymbols();
1227     for (const Elf_Sym &Sym : Syms) {
1228       ErrorOr<StringRef> SymNameOrErr = Sym.getName(File->getStringTable());
1229       error(SymNameOrErr);
1230       StringRef SymName = *SymNameOrErr;
1231       if (!shouldKeepInSymtab<ELFT>(*File, SymName, Sym))
1232         continue;
1233 
1234       auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1235       uintX_t VA = 0;
1236       if (Sym.st_shndx == SHN_ABS) {
1237         ESym->st_shndx = SHN_ABS;
1238         VA = Sym.st_value;
1239       } else {
1240         InputSectionBase<ELFT> *Section = File->getSection(Sym);
1241         if (!Section->isLive())
1242           continue;
1243         const OutputSectionBase<ELFT> *OutSec = Section->OutSec;
1244         ESym->st_shndx = OutSec->SectionIndex;
1245         VA += OutSec->getVA() + Section->getOffset(Sym);
1246       }
1247       ESym->st_name = StrTabSec.getOffset(SymName);
1248       ESym->st_size = Sym.st_size;
1249       ESym->setBindingAndType(Sym.getBinding(), Sym.getType());
1250       ESym->st_value = VA;
1251       Buf += sizeof(*ESym);
1252     }
1253   }
1254 }
1255 
1256 template <class ELFT>
1257 void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
1258   // Write the internal symbol table contents to the output symbol table
1259   // pointed by Buf.
1260   auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1261   for (SymbolBody *Body : Symbols) {
1262     const OutputSectionBase<ELFT> *OutSec = nullptr;
1263 
1264     switch (Body->kind()) {
1265     case SymbolBody::DefinedSyntheticKind:
1266       OutSec = &cast<DefinedSynthetic<ELFT>>(Body)->Section;
1267       break;
1268     case SymbolBody::DefinedRegularKind: {
1269       auto *Sym = cast<DefinedRegular<ELFT>>(Body->repl());
1270       if (!Sym->Section.isLive())
1271         continue;
1272       OutSec = Sym->Section.OutSec;
1273       break;
1274     }
1275     case SymbolBody::DefinedCommonKind:
1276       OutSec = Out<ELFT>::Bss;
1277       break;
1278     case SymbolBody::SharedKind: {
1279       if (cast<SharedSymbol<ELFT>>(Body)->needsCopy())
1280         OutSec = Out<ELFT>::Bss;
1281       break;
1282     }
1283     case SymbolBody::UndefinedKind:
1284     case SymbolBody::DefinedAbsoluteKind:
1285     case SymbolBody::LazyKind:
1286       break;
1287     }
1288 
1289     StringRef Name = Body->getName();
1290     ESym->st_name = StrTabSec.getOffset(Name);
1291 
1292     unsigned char Type = STT_NOTYPE;
1293     uintX_t Size = 0;
1294     if (const auto *EBody = dyn_cast<ELFSymbolBody<ELFT>>(Body)) {
1295       const Elf_Sym &InputSym = EBody->Sym;
1296       Type = InputSym.getType();
1297       Size = InputSym.st_size;
1298     }
1299 
1300     ESym->setBindingAndType(getSymbolBinding(Body), Type);
1301     ESym->st_size = Size;
1302     ESym->setVisibility(Body->getVisibility());
1303     ESym->st_value = getSymVA<ELFT>(*Body);
1304 
1305     if (isa<DefinedAbsolute<ELFT>>(Body))
1306       ESym->st_shndx = SHN_ABS;
1307     else if (OutSec)
1308       ESym->st_shndx = OutSec->SectionIndex;
1309 
1310     ++ESym;
1311   }
1312 }
1313 
1314 template <class ELFT>
1315 uint8_t SymbolTableSection<ELFT>::getSymbolBinding(SymbolBody *Body) {
1316   uint8_t Visibility = Body->getVisibility();
1317   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1318     return STB_LOCAL;
1319   if (const auto *EBody = dyn_cast<ELFSymbolBody<ELFT>>(Body))
1320     return EBody->Sym.getBinding();
1321   return Body->isWeak() ? STB_WEAK : STB_GLOBAL;
1322 }
1323 
1324 namespace lld {
1325 namespace elf2 {
1326 template class OutputSectionBase<ELF32LE>;
1327 template class OutputSectionBase<ELF32BE>;
1328 template class OutputSectionBase<ELF64LE>;
1329 template class OutputSectionBase<ELF64BE>;
1330 
1331 template class GotPltSection<ELF32LE>;
1332 template class GotPltSection<ELF32BE>;
1333 template class GotPltSection<ELF64LE>;
1334 template class GotPltSection<ELF64BE>;
1335 
1336 template class GotSection<ELF32LE>;
1337 template class GotSection<ELF32BE>;
1338 template class GotSection<ELF64LE>;
1339 template class GotSection<ELF64BE>;
1340 
1341 template class PltSection<ELF32LE>;
1342 template class PltSection<ELF32BE>;
1343 template class PltSection<ELF64LE>;
1344 template class PltSection<ELF64BE>;
1345 
1346 template class RelocationSection<ELF32LE>;
1347 template class RelocationSection<ELF32BE>;
1348 template class RelocationSection<ELF64LE>;
1349 template class RelocationSection<ELF64BE>;
1350 
1351 template class InterpSection<ELF32LE>;
1352 template class InterpSection<ELF32BE>;
1353 template class InterpSection<ELF64LE>;
1354 template class InterpSection<ELF64BE>;
1355 
1356 template class GnuHashTableSection<ELF32LE>;
1357 template class GnuHashTableSection<ELF32BE>;
1358 template class GnuHashTableSection<ELF64LE>;
1359 template class GnuHashTableSection<ELF64BE>;
1360 
1361 template class HashTableSection<ELF32LE>;
1362 template class HashTableSection<ELF32BE>;
1363 template class HashTableSection<ELF64LE>;
1364 template class HashTableSection<ELF64BE>;
1365 
1366 template class DynamicSection<ELF32LE>;
1367 template class DynamicSection<ELF32BE>;
1368 template class DynamicSection<ELF64LE>;
1369 template class DynamicSection<ELF64BE>;
1370 
1371 template class OutputSection<ELF32LE>;
1372 template class OutputSection<ELF32BE>;
1373 template class OutputSection<ELF64LE>;
1374 template class OutputSection<ELF64BE>;
1375 
1376 template class EHOutputSection<ELF32LE>;
1377 template class EHOutputSection<ELF32BE>;
1378 template class EHOutputSection<ELF64LE>;
1379 template class EHOutputSection<ELF64BE>;
1380 
1381 template class MergeOutputSection<ELF32LE>;
1382 template class MergeOutputSection<ELF32BE>;
1383 template class MergeOutputSection<ELF64LE>;
1384 template class MergeOutputSection<ELF64BE>;
1385 
1386 template class StringTableSection<ELF32LE>;
1387 template class StringTableSection<ELF32BE>;
1388 template class StringTableSection<ELF64LE>;
1389 template class StringTableSection<ELF64BE>;
1390 
1391 template class SymbolTableSection<ELF32LE>;
1392 template class SymbolTableSection<ELF32BE>;
1393 template class SymbolTableSection<ELF64LE>;
1394 template class SymbolTableSection<ELF64BE>;
1395 
1396 template ELFFile<ELF32LE>::uintX_t getSymVA<ELF32LE>(const SymbolBody &);
1397 template ELFFile<ELF32BE>::uintX_t getSymVA<ELF32BE>(const SymbolBody &);
1398 template ELFFile<ELF64LE>::uintX_t getSymVA<ELF64LE>(const SymbolBody &);
1399 template ELFFile<ELF64BE>::uintX_t getSymVA<ELF64BE>(const SymbolBody &);
1400 
1401 template ELFFile<ELF32LE>::uintX_t
1402 getLocalRelTarget(const ObjectFile<ELF32LE> &,
1403                   const ELFFile<ELF32LE>::Elf_Rel &);
1404 template ELFFile<ELF32BE>::uintX_t
1405 getLocalRelTarget(const ObjectFile<ELF32BE> &,
1406                   const ELFFile<ELF32BE>::Elf_Rel &);
1407 template ELFFile<ELF64LE>::uintX_t
1408 getLocalRelTarget(const ObjectFile<ELF64LE> &,
1409                   const ELFFile<ELF64LE>::Elf_Rel &);
1410 template ELFFile<ELF64BE>::uintX_t
1411 getLocalRelTarget(const ObjectFile<ELF64BE> &,
1412                   const ELFFile<ELF64BE>::Elf_Rel &);
1413 
1414 template ELFFile<ELF32LE>::uintX_t
1415 getLocalRelTarget(const ObjectFile<ELF32LE> &,
1416                   const ELFFile<ELF32LE>::Elf_Rela &);
1417 template ELFFile<ELF32BE>::uintX_t
1418 getLocalRelTarget(const ObjectFile<ELF32BE> &,
1419                   const ELFFile<ELF32BE>::Elf_Rela &);
1420 template ELFFile<ELF64LE>::uintX_t
1421 getLocalRelTarget(const ObjectFile<ELF64LE> &,
1422                   const ELFFile<ELF64LE>::Elf_Rela &);
1423 template ELFFile<ELF64BE>::uintX_t
1424 getLocalRelTarget(const ObjectFile<ELF64BE> &,
1425                   const ELFFile<ELF64BE>::Elf_Rela &);
1426 
1427 template bool includeInSymtab<ELF32LE>(const SymbolBody &);
1428 template bool includeInSymtab<ELF32BE>(const SymbolBody &);
1429 template bool includeInSymtab<ELF64LE>(const SymbolBody &);
1430 template bool includeInSymtab<ELF64BE>(const SymbolBody &);
1431 
1432 template bool shouldKeepInSymtab<ELF32LE>(const ObjectFile<ELF32LE> &,
1433                                           StringRef,
1434                                           const ELFFile<ELF32LE>::Elf_Sym &);
1435 template bool shouldKeepInSymtab<ELF32BE>(const ObjectFile<ELF32BE> &,
1436                                           StringRef,
1437                                           const ELFFile<ELF32BE>::Elf_Sym &);
1438 template bool shouldKeepInSymtab<ELF64LE>(const ObjectFile<ELF64LE> &,
1439                                           StringRef,
1440                                           const ELFFile<ELF64LE>::Elf_Sym &);
1441 template bool shouldKeepInSymtab<ELF64BE>(const ObjectFile<ELF64BE> &,
1442                                           StringRef,
1443                                           const ELFFile<ELF64BE>::Elf_Sym &);
1444 }
1445 }
1446