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