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 "EhFrame.h"
13 #include "LinkerScript.h"
14 #include "Strings.h"
15 #include "SymbolTable.h"
16 #include "Target.h"
17 #include "lld/Core/Parallel.h"
18 #include "llvm/Support/Dwarf.h"
19 #include "llvm/Support/MD5.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/SHA1.h"
22 #include <map>
23 
24 using namespace llvm;
25 using namespace llvm::dwarf;
26 using namespace llvm::object;
27 using namespace llvm::support::endian;
28 using namespace llvm::ELF;
29 
30 using namespace lld;
31 using namespace lld::elf;
32 
33 template <class ELFT>
34 OutputSectionBase<ELFT>::OutputSectionBase(StringRef Name, uint32_t Type,
35                                            uintX_t Flags)
36     : Name(Name) {
37   memset(&Header, 0, sizeof(Elf_Shdr));
38   Header.sh_type = Type;
39   Header.sh_flags = Flags;
40   Header.sh_addralign = 1;
41 }
42 
43 template <class ELFT> uint32_t OutputSectionBase<ELFT>::getPhdrFlags() const {
44   uintX_t Flags = getFlags();
45   uint32_t Ret = PF_R;
46   if (Flags & SHF_WRITE)
47     Ret |= PF_W;
48   if (Flags & SHF_EXECINSTR)
49     Ret |= PF_X;
50   return Ret;
51 }
52 
53 template <class ELFT>
54 void OutputSectionBase<ELFT>::writeHeaderTo(Elf_Shdr *Shdr) {
55   *Shdr = Header;
56 }
57 
58 template <class ELFT>
59 GotPltSection<ELFT>::GotPltSection()
60     : OutputSectionBase<ELFT>(".got.plt", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
61   this->Header.sh_addralign = Target->GotPltEntrySize;
62 }
63 
64 template <class ELFT> void GotPltSection<ELFT>::addEntry(SymbolBody &Sym) {
65   Sym.GotPltIndex = Target->GotPltHeaderEntriesNum + Entries.size();
66   Entries.push_back(&Sym);
67 }
68 
69 template <class ELFT> bool GotPltSection<ELFT>::empty() const {
70   return Entries.empty();
71 }
72 
73 template <class ELFT> void GotPltSection<ELFT>::finalize() {
74   this->Header.sh_size = (Target->GotPltHeaderEntriesNum + Entries.size()) *
75                          Target->GotPltEntrySize;
76 }
77 
78 template <class ELFT> void GotPltSection<ELFT>::writeTo(uint8_t *Buf) {
79   Target->writeGotPltHeader(Buf);
80   Buf += Target->GotPltHeaderEntriesNum * Target->GotPltEntrySize;
81   for (const SymbolBody *B : Entries) {
82     Target->writeGotPlt(Buf, *B);
83     Buf += sizeof(uintX_t);
84   }
85 }
86 
87 template <class ELFT>
88 GotSection<ELFT>::GotSection()
89     : OutputSectionBase<ELFT>(".got", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE) {
90   if (Config->EMachine == EM_MIPS)
91     this->Header.sh_flags |= SHF_MIPS_GPREL;
92   this->Header.sh_addralign = Target->GotEntrySize;
93 }
94 
95 template <class ELFT>
96 void GotSection<ELFT>::addEntry(SymbolBody &Sym) {
97   Sym.GotIndex = Entries.size();
98   Entries.push_back(&Sym);
99 }
100 
101 template <class ELFT>
102 void GotSection<ELFT>::addMipsEntry(SymbolBody &Sym, uintX_t Addend,
103                                     RelExpr Expr) {
104   // For "true" local symbols which can be referenced from the same module
105   // only compiler creates two instructions for address loading:
106   //
107   // lw   $8, 0($gp) # R_MIPS_GOT16
108   // addi $8, $8, 0  # R_MIPS_LO16
109   //
110   // The first instruction loads high 16 bits of the symbol address while
111   // the second adds an offset. That allows to reduce number of required
112   // GOT entries because only one global offset table entry is necessary
113   // for every 64 KBytes of local data. So for local symbols we need to
114   // allocate number of GOT entries to hold all required "page" addresses.
115   //
116   // All global symbols (hidden and regular) considered by compiler uniformly.
117   // It always generates a single `lw` instruction and R_MIPS_GOT16 relocation
118   // to load address of the symbol. So for each such symbol we need to
119   // allocate dedicated GOT entry to store its address.
120   //
121   // If a symbol is preemptible we need help of dynamic linker to get its
122   // final address. The corresponding GOT entries are allocated in the
123   // "global" part of GOT. Entries for non preemptible global symbol allocated
124   // in the "local" part of GOT.
125   //
126   // See "Global Offset Table" in Chapter 5:
127   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
128   if (Expr == R_MIPS_GOT_LOCAL_PAGE) {
129     // At this point we do not know final symbol value so to reduce number
130     // of allocated GOT entries do the following trick. Save all output
131     // sections referenced by GOT relocations. Then later in the `finalize`
132     // method calculate number of "pages" required to cover all saved output
133     // section and allocate appropriate number of GOT entries.
134     auto *OutSec = cast<DefinedRegular<ELFT>>(&Sym)->Section->OutSec;
135     MipsOutSections.insert(OutSec);
136     return;
137   }
138   if (Sym.isTls()) {
139     // GOT entries created for MIPS TLS relocations behave like
140     // almost GOT entries from other ABIs. They go to the end
141     // of the global offset table.
142     Sym.GotIndex = Entries.size();
143     Entries.push_back(&Sym);
144     return;
145   }
146   auto AddEntry = [&](SymbolBody &S, uintX_t A, MipsGotEntries &Items) {
147     if (S.isInGot() && !A)
148       return;
149     size_t NewIndex = Items.size();
150     if (!MipsGotMap.insert({{&S, A}, NewIndex}).second)
151       return;
152     Items.emplace_back(&S, A);
153     if (!A)
154       S.GotIndex = NewIndex;
155   };
156   if (Sym.isPreemptible()) {
157     // Ignore addends for preemptible symbols. They got single GOT entry anyway.
158     AddEntry(Sym, 0, MipsGlobal);
159     Sym.IsInGlobalMipsGot = true;
160   } else
161     AddEntry(Sym, Addend, MipsLocal);
162 }
163 
164 template <class ELFT> bool GotSection<ELFT>::addDynTlsEntry(SymbolBody &Sym) {
165   if (Sym.GlobalDynIndex != -1U)
166     return false;
167   Sym.GlobalDynIndex = Entries.size();
168   // Global Dynamic TLS entries take two GOT slots.
169   Entries.push_back(nullptr);
170   Entries.push_back(&Sym);
171   return true;
172 }
173 
174 // Reserves TLS entries for a TLS module ID and a TLS block offset.
175 // In total it takes two GOT slots.
176 template <class ELFT> bool GotSection<ELFT>::addTlsIndex() {
177   if (TlsIndexOff != uint32_t(-1))
178     return false;
179   TlsIndexOff = Entries.size() * sizeof(uintX_t);
180   Entries.push_back(nullptr);
181   Entries.push_back(nullptr);
182   return true;
183 }
184 
185 template <class ELFT>
186 typename GotSection<ELFT>::uintX_t
187 GotSection<ELFT>::getMipsLocalPageOffset(uintX_t EntryValue) {
188   // Initialize the entry by the %hi(EntryValue) expression
189   // but without right-shifting.
190   EntryValue = (EntryValue + 0x8000) & ~0xffff;
191   // Take into account MIPS GOT header.
192   // See comment in the GotSection::writeTo.
193   size_t NewIndex = MipsLocalGotPos.size() + 2;
194   auto P = MipsLocalGotPos.insert(std::make_pair(EntryValue, NewIndex));
195   assert(!P.second || MipsLocalGotPos.size() <= MipsPageEntries);
196   return (uintX_t)P.first->second * sizeof(uintX_t) - MipsGPOffset;
197 }
198 
199 template <class ELFT>
200 typename GotSection<ELFT>::uintX_t
201 GotSection<ELFT>::getMipsGotOffset(const SymbolBody &B, uintX_t Addend) const {
202   uintX_t Off = MipsPageEntries;
203   if (B.isTls())
204     Off += MipsLocal.size() + MipsGlobal.size() + B.GotIndex;
205   else if (B.IsInGlobalMipsGot)
206     Off += MipsLocal.size() + B.GotIndex;
207   else if (B.isInGot())
208     Off += B.GotIndex;
209   else {
210     auto It = MipsGotMap.find({&B, Addend});
211     assert(It != MipsGotMap.end());
212     Off += It->second;
213   }
214   return Off * sizeof(uintX_t) - MipsGPOffset;
215 }
216 
217 template <class ELFT>
218 typename GotSection<ELFT>::uintX_t GotSection<ELFT>::getMipsTlsOffset() {
219   return (MipsPageEntries + MipsLocal.size() + MipsGlobal.size()) *
220          sizeof(uintX_t);
221 }
222 
223 template <class ELFT>
224 typename GotSection<ELFT>::uintX_t
225 GotSection<ELFT>::getGlobalDynAddr(const SymbolBody &B) const {
226   return this->getVA() + B.GlobalDynIndex * sizeof(uintX_t);
227 }
228 
229 template <class ELFT>
230 typename GotSection<ELFT>::uintX_t
231 GotSection<ELFT>::getGlobalDynOffset(const SymbolBody &B) const {
232   return B.GlobalDynIndex * sizeof(uintX_t);
233 }
234 
235 template <class ELFT>
236 const SymbolBody *GotSection<ELFT>::getMipsFirstGlobalEntry() const {
237   return MipsGlobal.empty() ? nullptr : MipsGlobal.front().first;
238 }
239 
240 template <class ELFT>
241 unsigned GotSection<ELFT>::getMipsLocalEntriesNum() const {
242   return MipsPageEntries + MipsLocal.size();
243 }
244 
245 template <class ELFT> void GotSection<ELFT>::finalize() {
246   size_t EntriesNum = Entries.size();
247   if (Config->EMachine == EM_MIPS) {
248     // Take into account MIPS GOT header.
249     // See comment in the GotSection::writeTo.
250     MipsPageEntries += 2;
251     for (const OutputSectionBase<ELFT> *OutSec : MipsOutSections) {
252       // Calculate an upper bound of MIPS GOT entries required to store page
253       // addresses of local symbols. We assume the worst case - each 64kb
254       // page of the output section has at least one GOT relocation against it.
255       // Add 0x8000 to the section's size because the page address stored
256       // in the GOT entry is calculated as (value + 0x8000) & ~0xffff.
257       MipsPageEntries += (OutSec->getSize() + 0x8000 + 0xfffe) / 0xffff;
258     }
259     EntriesNum += MipsPageEntries + MipsLocal.size() + MipsGlobal.size();
260   }
261   this->Header.sh_size = EntriesNum * sizeof(uintX_t);
262 }
263 
264 template <class ELFT> void GotSection<ELFT>::writeMipsGot(uint8_t *&Buf) {
265   // Set the MSB of the second GOT slot. This is not required by any
266   // MIPS ABI documentation, though.
267   //
268   // There is a comment in glibc saying that "The MSB of got[1] of a
269   // gnu object is set to identify gnu objects," and in GNU gold it
270   // says "the second entry will be used by some runtime loaders".
271   // But how this field is being used is unclear.
272   //
273   // We are not really willing to mimic other linkers behaviors
274   // without understanding why they do that, but because all files
275   // generated by GNU tools have this special GOT value, and because
276   // we've been doing this for years, it is probably a safe bet to
277   // keep doing this for now. We really need to revisit this to see
278   // if we had to do this.
279   auto *P = reinterpret_cast<typename ELFT::Off *>(Buf);
280   P[1] = uintX_t(1) << (ELFT::Is64Bits ? 63 : 31);
281   // Write 'page address' entries to the local part of the GOT.
282   for (std::pair<uintX_t, size_t> &L : MipsLocalGotPos) {
283     uint8_t *Entry = Buf + L.second * sizeof(uintX_t);
284     write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, L.first);
285   }
286   Buf += MipsPageEntries * sizeof(uintX_t);
287   auto AddEntry = [&](const MipsGotEntry &SA) {
288     uint8_t *Entry = Buf;
289     Buf += sizeof(uintX_t);
290     const SymbolBody* Body = SA.first;
291     uintX_t VA = Body->template getVA<ELFT>(SA.second);
292     write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
293   };
294   std::for_each(std::begin(MipsLocal), std::end(MipsLocal), AddEntry);
295   std::for_each(std::begin(MipsGlobal), std::end(MipsGlobal), AddEntry);
296 }
297 
298 template <class ELFT> void GotSection<ELFT>::writeTo(uint8_t *Buf) {
299   if (Config->EMachine == EM_MIPS)
300     writeMipsGot(Buf);
301   for (const SymbolBody *B : Entries) {
302     uint8_t *Entry = Buf;
303     Buf += sizeof(uintX_t);
304     if (!B)
305       continue;
306     if (B->isPreemptible())
307       continue; // The dynamic linker will take care of it.
308     uintX_t VA = B->getVA<ELFT>();
309     write<uintX_t, ELFT::TargetEndianness, sizeof(uintX_t)>(Entry, VA);
310   }
311 }
312 
313 template <class ELFT>
314 PltSection<ELFT>::PltSection()
315     : OutputSectionBase<ELFT>(".plt", SHT_PROGBITS, SHF_ALLOC | SHF_EXECINSTR) {
316   this->Header.sh_addralign = 16;
317 }
318 
319 template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
320   // At beginning of PLT, we have code to call the dynamic linker
321   // to resolve dynsyms at runtime. Write such code.
322   Target->writePltHeader(Buf);
323   size_t Off = Target->PltHeaderSize;
324 
325   for (auto &I : Entries) {
326     const SymbolBody *B = I.first;
327     unsigned RelOff = I.second;
328     uint64_t Got = B->getGotPltVA<ELFT>();
329     uint64_t Plt = this->getVA() + Off;
330     Target->writePlt(Buf + Off, Got, Plt, B->PltIndex, RelOff);
331     Off += Target->PltEntrySize;
332   }
333 }
334 
335 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody &Sym) {
336   Sym.PltIndex = Entries.size();
337   unsigned RelOff = Out<ELFT>::RelaPlt->getRelocOffset();
338   Entries.push_back(std::make_pair(&Sym, RelOff));
339 }
340 
341 template <class ELFT> void PltSection<ELFT>::finalize() {
342   this->Header.sh_size =
343       Target->PltHeaderSize + Entries.size() * Target->PltEntrySize;
344 }
345 
346 template <class ELFT>
347 RelocationSection<ELFT>::RelocationSection(StringRef Name, bool Sort)
348     : OutputSectionBase<ELFT>(Name, Config->Rela ? SHT_RELA : SHT_REL,
349                               SHF_ALLOC),
350       Sort(Sort) {
351   this->Header.sh_entsize = Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
352   this->Header.sh_addralign = sizeof(uintX_t);
353 }
354 
355 template <class ELFT>
356 void RelocationSection<ELFT>::addReloc(const DynamicReloc<ELFT> &Reloc) {
357   Relocs.push_back(Reloc);
358 }
359 
360 template <class ELFT, class RelTy>
361 static bool compRelocations(const RelTy &A, const RelTy &B) {
362   return A.getSymbol(Config->Mips64EL) < B.getSymbol(Config->Mips64EL);
363 }
364 
365 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
366   uint8_t *BufBegin = Buf;
367   for (const DynamicReloc<ELFT> &Rel : Relocs) {
368     auto *P = reinterpret_cast<Elf_Rela *>(Buf);
369     Buf += Config->Rela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
370 
371     if (Config->Rela)
372       P->r_addend = Rel.getAddend();
373     P->r_offset = Rel.getOffset();
374     if (Config->EMachine == EM_MIPS && Rel.getOutputSec() == Out<ELFT>::Got)
375       // Dynamic relocation against MIPS GOT section make deal TLS entries
376       // allocated in the end of the GOT. We need to adjust the offset to take
377       // in account 'local' and 'global' GOT entries.
378       P->r_offset += Out<ELFT>::Got->getMipsTlsOffset();
379     P->setSymbolAndType(Rel.getSymIndex(), Rel.Type, Config->Mips64EL);
380   }
381 
382   if (Sort) {
383     if (Config->Rela)
384       std::stable_sort((Elf_Rela *)BufBegin,
385                        (Elf_Rela *)BufBegin + Relocs.size(),
386                        compRelocations<ELFT, Elf_Rela>);
387     else
388       std::stable_sort((Elf_Rel *)BufBegin, (Elf_Rel *)BufBegin + Relocs.size(),
389                        compRelocations<ELFT, Elf_Rel>);
390   }
391 }
392 
393 template <class ELFT> unsigned RelocationSection<ELFT>::getRelocOffset() {
394   return this->Header.sh_entsize * Relocs.size();
395 }
396 
397 template <class ELFT> void RelocationSection<ELFT>::finalize() {
398   this->Header.sh_link = Static ? Out<ELFT>::SymTab->SectionIndex
399                                 : Out<ELFT>::DynSymTab->SectionIndex;
400   this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
401 }
402 
403 template <class ELFT>
404 InterpSection<ELFT>::InterpSection()
405     : OutputSectionBase<ELFT>(".interp", SHT_PROGBITS, SHF_ALLOC) {
406   this->Header.sh_size = Config->DynamicLinker.size() + 1;
407 }
408 
409 template <class ELFT> void InterpSection<ELFT>::writeTo(uint8_t *Buf) {
410   StringRef S = Config->DynamicLinker;
411   memcpy(Buf, S.data(), S.size());
412 }
413 
414 template <class ELFT>
415 HashTableSection<ELFT>::HashTableSection()
416     : OutputSectionBase<ELFT>(".hash", SHT_HASH, SHF_ALLOC) {
417   this->Header.sh_entsize = sizeof(Elf_Word);
418   this->Header.sh_addralign = sizeof(Elf_Word);
419 }
420 
421 static uint32_t hashSysv(StringRef Name) {
422   uint32_t H = 0;
423   for (char C : Name) {
424     H = (H << 4) + C;
425     uint32_t G = H & 0xf0000000;
426     if (G)
427       H ^= G >> 24;
428     H &= ~G;
429   }
430   return H;
431 }
432 
433 template <class ELFT> void HashTableSection<ELFT>::finalize() {
434   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
435 
436   unsigned NumEntries = 2;                             // nbucket and nchain.
437   NumEntries += Out<ELFT>::DynSymTab->getNumSymbols(); // The chain entries.
438 
439   // Create as many buckets as there are symbols.
440   // FIXME: This is simplistic. We can try to optimize it, but implementing
441   // support for SHT_GNU_HASH is probably even more profitable.
442   NumEntries += Out<ELFT>::DynSymTab->getNumSymbols();
443   this->Header.sh_size = NumEntries * sizeof(Elf_Word);
444 }
445 
446 template <class ELFT> void HashTableSection<ELFT>::writeTo(uint8_t *Buf) {
447   unsigned NumSymbols = Out<ELFT>::DynSymTab->getNumSymbols();
448   auto *P = reinterpret_cast<Elf_Word *>(Buf);
449   *P++ = NumSymbols; // nbucket
450   *P++ = NumSymbols; // nchain
451 
452   Elf_Word *Buckets = P;
453   Elf_Word *Chains = P + NumSymbols;
454 
455   for (const std::pair<SymbolBody *, unsigned> &P :
456        Out<ELFT>::DynSymTab->getSymbols()) {
457     SymbolBody *Body = P.first;
458     StringRef Name = Body->getName();
459     unsigned I = Body->DynsymIndex;
460     uint32_t Hash = hashSysv(Name) % NumSymbols;
461     Chains[I] = Buckets[Hash];
462     Buckets[Hash] = I;
463   }
464 }
465 
466 static uint32_t hashGnu(StringRef Name) {
467   uint32_t H = 5381;
468   for (uint8_t C : Name)
469     H = (H << 5) + H + C;
470   return H;
471 }
472 
473 template <class ELFT>
474 GnuHashTableSection<ELFT>::GnuHashTableSection()
475     : OutputSectionBase<ELFT>(".gnu.hash", SHT_GNU_HASH, SHF_ALLOC) {
476   this->Header.sh_entsize = ELFT::Is64Bits ? 0 : 4;
477   this->Header.sh_addralign = sizeof(uintX_t);
478 }
479 
480 template <class ELFT>
481 unsigned GnuHashTableSection<ELFT>::calcNBuckets(unsigned NumHashed) {
482   if (!NumHashed)
483     return 0;
484 
485   // These values are prime numbers which are not greater than 2^(N-1) + 1.
486   // In result, for any particular NumHashed we return a prime number
487   // which is not greater than NumHashed.
488   static const unsigned Primes[] = {
489       1,   1,    3,    3,    7,    13,    31,    61,    127,   251,
490       509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071};
491 
492   return Primes[std::min<unsigned>(Log2_32_Ceil(NumHashed),
493                                    array_lengthof(Primes) - 1)];
494 }
495 
496 // Bloom filter estimation: at least 8 bits for each hashed symbol.
497 // GNU Hash table requirement: it should be a power of 2,
498 //   the minimum value is 1, even for an empty table.
499 // Expected results for a 32-bit target:
500 //   calcMaskWords(0..4)   = 1
501 //   calcMaskWords(5..8)   = 2
502 //   calcMaskWords(9..16)  = 4
503 // For a 64-bit target:
504 //   calcMaskWords(0..8)   = 1
505 //   calcMaskWords(9..16)  = 2
506 //   calcMaskWords(17..32) = 4
507 template <class ELFT>
508 unsigned GnuHashTableSection<ELFT>::calcMaskWords(unsigned NumHashed) {
509   if (!NumHashed)
510     return 1;
511   return NextPowerOf2((NumHashed - 1) / sizeof(Elf_Off));
512 }
513 
514 template <class ELFT> void GnuHashTableSection<ELFT>::finalize() {
515   unsigned NumHashed = Symbols.size();
516   NBuckets = calcNBuckets(NumHashed);
517   MaskWords = calcMaskWords(NumHashed);
518   // Second hash shift estimation: just predefined values.
519   Shift2 = ELFT::Is64Bits ? 6 : 5;
520 
521   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
522   this->Header.sh_size = sizeof(Elf_Word) * 4            // Header
523                          + sizeof(Elf_Off) * MaskWords   // Bloom Filter
524                          + sizeof(Elf_Word) * NBuckets   // Hash Buckets
525                          + sizeof(Elf_Word) * NumHashed; // Hash Values
526 }
527 
528 template <class ELFT> void GnuHashTableSection<ELFT>::writeTo(uint8_t *Buf) {
529   writeHeader(Buf);
530   if (Symbols.empty())
531     return;
532   writeBloomFilter(Buf);
533   writeHashTable(Buf);
534 }
535 
536 template <class ELFT>
537 void GnuHashTableSection<ELFT>::writeHeader(uint8_t *&Buf) {
538   auto *P = reinterpret_cast<Elf_Word *>(Buf);
539   *P++ = NBuckets;
540   *P++ = Out<ELFT>::DynSymTab->getNumSymbols() - Symbols.size();
541   *P++ = MaskWords;
542   *P++ = Shift2;
543   Buf = reinterpret_cast<uint8_t *>(P);
544 }
545 
546 template <class ELFT>
547 void GnuHashTableSection<ELFT>::writeBloomFilter(uint8_t *&Buf) {
548   unsigned C = sizeof(Elf_Off) * 8;
549 
550   auto *Masks = reinterpret_cast<Elf_Off *>(Buf);
551   for (const SymbolData &Sym : Symbols) {
552     size_t Pos = (Sym.Hash / C) & (MaskWords - 1);
553     uintX_t V = (uintX_t(1) << (Sym.Hash % C)) |
554                 (uintX_t(1) << ((Sym.Hash >> Shift2) % C));
555     Masks[Pos] |= V;
556   }
557   Buf += sizeof(Elf_Off) * MaskWords;
558 }
559 
560 template <class ELFT>
561 void GnuHashTableSection<ELFT>::writeHashTable(uint8_t *Buf) {
562   Elf_Word *Buckets = reinterpret_cast<Elf_Word *>(Buf);
563   Elf_Word *Values = Buckets + NBuckets;
564 
565   int PrevBucket = -1;
566   int I = 0;
567   for (const SymbolData &Sym : Symbols) {
568     int Bucket = Sym.Hash % NBuckets;
569     assert(PrevBucket <= Bucket);
570     if (Bucket != PrevBucket) {
571       Buckets[Bucket] = Sym.Body->DynsymIndex;
572       PrevBucket = Bucket;
573       if (I > 0)
574         Values[I - 1] |= 1;
575     }
576     Values[I] = Sym.Hash & ~1;
577     ++I;
578   }
579   if (I > 0)
580     Values[I - 1] |= 1;
581 }
582 
583 // Add symbols to this symbol hash table. Note that this function
584 // destructively sort a given vector -- which is needed because
585 // GNU-style hash table places some sorting requirements.
586 template <class ELFT>
587 void GnuHashTableSection<ELFT>::addSymbols(
588     std::vector<std::pair<SymbolBody *, size_t>> &V) {
589   // Ideally this will just be 'auto' but GCC 6.1 is not able
590   // to deduce it correctly.
591   std::vector<std::pair<SymbolBody *, size_t>>::iterator Mid =
592       std::stable_partition(V.begin(), V.end(),
593                             [](std::pair<SymbolBody *, size_t> &P) {
594                               return P.first->isUndefined();
595                             });
596   if (Mid == V.end())
597     return;
598   for (auto I = Mid, E = V.end(); I != E; ++I) {
599     SymbolBody *B = I->first;
600     size_t StrOff = I->second;
601     Symbols.push_back({B, StrOff, hashGnu(B->getName())});
602   }
603 
604   unsigned NBuckets = calcNBuckets(Symbols.size());
605   std::stable_sort(Symbols.begin(), Symbols.end(),
606                    [&](const SymbolData &L, const SymbolData &R) {
607                      return L.Hash % NBuckets < R.Hash % NBuckets;
608                    });
609 
610   V.erase(Mid, V.end());
611   for (const SymbolData &Sym : Symbols)
612     V.push_back({Sym.Body, Sym.STName});
613 }
614 
615 // Returns the number of version definition entries. Because the first entry
616 // is for the version definition itself, it is the number of versioned symbols
617 // plus one. Note that we don't support multiple versions yet.
618 static unsigned getVerDefNum() { return Config->VersionDefinitions.size() + 1; }
619 
620 template <class ELFT>
621 DynamicSection<ELFT>::DynamicSection()
622     : OutputSectionBase<ELFT>(".dynamic", SHT_DYNAMIC, SHF_ALLOC | SHF_WRITE) {
623   Elf_Shdr &Header = this->Header;
624   Header.sh_addralign = sizeof(uintX_t);
625   Header.sh_entsize = ELFT::Is64Bits ? 16 : 8;
626 
627   // .dynamic section is not writable on MIPS.
628   // See "Special Section" in Chapter 4 in the following document:
629   // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
630   if (Config->EMachine == EM_MIPS)
631     Header.sh_flags = SHF_ALLOC;
632 }
633 
634 template <class ELFT> void DynamicSection<ELFT>::finalize() {
635   if (this->Header.sh_size)
636     return; // Already finalized.
637 
638   Elf_Shdr &Header = this->Header;
639   Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
640 
641   auto Add = [=](Entry E) { Entries.push_back(E); };
642 
643   // Add strings. We know that these are the last strings to be added to
644   // DynStrTab and doing this here allows this function to set DT_STRSZ.
645   if (!Config->RPath.empty())
646     Add({Config->EnableNewDtags ? DT_RUNPATH : DT_RPATH,
647          Out<ELFT>::DynStrTab->addString(Config->RPath)});
648   for (const std::unique_ptr<SharedFile<ELFT>> &F :
649        Symtab<ELFT>::X->getSharedFiles())
650     if (F->isNeeded())
651       Add({DT_NEEDED, Out<ELFT>::DynStrTab->addString(F->getSoName())});
652   if (!Config->SoName.empty())
653     Add({DT_SONAME, Out<ELFT>::DynStrTab->addString(Config->SoName)});
654 
655   Out<ELFT>::DynStrTab->finalize();
656 
657   if (Out<ELFT>::RelaDyn->hasRelocs()) {
658     bool IsRela = Config->Rela;
659     Add({IsRela ? DT_RELA : DT_REL, Out<ELFT>::RelaDyn});
660     Add({IsRela ? DT_RELASZ : DT_RELSZ, Out<ELFT>::RelaDyn->getSize()});
661     Add({IsRela ? DT_RELAENT : DT_RELENT,
662          uintX_t(IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel))});
663   }
664   if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
665     Add({DT_JMPREL, Out<ELFT>::RelaPlt});
666     Add({DT_PLTRELSZ, Out<ELFT>::RelaPlt->getSize()});
667     Add({Config->EMachine == EM_MIPS ? DT_MIPS_PLTGOT : DT_PLTGOT,
668          Out<ELFT>::GotPlt});
669     Add({DT_PLTREL, uint64_t(Config->Rela ? DT_RELA : DT_REL)});
670   }
671 
672   Add({DT_SYMTAB, Out<ELFT>::DynSymTab});
673   Add({DT_SYMENT, sizeof(Elf_Sym)});
674   Add({DT_STRTAB, Out<ELFT>::DynStrTab});
675   Add({DT_STRSZ, Out<ELFT>::DynStrTab->getSize()});
676   if (Out<ELFT>::GnuHashTab)
677     Add({DT_GNU_HASH, Out<ELFT>::GnuHashTab});
678   if (Out<ELFT>::HashTab)
679     Add({DT_HASH, Out<ELFT>::HashTab});
680 
681   if (PreInitArraySec) {
682     Add({DT_PREINIT_ARRAY, PreInitArraySec});
683     Add({DT_PREINIT_ARRAYSZ, PreInitArraySec->getSize()});
684   }
685   if (InitArraySec) {
686     Add({DT_INIT_ARRAY, InitArraySec});
687     Add({DT_INIT_ARRAYSZ, (uintX_t)InitArraySec->getSize()});
688   }
689   if (FiniArraySec) {
690     Add({DT_FINI_ARRAY, FiniArraySec});
691     Add({DT_FINI_ARRAYSZ, (uintX_t)FiniArraySec->getSize()});
692   }
693 
694   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Init))
695     Add({DT_INIT, B});
696   if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Fini))
697     Add({DT_FINI, B});
698 
699   uint32_t DtFlags = 0;
700   uint32_t DtFlags1 = 0;
701   if (Config->Bsymbolic)
702     DtFlags |= DF_SYMBOLIC;
703   if (Config->ZNodelete)
704     DtFlags1 |= DF_1_NODELETE;
705   if (Config->ZNow) {
706     DtFlags |= DF_BIND_NOW;
707     DtFlags1 |= DF_1_NOW;
708   }
709   if (Config->ZOrigin) {
710     DtFlags |= DF_ORIGIN;
711     DtFlags1 |= DF_1_ORIGIN;
712   }
713 
714   if (DtFlags)
715     Add({DT_FLAGS, DtFlags});
716   if (DtFlags1)
717     Add({DT_FLAGS_1, DtFlags1});
718 
719   if (!Config->Entry.empty())
720     Add({DT_DEBUG, (uint64_t)0});
721 
722   bool HasVerNeed = Out<ELFT>::VerNeed->getNeedNum() != 0;
723   if (HasVerNeed || Out<ELFT>::VerDef)
724     Add({DT_VERSYM, Out<ELFT>::VerSym});
725   if (Out<ELFT>::VerDef) {
726     Add({DT_VERDEF, Out<ELFT>::VerDef});
727     Add({DT_VERDEFNUM, getVerDefNum()});
728   }
729   if (HasVerNeed) {
730     Add({DT_VERNEED, Out<ELFT>::VerNeed});
731     Add({DT_VERNEEDNUM, Out<ELFT>::VerNeed->getNeedNum()});
732   }
733 
734   if (Config->EMachine == EM_MIPS) {
735     Add({DT_MIPS_RLD_VERSION, 1});
736     Add({DT_MIPS_FLAGS, RHF_NOTPOT});
737     Add({DT_MIPS_BASE_ADDRESS, Config->ImageBase});
738     Add({DT_MIPS_SYMTABNO, Out<ELFT>::DynSymTab->getNumSymbols()});
739     Add({DT_MIPS_LOCAL_GOTNO, Out<ELFT>::Got->getMipsLocalEntriesNum()});
740     if (const SymbolBody *B = Out<ELFT>::Got->getMipsFirstGlobalEntry())
741       Add({DT_MIPS_GOTSYM, B->DynsymIndex});
742     else
743       Add({DT_MIPS_GOTSYM, Out<ELFT>::DynSymTab->getNumSymbols()});
744     Add({DT_PLTGOT, Out<ELFT>::Got});
745     if (Out<ELFT>::MipsRldMap)
746       Add({DT_MIPS_RLD_MAP, Out<ELFT>::MipsRldMap});
747   }
748 
749   // +1 for DT_NULL
750   Header.sh_size = (Entries.size() + 1) * Header.sh_entsize;
751 }
752 
753 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
754   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
755 
756   for (const Entry &E : Entries) {
757     P->d_tag = E.Tag;
758     switch (E.Kind) {
759     case Entry::SecAddr:
760       P->d_un.d_ptr = E.OutSec->getVA();
761       break;
762     case Entry::SymAddr:
763       P->d_un.d_ptr = E.Sym->template getVA<ELFT>();
764       break;
765     case Entry::PlainInt:
766       P->d_un.d_val = E.Val;
767       break;
768     }
769     ++P;
770   }
771 }
772 
773 template <class ELFT>
774 EhFrameHeader<ELFT>::EhFrameHeader()
775     : OutputSectionBase<ELFT>(".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC) {}
776 
777 // .eh_frame_hdr contains a binary search table of pointers to FDEs.
778 // Each entry of the search table consists of two values,
779 // the starting PC from where FDEs covers, and the FDE's address.
780 // It is sorted by PC.
781 template <class ELFT> void EhFrameHeader<ELFT>::writeTo(uint8_t *Buf) {
782   const endianness E = ELFT::TargetEndianness;
783 
784   // Sort the FDE list by their PC and uniqueify. Usually there is only
785   // one FDE for a PC (i.e. function), but if ICF merges two functions
786   // into one, there can be more than one FDEs pointing to the address.
787   auto Less = [](const FdeData &A, const FdeData &B) { return A.Pc < B.Pc; };
788   std::stable_sort(Fdes.begin(), Fdes.end(), Less);
789   auto Eq = [](const FdeData &A, const FdeData &B) { return A.Pc == B.Pc; };
790   Fdes.erase(std::unique(Fdes.begin(), Fdes.end(), Eq), Fdes.end());
791 
792   Buf[0] = 1;
793   Buf[1] = DW_EH_PE_pcrel | DW_EH_PE_sdata4;
794   Buf[2] = DW_EH_PE_udata4;
795   Buf[3] = DW_EH_PE_datarel | DW_EH_PE_sdata4;
796   write32<E>(Buf + 4, Out<ELFT>::EhFrame->getVA() - this->getVA() - 4);
797   write32<E>(Buf + 8, Fdes.size());
798   Buf += 12;
799 
800   uintX_t VA = this->getVA();
801   for (FdeData &Fde : Fdes) {
802     write32<E>(Buf, Fde.Pc - VA);
803     write32<E>(Buf + 4, Fde.FdeVA - VA);
804     Buf += 8;
805   }
806 }
807 
808 template <class ELFT> void EhFrameHeader<ELFT>::finalize() {
809   // .eh_frame_hdr has a 12 bytes header followed by an array of FDEs.
810   this->Header.sh_size = 12 + Out<ELFT>::EhFrame->NumFdes * 8;
811 }
812 
813 template <class ELFT>
814 void EhFrameHeader<ELFT>::addFde(uint32_t Pc, uint32_t FdeVA) {
815   Fdes.push_back({Pc, FdeVA});
816 }
817 
818 template <class ELFT>
819 OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
820     : OutputSectionBase<ELFT>(Name, Type, Flags) {
821   if (Type == SHT_RELA)
822     this->Header.sh_entsize = sizeof(Elf_Rela);
823   else if (Type == SHT_REL)
824     this->Header.sh_entsize = sizeof(Elf_Rel);
825 }
826 
827 template <class ELFT> void OutputSection<ELFT>::finalize() {
828   uint32_t Type = this->Header.sh_type;
829   if (Type != SHT_RELA && Type != SHT_REL)
830     return;
831   this->Header.sh_link = Out<ELFT>::SymTab->SectionIndex;
832   // sh_info for SHT_REL[A] sections should contain the section header index of
833   // the section to which the relocation applies.
834   InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
835   this->Header.sh_info = S->OutSec->SectionIndex;
836 }
837 
838 template <class ELFT>
839 void OutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
840   assert(C->Live);
841   auto *S = cast<InputSection<ELFT>>(C);
842   Sections.push_back(S);
843   S->OutSec = this;
844   this->updateAlignment(S->Alignment);
845 }
846 
847 // If an input string is in the form of "foo.N" where N is a number,
848 // return N. Otherwise, returns 65536, which is one greater than the
849 // lowest priority.
850 static int getPriority(StringRef S) {
851   size_t Pos = S.rfind('.');
852   if (Pos == StringRef::npos)
853     return 65536;
854   int V;
855   if (S.substr(Pos + 1).getAsInteger(10, V))
856     return 65536;
857   return V;
858 }
859 
860 // This function is called after we sort input sections
861 // and scan relocations to setup sections' offsets.
862 template <class ELFT> void OutputSection<ELFT>::assignOffsets() {
863   uintX_t Off = this->Header.sh_size;
864   for (InputSection<ELFT> *S : Sections) {
865     Off = alignTo(Off, S->Alignment);
866     S->OutSecOff = Off;
867     Off += S->getSize();
868   }
869   this->Header.sh_size = Off;
870 }
871 
872 // Sorts input sections by section name suffixes, so that .foo.N comes
873 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
874 // We want to keep the original order if the priorities are the same
875 // because the compiler keeps the original initialization order in a
876 // translation unit and we need to respect that.
877 // For more detail, read the section of the GCC's manual about init_priority.
878 template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
879   // Sort sections by priority.
880   typedef std::pair<int, InputSection<ELFT> *> Pair;
881   auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
882 
883   std::vector<Pair> V;
884   for (InputSection<ELFT> *S : Sections)
885     V.push_back({getPriority(S->getSectionName()), S});
886   std::stable_sort(V.begin(), V.end(), Comp);
887   Sections.clear();
888   for (Pair &P : V)
889     Sections.push_back(P.second);
890 }
891 
892 // Returns true if S matches /Filename.?\.o$/.
893 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
894   if (!S.endswith(".o"))
895     return false;
896   S = S.drop_back(2);
897   if (S.endswith(Filename))
898     return true;
899   return !S.empty() && S.drop_back().endswith(Filename);
900 }
901 
902 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
903 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
904 
905 // .ctors and .dtors are sorted by this priority from highest to lowest.
906 //
907 //  1. The section was contained in crtbegin (crtbegin contains
908 //     some sentinel value in its .ctors and .dtors so that the runtime
909 //     can find the beginning of the sections.)
910 //
911 //  2. The section has an optional priority value in the form of ".ctors.N"
912 //     or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
913 //     they are compared as string rather than number.
914 //
915 //  3. The section is just ".ctors" or ".dtors".
916 //
917 //  4. The section was contained in crtend, which contains an end marker.
918 //
919 // In an ideal world, we don't need this function because .init_array and
920 // .ctors are duplicate features (and .init_array is newer.) However, there
921 // are too many real-world use cases of .ctors, so we had no choice to
922 // support that with this rather ad-hoc semantics.
923 template <class ELFT>
924 static bool compCtors(const InputSection<ELFT> *A,
925                       const InputSection<ELFT> *B) {
926   bool BeginA = isCrtbegin(A->getFile()->getName());
927   bool BeginB = isCrtbegin(B->getFile()->getName());
928   if (BeginA != BeginB)
929     return BeginA;
930   bool EndA = isCrtend(A->getFile()->getName());
931   bool EndB = isCrtend(B->getFile()->getName());
932   if (EndA != EndB)
933     return EndB;
934   StringRef X = A->getSectionName();
935   StringRef Y = B->getSectionName();
936   assert(X.startswith(".ctors") || X.startswith(".dtors"));
937   assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
938   X = X.substr(6);
939   Y = Y.substr(6);
940   if (X.empty() && Y.empty())
941     return false;
942   return X < Y;
943 }
944 
945 // Sorts input sections by the special rules for .ctors and .dtors.
946 // Unfortunately, the rules are different from the one for .{init,fini}_array.
947 // Read the comment above.
948 template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
949   std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
950 }
951 
952 static void fill(uint8_t *Buf, size_t Size, ArrayRef<uint8_t> A) {
953   size_t I = 0;
954   for (; I + A.size() < Size; I += A.size())
955     memcpy(Buf + I, A.data(), A.size());
956   memcpy(Buf + I, A.data(), Size - I);
957 }
958 
959 template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
960   ArrayRef<uint8_t> Filler = Script<ELFT>::X->getFiller(this->Name);
961   if (!Filler.empty())
962     fill(Buf, this->getSize(), Filler);
963   if (Config->Threads) {
964     parallel_for_each(Sections.begin(), Sections.end(),
965                       [=](InputSection<ELFT> *C) { C->writeTo(Buf); });
966   } else {
967     for (InputSection<ELFT> *C : Sections)
968       C->writeTo(Buf);
969   }
970 }
971 
972 template <class ELFT>
973 EhOutputSection<ELFT>::EhOutputSection()
974     : OutputSectionBase<ELFT>(".eh_frame", SHT_PROGBITS, SHF_ALLOC) {}
975 
976 // Search for an existing CIE record or create a new one.
977 // CIE records from input object files are uniquified by their contents
978 // and where their relocations point to.
979 template <class ELFT>
980 template <class RelTy>
981 CieRecord *EhOutputSection<ELFT>::addCie(EhSectionPiece &Piece,
982                                          EhInputSection<ELFT> *Sec,
983                                          ArrayRef<RelTy> Rels) {
984   const endianness E = ELFT::TargetEndianness;
985   if (read32<E>(Piece.data().data() + 4) != 0)
986     fatal("CIE expected at beginning of .eh_frame: " + Sec->getSectionName());
987 
988   SymbolBody *Personality = nullptr;
989   unsigned FirstRelI = Piece.FirstRelocation;
990   if (FirstRelI != (unsigned)-1)
991     Personality = &Sec->getFile()->getRelocTargetSym(Rels[FirstRelI]);
992 
993   // Search for an existing CIE by CIE contents/relocation target pair.
994   CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
995 
996   // If not found, create a new one.
997   if (Cie->Piece == nullptr) {
998     Cie->Piece = &Piece;
999     Cies.push_back(Cie);
1000   }
1001   return Cie;
1002 }
1003 
1004 // There is one FDE per function. Returns true if a given FDE
1005 // points to a live function.
1006 template <class ELFT>
1007 template <class RelTy>
1008 bool EhOutputSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
1009                                       EhInputSection<ELFT> *Sec,
1010                                       ArrayRef<RelTy> Rels) {
1011   unsigned FirstRelI = Piece.FirstRelocation;
1012   if (FirstRelI == (unsigned)-1)
1013     fatal("FDE doesn't reference another section");
1014   const RelTy &Rel = Rels[FirstRelI];
1015   SymbolBody &B = Sec->getFile()->getRelocTargetSym(Rel);
1016   auto *D = dyn_cast<DefinedRegular<ELFT>>(&B);
1017   if (!D || !D->Section)
1018     return false;
1019   InputSectionBase<ELFT> *Target = D->Section->Repl;
1020   return Target && Target->Live;
1021 }
1022 
1023 // .eh_frame is a sequence of CIE or FDE records. In general, there
1024 // is one CIE record per input object file which is followed by
1025 // a list of FDEs. This function searches an existing CIE or create a new
1026 // one and associates FDEs to the CIE.
1027 template <class ELFT>
1028 template <class RelTy>
1029 void EhOutputSection<ELFT>::addSectionAux(EhInputSection<ELFT> *Sec,
1030                                           ArrayRef<RelTy> Rels) {
1031   const endianness E = ELFT::TargetEndianness;
1032 
1033   DenseMap<size_t, CieRecord *> OffsetToCie;
1034   for (EhSectionPiece &Piece : Sec->Pieces) {
1035     // The empty record is the end marker.
1036     if (Piece.size() == 4)
1037       return;
1038 
1039     size_t Offset = Piece.InputOff;
1040     uint32_t ID = read32<E>(Piece.data().data() + 4);
1041     if (ID == 0) {
1042       OffsetToCie[Offset] = addCie(Piece, Sec, Rels);
1043       continue;
1044     }
1045 
1046     uint32_t CieOffset = Offset + 4 - ID;
1047     CieRecord *Cie = OffsetToCie[CieOffset];
1048     if (!Cie)
1049       fatal("invalid CIE reference");
1050 
1051     if (!isFdeLive(Piece, Sec, Rels))
1052       continue;
1053     Cie->FdePieces.push_back(&Piece);
1054     NumFdes++;
1055   }
1056 }
1057 
1058 template <class ELFT>
1059 void EhOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1060   auto *Sec = cast<EhInputSection<ELFT>>(C);
1061   Sec->OutSec = this;
1062   this->updateAlignment(Sec->Alignment);
1063   Sections.push_back(Sec);
1064 
1065   // .eh_frame is a sequence of CIE or FDE records. This function
1066   // splits it into pieces so that we can call
1067   // SplitInputSection::getSectionPiece on the section.
1068   Sec->split();
1069   if (Sec->Pieces.empty())
1070     return;
1071 
1072   if (const Elf_Shdr *RelSec = Sec->RelocSection) {
1073     ELFFile<ELFT> &Obj = Sec->getFile()->getObj();
1074     if (RelSec->sh_type == SHT_RELA)
1075       addSectionAux(Sec, Obj.relas(RelSec));
1076     else
1077       addSectionAux(Sec, Obj.rels(RelSec));
1078     return;
1079   }
1080   addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
1081 }
1082 
1083 template <class ELFT>
1084 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
1085   memcpy(Buf, D.data(), D.size());
1086 
1087   // Fix the size field. -4 since size does not include the size field itself.
1088   const endianness E = ELFT::TargetEndianness;
1089   write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
1090 }
1091 
1092 template <class ELFT> void EhOutputSection<ELFT>::finalize() {
1093   if (this->Header.sh_size)
1094     return; // Already finalized.
1095 
1096   size_t Off = 0;
1097   for (CieRecord *Cie : Cies) {
1098     Cie->Piece->OutputOff = Off;
1099     Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
1100 
1101     for (SectionPiece *Fde : Cie->FdePieces) {
1102       Fde->OutputOff = Off;
1103       Off += alignTo(Fde->size(), sizeof(uintX_t));
1104     }
1105   }
1106   this->Header.sh_size = Off;
1107 }
1108 
1109 template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
1110   const endianness E = ELFT::TargetEndianness;
1111   switch (Size) {
1112   case DW_EH_PE_udata2:
1113     return read16<E>(Buf);
1114   case DW_EH_PE_udata4:
1115     return read32<E>(Buf);
1116   case DW_EH_PE_udata8:
1117     return read64<E>(Buf);
1118   case DW_EH_PE_absptr:
1119     if (ELFT::Is64Bits)
1120       return read64<E>(Buf);
1121     return read32<E>(Buf);
1122   }
1123   fatal("unknown FDE size encoding");
1124 }
1125 
1126 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
1127 // We need it to create .eh_frame_hdr section.
1128 template <class ELFT>
1129 typename ELFT::uint EhOutputSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
1130                                                     uint8_t Enc) {
1131   // The starting address to which this FDE applies is
1132   // stored at FDE + 8 byte.
1133   size_t Off = FdeOff + 8;
1134   uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
1135   if ((Enc & 0x70) == DW_EH_PE_absptr)
1136     return Addr;
1137   if ((Enc & 0x70) == DW_EH_PE_pcrel)
1138     return Addr + this->getVA() + Off;
1139   fatal("unknown FDE size relative encoding");
1140 }
1141 
1142 template <class ELFT> void EhOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1143   const endianness E = ELFT::TargetEndianness;
1144   for (CieRecord *Cie : Cies) {
1145     size_t CieOffset = Cie->Piece->OutputOff;
1146     writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
1147 
1148     for (SectionPiece *Fde : Cie->FdePieces) {
1149       size_t Off = Fde->OutputOff;
1150       writeCieFde<ELFT>(Buf + Off, Fde->data());
1151 
1152       // FDE's second word should have the offset to an associated CIE.
1153       // Write it.
1154       write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
1155     }
1156   }
1157 
1158   for (EhInputSection<ELFT> *S : Sections)
1159     S->relocate(Buf, nullptr);
1160 
1161   // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
1162   // to get a FDE from an address to which FDE is applied. So here
1163   // we obtain two addresses and pass them to EhFrameHdr object.
1164   if (Out<ELFT>::EhFrameHdr) {
1165     for (CieRecord *Cie : Cies) {
1166       uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece->data());
1167       for (SectionPiece *Fde : Cie->FdePieces) {
1168         uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
1169         uintX_t FdeVA = this->getVA() + Fde->OutputOff;
1170         Out<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
1171       }
1172     }
1173   }
1174 }
1175 
1176 template <class ELFT>
1177 MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
1178                                              uintX_t Flags, uintX_t Alignment)
1179     : OutputSectionBase<ELFT>(Name, Type, Flags),
1180       Builder(StringTableBuilder::RAW, Alignment) {}
1181 
1182 template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1183   if (shouldTailMerge()) {
1184     StringRef Data = Builder.data();
1185     memcpy(Buf, Data.data(), Data.size());
1186     return;
1187   }
1188   for (const std::pair<CachedHash<StringRef>, size_t> &P : Builder.getMap()) {
1189     StringRef Data = P.first.Val;
1190     memcpy(Buf + P.second, Data.data(), Data.size());
1191   }
1192 }
1193 
1194 static StringRef toStringRef(ArrayRef<uint8_t> A) {
1195   return {(const char *)A.data(), A.size()};
1196 }
1197 
1198 template <class ELFT>
1199 void MergeOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1200   auto *Sec = cast<MergeInputSection<ELFT>>(C);
1201   Sec->OutSec = this;
1202   this->updateAlignment(Sec->Alignment);
1203   this->Header.sh_entsize = Sec->getSectionHdr()->sh_entsize;
1204   Sections.push_back(Sec);
1205 
1206   bool IsString = this->Header.sh_flags & SHF_STRINGS;
1207 
1208   for (SectionPiece &Piece : Sec->Pieces) {
1209     if (!Piece.Live)
1210       continue;
1211     uintX_t OutputOffset = Builder.add(toStringRef(Piece.data()));
1212     if (!IsString || !shouldTailMerge())
1213       Piece.OutputOff = OutputOffset;
1214   }
1215 }
1216 
1217 template <class ELFT>
1218 unsigned MergeOutputSection<ELFT>::getOffset(StringRef Val) {
1219   return Builder.getOffset(Val);
1220 }
1221 
1222 template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
1223   return Config->Optimize >= 2 && this->Header.sh_flags & SHF_STRINGS;
1224 }
1225 
1226 template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
1227   if (shouldTailMerge())
1228     Builder.finalize();
1229   this->Header.sh_size = Builder.getSize();
1230 }
1231 
1232 template <class ELFT> void MergeOutputSection<ELFT>::finalizePieces() {
1233   for (MergeInputSection<ELFT> *Sec : Sections)
1234     Sec->finalizePieces();
1235 }
1236 
1237 template <class ELFT>
1238 StringTableSection<ELFT>::StringTableSection(StringRef Name, bool Dynamic)
1239     : OutputSectionBase<ELFT>(Name, SHT_STRTAB,
1240                               Dynamic ? (uintX_t)SHF_ALLOC : 0),
1241       Dynamic(Dynamic) {}
1242 
1243 // Adds a string to the string table. If HashIt is true we hash and check for
1244 // duplicates. It is optional because the name of global symbols are already
1245 // uniqued and hashing them again has a big cost for a small value: uniquing
1246 // them with some other string that happens to be the same.
1247 template <class ELFT>
1248 unsigned StringTableSection<ELFT>::addString(StringRef S, bool HashIt) {
1249   if (HashIt) {
1250     auto R = StringMap.insert(std::make_pair(S, Size));
1251     if (!R.second)
1252       return R.first->second;
1253   }
1254   unsigned Ret = Size;
1255   Size += S.size() + 1;
1256   Strings.push_back(S);
1257   return Ret;
1258 }
1259 
1260 template <class ELFT> void StringTableSection<ELFT>::writeTo(uint8_t *Buf) {
1261   // ELF string tables start with NUL byte, so advance the pointer by one.
1262   ++Buf;
1263   for (StringRef S : Strings) {
1264     memcpy(Buf, S.data(), S.size());
1265     Buf += S.size() + 1;
1266   }
1267 }
1268 
1269 template <class ELFT>
1270 typename ELFT::uint DynamicReloc<ELFT>::getOffset() const {
1271   if (OutputSec)
1272     return OutputSec->getVA() + OffsetInSec;
1273   return InputSec->OutSec->getVA() + OffsetInSec;
1274 }
1275 
1276 template <class ELFT>
1277 typename ELFT::uint DynamicReloc<ELFT>::getAddend() const {
1278   if (UseSymVA)
1279     return Sym->getVA<ELFT>(Addend);
1280   return Addend;
1281 }
1282 
1283 template <class ELFT> uint32_t DynamicReloc<ELFT>::getSymIndex() const {
1284   if (Sym && !UseSymVA)
1285     return Sym->DynsymIndex;
1286   return 0;
1287 }
1288 
1289 template <class ELFT>
1290 SymbolTableSection<ELFT>::SymbolTableSection(
1291     StringTableSection<ELFT> &StrTabSec)
1292     : OutputSectionBase<ELFT>(StrTabSec.isDynamic() ? ".dynsym" : ".symtab",
1293                               StrTabSec.isDynamic() ? SHT_DYNSYM : SHT_SYMTAB,
1294                               StrTabSec.isDynamic() ? (uintX_t)SHF_ALLOC : 0),
1295       StrTabSec(StrTabSec) {
1296   this->Header.sh_entsize = sizeof(Elf_Sym);
1297   this->Header.sh_addralign = sizeof(uintX_t);
1298 }
1299 
1300 // Orders symbols according to their positions in the GOT,
1301 // in compliance with MIPS ABI rules.
1302 // See "Global Offset Table" in Chapter 5 in the following document
1303 // for detailed description:
1304 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
1305 static bool sortMipsSymbols(const std::pair<SymbolBody *, unsigned> &L,
1306                             const std::pair<SymbolBody *, unsigned> &R) {
1307   // Sort entries related to non-local preemptible symbols by GOT indexes.
1308   // All other entries go to the first part of GOT in arbitrary order.
1309   bool LIsInLocalGot = !L.first->IsInGlobalMipsGot;
1310   bool RIsInLocalGot = !R.first->IsInGlobalMipsGot;
1311   if (LIsInLocalGot || RIsInLocalGot)
1312     return !RIsInLocalGot;
1313   return L.first->GotIndex < R.first->GotIndex;
1314 }
1315 
1316 static uint8_t getSymbolBinding(SymbolBody *Body) {
1317   Symbol *S = Body->symbol();
1318   uint8_t Visibility = S->Visibility;
1319   if (Visibility != STV_DEFAULT && Visibility != STV_PROTECTED)
1320     return STB_LOCAL;
1321   if (Config->NoGnuUnique && S->Binding == STB_GNU_UNIQUE)
1322     return STB_GLOBAL;
1323   return S->Binding;
1324 }
1325 
1326 template <class ELFT> void SymbolTableSection<ELFT>::finalize() {
1327   if (this->Header.sh_size)
1328     return; // Already finalized.
1329 
1330   this->Header.sh_size = getNumSymbols() * sizeof(Elf_Sym);
1331   this->Header.sh_link = StrTabSec.SectionIndex;
1332   this->Header.sh_info = NumLocals + 1;
1333 
1334   if (Config->Relocatable) {
1335     size_t I = NumLocals;
1336     for (const std::pair<SymbolBody *, size_t> &P : Symbols)
1337       P.first->DynsymIndex = ++I;
1338     return;
1339   }
1340 
1341   if (!StrTabSec.isDynamic()) {
1342     std::stable_sort(Symbols.begin(), Symbols.end(),
1343                      [](const std::pair<SymbolBody *, unsigned> &L,
1344                         const std::pair<SymbolBody *, unsigned> &R) {
1345                        return getSymbolBinding(L.first) == STB_LOCAL &&
1346                               getSymbolBinding(R.first) != STB_LOCAL;
1347                      });
1348     return;
1349   }
1350   if (Out<ELFT>::GnuHashTab)
1351     // NB: It also sorts Symbols to meet the GNU hash table requirements.
1352     Out<ELFT>::GnuHashTab->addSymbols(Symbols);
1353   else if (Config->EMachine == EM_MIPS)
1354     std::stable_sort(Symbols.begin(), Symbols.end(), sortMipsSymbols);
1355   size_t I = 0;
1356   for (const std::pair<SymbolBody *, size_t> &P : Symbols)
1357     P.first->DynsymIndex = ++I;
1358 }
1359 
1360 template <class ELFT>
1361 void SymbolTableSection<ELFT>::addSymbol(SymbolBody *B) {
1362   Symbols.push_back({B, StrTabSec.addString(B->getName(), false)});
1363 }
1364 
1365 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
1366   Buf += sizeof(Elf_Sym);
1367 
1368   // All symbols with STB_LOCAL binding precede the weak and global symbols.
1369   // .dynsym only contains global symbols.
1370   if (!Config->DiscardAll && !StrTabSec.isDynamic())
1371     writeLocalSymbols(Buf);
1372 
1373   writeGlobalSymbols(Buf);
1374 }
1375 
1376 template <class ELFT>
1377 void SymbolTableSection<ELFT>::writeLocalSymbols(uint8_t *&Buf) {
1378   // Iterate over all input object files to copy their local symbols
1379   // to the output symbol table pointed by Buf.
1380   for (const std::unique_ptr<ObjectFile<ELFT>> &File :
1381        Symtab<ELFT>::X->getObjectFiles()) {
1382     for (const std::pair<const DefinedRegular<ELFT> *, size_t> &P :
1383          File->KeptLocalSyms) {
1384       const DefinedRegular<ELFT> &Body = *P.first;
1385       InputSectionBase<ELFT> *Section = Body.Section;
1386       auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1387 
1388       if (!Section) {
1389         ESym->st_shndx = SHN_ABS;
1390         ESym->st_value = Body.Value;
1391       } else {
1392         const OutputSectionBase<ELFT> *OutSec = Section->OutSec;
1393         ESym->st_shndx = OutSec->SectionIndex;
1394         ESym->st_value = OutSec->getVA() + Section->getOffset(Body);
1395       }
1396       ESym->st_name = P.second;
1397       ESym->st_size = Body.template getSize<ELFT>();
1398       ESym->setBindingAndType(STB_LOCAL, Body.Type);
1399       Buf += sizeof(*ESym);
1400     }
1401   }
1402 }
1403 
1404 template <class ELFT>
1405 void SymbolTableSection<ELFT>::writeGlobalSymbols(uint8_t *Buf) {
1406   // Write the internal symbol table contents to the output symbol table
1407   // pointed by Buf.
1408   auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
1409   for (const std::pair<SymbolBody *, size_t> &P : Symbols) {
1410     SymbolBody *Body = P.first;
1411     size_t StrOff = P.second;
1412 
1413     uint8_t Type = Body->Type;
1414     uintX_t Size = Body->getSize<ELFT>();
1415 
1416     ESym->setBindingAndType(getSymbolBinding(Body), Type);
1417     ESym->st_size = Size;
1418     ESym->st_name = StrOff;
1419     ESym->setVisibility(Body->symbol()->Visibility);
1420     ESym->st_value = Body->getVA<ELFT>();
1421 
1422     if (const OutputSectionBase<ELFT> *OutSec = getOutputSection(Body))
1423       ESym->st_shndx = OutSec->SectionIndex;
1424     else if (isa<DefinedRegular<ELFT>>(Body))
1425       ESym->st_shndx = SHN_ABS;
1426 
1427     // On MIPS we need to mark symbol which has a PLT entry and requires pointer
1428     // equality by STO_MIPS_PLT flag. That is necessary to help dynamic linker
1429     // distinguish such symbols and MIPS lazy-binding stubs.
1430     // https://sourceware.org/ml/binutils/2008-07/txt00000.txt
1431     if (Config->EMachine == EM_MIPS && Body->isInPlt() &&
1432         Body->NeedsCopyOrPltAddr)
1433       ESym->st_other |= STO_MIPS_PLT;
1434     ++ESym;
1435   }
1436 }
1437 
1438 template <class ELFT>
1439 const OutputSectionBase<ELFT> *
1440 SymbolTableSection<ELFT>::getOutputSection(SymbolBody *Sym) {
1441   switch (Sym->kind()) {
1442   case SymbolBody::DefinedSyntheticKind:
1443     return cast<DefinedSynthetic<ELFT>>(Sym)->Section;
1444   case SymbolBody::DefinedRegularKind: {
1445     auto &D = cast<DefinedRegular<ELFT>>(*Sym);
1446     if (D.Section)
1447       return D.Section->OutSec;
1448     break;
1449   }
1450   case SymbolBody::DefinedCommonKind:
1451     return CommonInputSection<ELFT>::X->OutSec;
1452   case SymbolBody::SharedKind:
1453     if (cast<SharedSymbol<ELFT>>(Sym)->needsCopy())
1454       return Out<ELFT>::Bss;
1455     break;
1456   case SymbolBody::UndefinedKind:
1457   case SymbolBody::LazyArchiveKind:
1458   case SymbolBody::LazyObjectKind:
1459     break;
1460   case SymbolBody::DefinedBitcodeKind:
1461     llvm_unreachable("should have been replaced");
1462   }
1463   return nullptr;
1464 }
1465 
1466 template <class ELFT>
1467 VersionDefinitionSection<ELFT>::VersionDefinitionSection()
1468     : OutputSectionBase<ELFT>(".gnu.version_d", SHT_GNU_verdef, SHF_ALLOC) {
1469   this->Header.sh_addralign = sizeof(uint32_t);
1470 }
1471 
1472 static StringRef getFileDefName() {
1473   if (!Config->SoName.empty())
1474     return Config->SoName;
1475   return Config->OutputFile;
1476 }
1477 
1478 template <class ELFT> void VersionDefinitionSection<ELFT>::finalize() {
1479   FileDefNameOff = Out<ELFT>::DynStrTab->addString(getFileDefName());
1480   for (VersionDefinition &V : Config->VersionDefinitions)
1481     V.NameOff = Out<ELFT>::DynStrTab->addString(V.Name);
1482 
1483   this->Header.sh_size =
1484       (sizeof(Elf_Verdef) + sizeof(Elf_Verdaux)) * getVerDefNum();
1485   this->Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
1486 
1487   // sh_info should be set to the number of definitions. This fact is missed in
1488   // documentation, but confirmed by binutils community:
1489   // https://sourceware.org/ml/binutils/2014-11/msg00355.html
1490   this->Header.sh_info = getVerDefNum();
1491 }
1492 
1493 template <class ELFT>
1494 void VersionDefinitionSection<ELFT>::writeOne(uint8_t *Buf, uint32_t Index,
1495                                               StringRef Name, size_t NameOff) {
1496   auto *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1497   Verdef->vd_version = 1;
1498   Verdef->vd_cnt = 1;
1499   Verdef->vd_aux = sizeof(Elf_Verdef);
1500   Verdef->vd_next = sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1501   Verdef->vd_flags = (Index == 1 ? VER_FLG_BASE : 0);
1502   Verdef->vd_ndx = Index;
1503   Verdef->vd_hash = hashSysv(Name);
1504 
1505   auto *Verdaux = reinterpret_cast<Elf_Verdaux *>(Buf + sizeof(Elf_Verdef));
1506   Verdaux->vda_name = NameOff;
1507   Verdaux->vda_next = 0;
1508 }
1509 
1510 template <class ELFT>
1511 void VersionDefinitionSection<ELFT>::writeTo(uint8_t *Buf) {
1512   writeOne(Buf, 1, getFileDefName(), FileDefNameOff);
1513 
1514   for (VersionDefinition &V : Config->VersionDefinitions) {
1515     Buf += sizeof(Elf_Verdef) + sizeof(Elf_Verdaux);
1516     writeOne(Buf, V.Id, V.Name, V.NameOff);
1517   }
1518 
1519   // Need to terminate the last version definition.
1520   Elf_Verdef *Verdef = reinterpret_cast<Elf_Verdef *>(Buf);
1521   Verdef->vd_next = 0;
1522 }
1523 
1524 template <class ELFT>
1525 VersionTableSection<ELFT>::VersionTableSection()
1526     : OutputSectionBase<ELFT>(".gnu.version", SHT_GNU_versym, SHF_ALLOC) {
1527   this->Header.sh_addralign = sizeof(uint16_t);
1528 }
1529 
1530 template <class ELFT> void VersionTableSection<ELFT>::finalize() {
1531   this->Header.sh_size =
1532       sizeof(Elf_Versym) * (Out<ELFT>::DynSymTab->getSymbols().size() + 1);
1533   this->Header.sh_entsize = sizeof(Elf_Versym);
1534   // At the moment of june 2016 GNU docs does not mention that sh_link field
1535   // should be set, but Sun docs do. Also readelf relies on this field.
1536   this->Header.sh_link = Out<ELFT>::DynSymTab->SectionIndex;
1537 }
1538 
1539 template <class ELFT> void VersionTableSection<ELFT>::writeTo(uint8_t *Buf) {
1540   auto *OutVersym = reinterpret_cast<Elf_Versym *>(Buf) + 1;
1541   for (const std::pair<SymbolBody *, size_t> &P :
1542        Out<ELFT>::DynSymTab->getSymbols()) {
1543     OutVersym->vs_index = P.first->symbol()->VersionId;
1544     ++OutVersym;
1545   }
1546 }
1547 
1548 template <class ELFT>
1549 VersionNeedSection<ELFT>::VersionNeedSection()
1550     : OutputSectionBase<ELFT>(".gnu.version_r", SHT_GNU_verneed, SHF_ALLOC) {
1551   this->Header.sh_addralign = sizeof(uint32_t);
1552 
1553   // Identifiers in verneed section start at 2 because 0 and 1 are reserved
1554   // for VER_NDX_LOCAL and VER_NDX_GLOBAL.
1555   // First identifiers are reserved by verdef section if it exist.
1556   NextIndex = getVerDefNum() + 1;
1557 }
1558 
1559 template <class ELFT>
1560 void VersionNeedSection<ELFT>::addSymbol(SharedSymbol<ELFT> *SS) {
1561   if (!SS->Verdef) {
1562     SS->symbol()->VersionId = VER_NDX_GLOBAL;
1563     return;
1564   }
1565   SharedFile<ELFT> *F = SS->file();
1566   // If we don't already know that we need an Elf_Verneed for this DSO, prepare
1567   // to create one by adding it to our needed list and creating a dynstr entry
1568   // for the soname.
1569   if (F->VerdefMap.empty())
1570     Needed.push_back({F, Out<ELFT>::DynStrTab->addString(F->getSoName())});
1571   typename SharedFile<ELFT>::NeededVer &NV = F->VerdefMap[SS->Verdef];
1572   // If we don't already know that we need an Elf_Vernaux for this Elf_Verdef,
1573   // prepare to create one by allocating a version identifier and creating a
1574   // dynstr entry for the version name.
1575   if (NV.Index == 0) {
1576     NV.StrTab = Out<ELFT>::DynStrTab->addString(
1577         SS->file()->getStringTable().data() + SS->Verdef->getAux()->vda_name);
1578     NV.Index = NextIndex++;
1579   }
1580   SS->symbol()->VersionId = NV.Index;
1581 }
1582 
1583 template <class ELFT> void VersionNeedSection<ELFT>::writeTo(uint8_t *Buf) {
1584   // The Elf_Verneeds need to appear first, followed by the Elf_Vernauxs.
1585   auto *Verneed = reinterpret_cast<Elf_Verneed *>(Buf);
1586   auto *Vernaux = reinterpret_cast<Elf_Vernaux *>(Verneed + Needed.size());
1587 
1588   for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed) {
1589     // Create an Elf_Verneed for this DSO.
1590     Verneed->vn_version = 1;
1591     Verneed->vn_cnt = P.first->VerdefMap.size();
1592     Verneed->vn_file = P.second;
1593     Verneed->vn_aux =
1594         reinterpret_cast<char *>(Vernaux) - reinterpret_cast<char *>(Verneed);
1595     Verneed->vn_next = sizeof(Elf_Verneed);
1596     ++Verneed;
1597 
1598     // Create the Elf_Vernauxs for this Elf_Verneed. The loop iterates over
1599     // VerdefMap, which will only contain references to needed version
1600     // definitions. Each Elf_Vernaux is based on the information contained in
1601     // the Elf_Verdef in the source DSO. This loop iterates over a std::map of
1602     // pointers, but is deterministic because the pointers refer to Elf_Verdef
1603     // data structures within a single input file.
1604     for (auto &NV : P.first->VerdefMap) {
1605       Vernaux->vna_hash = NV.first->vd_hash;
1606       Vernaux->vna_flags = 0;
1607       Vernaux->vna_other = NV.second.Index;
1608       Vernaux->vna_name = NV.second.StrTab;
1609       Vernaux->vna_next = sizeof(Elf_Vernaux);
1610       ++Vernaux;
1611     }
1612 
1613     Vernaux[-1].vna_next = 0;
1614   }
1615   Verneed[-1].vn_next = 0;
1616 }
1617 
1618 template <class ELFT> void VersionNeedSection<ELFT>::finalize() {
1619   this->Header.sh_link = Out<ELFT>::DynStrTab->SectionIndex;
1620   this->Header.sh_info = Needed.size();
1621   unsigned Size = Needed.size() * sizeof(Elf_Verneed);
1622   for (std::pair<SharedFile<ELFT> *, size_t> &P : Needed)
1623     Size += P.first->VerdefMap.size() * sizeof(Elf_Vernaux);
1624   this->Header.sh_size = Size;
1625 }
1626 
1627 template <class ELFT>
1628 BuildIdSection<ELFT>::BuildIdSection(size_t HashSize)
1629     : OutputSectionBase<ELFT>(".note.gnu.build-id", SHT_NOTE, SHF_ALLOC),
1630       HashSize(HashSize) {
1631   // 16 bytes for the note section header.
1632   this->Header.sh_size = 16 + HashSize;
1633 }
1634 
1635 template <class ELFT> void BuildIdSection<ELFT>::writeTo(uint8_t *Buf) {
1636   const endianness E = ELFT::TargetEndianness;
1637   write32<E>(Buf, 4);                   // Name size
1638   write32<E>(Buf + 4, HashSize);        // Content size
1639   write32<E>(Buf + 8, NT_GNU_BUILD_ID); // Type
1640   memcpy(Buf + 12, "GNU", 4);           // Name string
1641   HashBuf = Buf + 16;
1642 }
1643 
1644 template <class ELFT>
1645 void BuildIdFnv1<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1646   const endianness E = ELFT::TargetEndianness;
1647 
1648   // 64-bit FNV-1 hash
1649   uint64_t Hash = 0xcbf29ce484222325;
1650   for (ArrayRef<uint8_t> Buf : Bufs) {
1651     for (uint8_t B : Buf) {
1652       Hash *= 0x100000001b3;
1653       Hash ^= B;
1654     }
1655   }
1656   write64<E>(this->HashBuf, Hash);
1657 }
1658 
1659 template <class ELFT>
1660 void BuildIdMd5<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1661   MD5 Hash;
1662   for (ArrayRef<uint8_t> Buf : Bufs)
1663     Hash.update(Buf);
1664   MD5::MD5Result Res;
1665   Hash.final(Res);
1666   memcpy(this->HashBuf, Res, 16);
1667 }
1668 
1669 template <class ELFT>
1670 void BuildIdSha1<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1671   SHA1 Hash;
1672   for (ArrayRef<uint8_t> Buf : Bufs)
1673     Hash.update(Buf);
1674   memcpy(this->HashBuf, Hash.final().data(), 20);
1675 }
1676 
1677 template <class ELFT>
1678 BuildIdHexstring<ELFT>::BuildIdHexstring()
1679     : BuildIdSection<ELFT>(Config->BuildIdVector.size()) {}
1680 
1681 template <class ELFT>
1682 void BuildIdHexstring<ELFT>::writeBuildId(ArrayRef<ArrayRef<uint8_t>> Bufs) {
1683   memcpy(this->HashBuf, Config->BuildIdVector.data(),
1684          Config->BuildIdVector.size());
1685 }
1686 
1687 template <class ELFT>
1688 MipsReginfoOutputSection<ELFT>::MipsReginfoOutputSection()
1689     : OutputSectionBase<ELFT>(".reginfo", SHT_MIPS_REGINFO, SHF_ALLOC) {
1690   this->Header.sh_addralign = 4;
1691   this->Header.sh_entsize = sizeof(Elf_Mips_RegInfo);
1692   this->Header.sh_size = sizeof(Elf_Mips_RegInfo);
1693 }
1694 
1695 template <class ELFT>
1696 void MipsReginfoOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1697   auto *R = reinterpret_cast<Elf_Mips_RegInfo *>(Buf);
1698   R->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset;
1699   R->ri_gprmask = GprMask;
1700 }
1701 
1702 template <class ELFT>
1703 void MipsReginfoOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1704   // Copy input object file's .reginfo gprmask to output.
1705   auto *S = cast<MipsReginfoInputSection<ELFT>>(C);
1706   GprMask |= S->Reginfo->ri_gprmask;
1707   S->OutSec = this;
1708 }
1709 
1710 template <class ELFT>
1711 MipsOptionsOutputSection<ELFT>::MipsOptionsOutputSection()
1712     : OutputSectionBase<ELFT>(".MIPS.options", SHT_MIPS_OPTIONS,
1713                               SHF_ALLOC | SHF_MIPS_NOSTRIP) {
1714   this->Header.sh_addralign = 8;
1715   this->Header.sh_entsize = 1;
1716   this->Header.sh_size = sizeof(Elf_Mips_Options) + sizeof(Elf_Mips_RegInfo);
1717 }
1718 
1719 template <class ELFT>
1720 void MipsOptionsOutputSection<ELFT>::writeTo(uint8_t *Buf) {
1721   auto *Opt = reinterpret_cast<Elf_Mips_Options *>(Buf);
1722   Opt->kind = ODK_REGINFO;
1723   Opt->size = this->Header.sh_size;
1724   Opt->section = 0;
1725   Opt->info = 0;
1726   auto *Reg = reinterpret_cast<Elf_Mips_RegInfo *>(Buf + sizeof(*Opt));
1727   Reg->ri_gp_value = Out<ELFT>::Got->getVA() + MipsGPOffset;
1728   Reg->ri_gprmask = GprMask;
1729 }
1730 
1731 template <class ELFT>
1732 void MipsOptionsOutputSection<ELFT>::addSection(InputSectionBase<ELFT> *C) {
1733   auto *S = cast<MipsOptionsInputSection<ELFT>>(C);
1734   if (S->Reginfo)
1735     GprMask |= S->Reginfo->ri_gprmask;
1736   S->OutSec = this;
1737 }
1738 
1739 template <class ELFT>
1740 std::pair<OutputSectionBase<ELFT> *, bool>
1741 OutputSectionFactory<ELFT>::create(InputSectionBase<ELFT> *C,
1742                                    StringRef OutsecName) {
1743   SectionKey<ELFT::Is64Bits> Key = createKey(C, OutsecName);
1744   OutputSectionBase<ELFT> *&Sec = Map[Key];
1745   if (Sec)
1746     return {Sec, false};
1747 
1748   switch (C->SectionKind) {
1749   case InputSectionBase<ELFT>::Regular:
1750     Sec = new OutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
1751     break;
1752   case InputSectionBase<ELFT>::EHFrame:
1753     return {Out<ELFT>::EhFrame, false};
1754   case InputSectionBase<ELFT>::Merge:
1755     Sec = new MergeOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags,
1756                                        Key.Alignment);
1757     break;
1758   case InputSectionBase<ELFT>::MipsReginfo:
1759     Sec = new MipsReginfoOutputSection<ELFT>();
1760     break;
1761   case InputSectionBase<ELFT>::MipsOptions:
1762     Sec = new MipsOptionsOutputSection<ELFT>();
1763     break;
1764   }
1765   OwningSections.emplace_back(Sec);
1766   return {Sec, true};
1767 }
1768 
1769 template <class ELFT>
1770 OutputSectionBase<ELFT> *OutputSectionFactory<ELFT>::lookup(StringRef Name,
1771                                                             uint32_t Type,
1772                                                             uintX_t Flags) {
1773   return Map.lookup({Name, Type, Flags, 0});
1774 }
1775 
1776 template <class ELFT>
1777 SectionKey<ELFT::Is64Bits>
1778 OutputSectionFactory<ELFT>::createKey(InputSectionBase<ELFT> *C,
1779                                       StringRef OutsecName) {
1780   const Elf_Shdr *H = C->getSectionHdr();
1781   uintX_t Flags = H->sh_flags & ~SHF_GROUP & ~SHF_COMPRESSED;
1782 
1783   // For SHF_MERGE we create different output sections for each alignment.
1784   // This makes each output section simple and keeps a single level mapping from
1785   // input to output.
1786   uintX_t Alignment = 0;
1787   if (isa<MergeInputSection<ELFT>>(C))
1788     Alignment = std::max(H->sh_addralign, H->sh_entsize);
1789 
1790   uint32_t Type = H->sh_type;
1791   return SectionKey<ELFT::Is64Bits>{OutsecName, Type, Flags, Alignment};
1792 }
1793 
1794 template <bool Is64Bits>
1795 typename lld::elf::SectionKey<Is64Bits>
1796 DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::getEmptyKey() {
1797   return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0, 0};
1798 }
1799 
1800 template <bool Is64Bits>
1801 typename lld::elf::SectionKey<Is64Bits>
1802 DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::getTombstoneKey() {
1803   return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0,
1804                               0};
1805 }
1806 
1807 template <bool Is64Bits>
1808 unsigned
1809 DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::getHashValue(const Key &Val) {
1810   return hash_combine(Val.Name, Val.Type, Val.Flags, Val.Alignment);
1811 }
1812 
1813 template <bool Is64Bits>
1814 bool DenseMapInfo<lld::elf::SectionKey<Is64Bits>>::isEqual(const Key &LHS,
1815                                                            const Key &RHS) {
1816   return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
1817          LHS.Type == RHS.Type && LHS.Flags == RHS.Flags &&
1818          LHS.Alignment == RHS.Alignment;
1819 }
1820 
1821 namespace llvm {
1822 template struct DenseMapInfo<SectionKey<true>>;
1823 template struct DenseMapInfo<SectionKey<false>>;
1824 }
1825 
1826 namespace lld {
1827 namespace elf {
1828 template class OutputSectionBase<ELF32LE>;
1829 template class OutputSectionBase<ELF32BE>;
1830 template class OutputSectionBase<ELF64LE>;
1831 template class OutputSectionBase<ELF64BE>;
1832 
1833 template class EhFrameHeader<ELF32LE>;
1834 template class EhFrameHeader<ELF32BE>;
1835 template class EhFrameHeader<ELF64LE>;
1836 template class EhFrameHeader<ELF64BE>;
1837 
1838 template class GotPltSection<ELF32LE>;
1839 template class GotPltSection<ELF32BE>;
1840 template class GotPltSection<ELF64LE>;
1841 template class GotPltSection<ELF64BE>;
1842 
1843 template class GotSection<ELF32LE>;
1844 template class GotSection<ELF32BE>;
1845 template class GotSection<ELF64LE>;
1846 template class GotSection<ELF64BE>;
1847 
1848 template class PltSection<ELF32LE>;
1849 template class PltSection<ELF32BE>;
1850 template class PltSection<ELF64LE>;
1851 template class PltSection<ELF64BE>;
1852 
1853 template class RelocationSection<ELF32LE>;
1854 template class RelocationSection<ELF32BE>;
1855 template class RelocationSection<ELF64LE>;
1856 template class RelocationSection<ELF64BE>;
1857 
1858 template class InterpSection<ELF32LE>;
1859 template class InterpSection<ELF32BE>;
1860 template class InterpSection<ELF64LE>;
1861 template class InterpSection<ELF64BE>;
1862 
1863 template class GnuHashTableSection<ELF32LE>;
1864 template class GnuHashTableSection<ELF32BE>;
1865 template class GnuHashTableSection<ELF64LE>;
1866 template class GnuHashTableSection<ELF64BE>;
1867 
1868 template class HashTableSection<ELF32LE>;
1869 template class HashTableSection<ELF32BE>;
1870 template class HashTableSection<ELF64LE>;
1871 template class HashTableSection<ELF64BE>;
1872 
1873 template class DynamicSection<ELF32LE>;
1874 template class DynamicSection<ELF32BE>;
1875 template class DynamicSection<ELF64LE>;
1876 template class DynamicSection<ELF64BE>;
1877 
1878 template class OutputSection<ELF32LE>;
1879 template class OutputSection<ELF32BE>;
1880 template class OutputSection<ELF64LE>;
1881 template class OutputSection<ELF64BE>;
1882 
1883 template class EhOutputSection<ELF32LE>;
1884 template class EhOutputSection<ELF32BE>;
1885 template class EhOutputSection<ELF64LE>;
1886 template class EhOutputSection<ELF64BE>;
1887 
1888 template class MipsReginfoOutputSection<ELF32LE>;
1889 template class MipsReginfoOutputSection<ELF32BE>;
1890 template class MipsReginfoOutputSection<ELF64LE>;
1891 template class MipsReginfoOutputSection<ELF64BE>;
1892 
1893 template class MipsOptionsOutputSection<ELF32LE>;
1894 template class MipsOptionsOutputSection<ELF32BE>;
1895 template class MipsOptionsOutputSection<ELF64LE>;
1896 template class MipsOptionsOutputSection<ELF64BE>;
1897 
1898 template class MergeOutputSection<ELF32LE>;
1899 template class MergeOutputSection<ELF32BE>;
1900 template class MergeOutputSection<ELF64LE>;
1901 template class MergeOutputSection<ELF64BE>;
1902 
1903 template class StringTableSection<ELF32LE>;
1904 template class StringTableSection<ELF32BE>;
1905 template class StringTableSection<ELF64LE>;
1906 template class StringTableSection<ELF64BE>;
1907 
1908 template class SymbolTableSection<ELF32LE>;
1909 template class SymbolTableSection<ELF32BE>;
1910 template class SymbolTableSection<ELF64LE>;
1911 template class SymbolTableSection<ELF64BE>;
1912 
1913 template class VersionTableSection<ELF32LE>;
1914 template class VersionTableSection<ELF32BE>;
1915 template class VersionTableSection<ELF64LE>;
1916 template class VersionTableSection<ELF64BE>;
1917 
1918 template class VersionNeedSection<ELF32LE>;
1919 template class VersionNeedSection<ELF32BE>;
1920 template class VersionNeedSection<ELF64LE>;
1921 template class VersionNeedSection<ELF64BE>;
1922 
1923 template class VersionDefinitionSection<ELF32LE>;
1924 template class VersionDefinitionSection<ELF32BE>;
1925 template class VersionDefinitionSection<ELF64LE>;
1926 template class VersionDefinitionSection<ELF64BE>;
1927 
1928 template class BuildIdSection<ELF32LE>;
1929 template class BuildIdSection<ELF32BE>;
1930 template class BuildIdSection<ELF64LE>;
1931 template class BuildIdSection<ELF64BE>;
1932 
1933 template class BuildIdFnv1<ELF32LE>;
1934 template class BuildIdFnv1<ELF32BE>;
1935 template class BuildIdFnv1<ELF64LE>;
1936 template class BuildIdFnv1<ELF64BE>;
1937 
1938 template class BuildIdMd5<ELF32LE>;
1939 template class BuildIdMd5<ELF32BE>;
1940 template class BuildIdMd5<ELF64LE>;
1941 template class BuildIdMd5<ELF64BE>;
1942 
1943 template class BuildIdSha1<ELF32LE>;
1944 template class BuildIdSha1<ELF32BE>;
1945 template class BuildIdSha1<ELF64LE>;
1946 template class BuildIdSha1<ELF64BE>;
1947 
1948 template class BuildIdHexstring<ELF32LE>;
1949 template class BuildIdHexstring<ELF32BE>;
1950 template class BuildIdHexstring<ELF64LE>;
1951 template class BuildIdHexstring<ELF64BE>;
1952 
1953 template class OutputSectionFactory<ELF32LE>;
1954 template class OutputSectionFactory<ELF32BE>;
1955 template class OutputSectionFactory<ELF64LE>;
1956 template class OutputSectionFactory<ELF64BE>;
1957 }
1958 }
1959