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