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