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