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