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