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