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 "Memory.h"
15 #include "Strings.h"
16 #include "SymbolTable.h"
17 #include "SyntheticSections.h"
18 #include "Target.h"
19 #include "Threads.h"
20 #include "llvm/Support/Dwarf.h"
21 #include "llvm/Support/MD5.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/SHA1.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 OutputSectionBase::OutputSectionBase(StringRef Name, uint32_t Type,
35                                      uint64_t Flags)
36     : Name(Name) {
37   this->Type = Type;
38   this->Flags = Flags;
39   this->Addralign = 1;
40 }
41 
42 uint32_t OutputSectionBase::getPhdrFlags() const {
43   uint32_t Ret = PF_R;
44   if (Flags & SHF_WRITE)
45     Ret |= PF_W;
46   if (Flags & SHF_EXECINSTR)
47     Ret |= PF_X;
48   return Ret;
49 }
50 
51 template <class ELFT>
52 void OutputSectionBase::writeHeaderTo(typename ELFT::Shdr *Shdr) {
53   Shdr->sh_entsize = Entsize;
54   Shdr->sh_addralign = Addralign;
55   Shdr->sh_type = Type;
56   Shdr->sh_offset = Offset;
57   Shdr->sh_flags = Flags;
58   Shdr->sh_info = Info;
59   Shdr->sh_link = Link;
60   Shdr->sh_addr = Addr;
61   Shdr->sh_size = Size;
62   Shdr->sh_name = ShName;
63 }
64 
65 template <class ELFT> static uint64_t getEntsize(uint32_t Type) {
66   switch (Type) {
67   case SHT_RELA:
68     return sizeof(typename ELFT::Rela);
69   case SHT_REL:
70     return sizeof(typename ELFT::Rel);
71   case SHT_MIPS_REGINFO:
72     return sizeof(Elf_Mips_RegInfo<ELFT>);
73   case SHT_MIPS_OPTIONS:
74     return sizeof(Elf_Mips_Options<ELFT>) + sizeof(Elf_Mips_RegInfo<ELFT>);
75   case SHT_MIPS_ABIFLAGS:
76     return sizeof(Elf_Mips_ABIFlags<ELFT>);
77   default:
78     return 0;
79   }
80 }
81 
82 template <class ELFT>
83 OutputSection<ELFT>::OutputSection(StringRef Name, uint32_t Type, uintX_t Flags)
84     : OutputSectionBase(Name, Type, Flags) {
85   this->Entsize = getEntsize<ELFT>(Type);
86 }
87 
88 template <typename ELFT>
89 static bool compareByFilePosition(InputSection<ELFT> *A,
90                                   InputSection<ELFT> *B) {
91   // Synthetic doesn't have link order dependecy, stable_sort will keep it last
92   if (A->kind() == InputSectionData::Synthetic ||
93       B->kind() == InputSectionData::Synthetic)
94     return false;
95   auto *LA = cast<InputSection<ELFT>>(A->getLinkOrderDep());
96   auto *LB = cast<InputSection<ELFT>>(B->getLinkOrderDep());
97   OutputSectionBase *AOut = LA->OutSec;
98   OutputSectionBase *BOut = LB->OutSec;
99   if (AOut != BOut)
100     return AOut->SectionIndex < BOut->SectionIndex;
101   return LA->OutSecOff < LB->OutSecOff;
102 }
103 
104 template <class ELFT> void OutputSection<ELFT>::finalize() {
105   if ((this->Flags & SHF_LINK_ORDER) && !this->Sections.empty()) {
106     std::sort(Sections.begin(), Sections.end(), compareByFilePosition<ELFT>);
107     Size = 0;
108     assignOffsets();
109 
110     // We must preserve the link order dependency of sections with the
111     // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
112     // need to translate the InputSection sh_link to the OutputSection sh_link,
113     // all InputSections in the OutputSection have the same dependency.
114     if (auto *D = this->Sections.front()->getLinkOrderDep())
115       this->Link = D->OutSec->SectionIndex;
116   }
117 
118   uint32_t Type = this->Type;
119   if (!Config->Relocatable || (Type != SHT_RELA && Type != SHT_REL))
120     return;
121 
122   this->Link = In<ELFT>::SymTab->OutSec->SectionIndex;
123   // sh_info for SHT_REL[A] sections should contain the section header index of
124   // the section to which the relocation applies.
125   InputSectionBase<ELFT> *S = Sections[0]->getRelocatedSection();
126   this->Info = S->OutSec->SectionIndex;
127 }
128 
129 template <class ELFT>
130 void OutputSection<ELFT>::addSection(InputSectionData *C) {
131   assert(C->Live);
132   auto *S = cast<InputSection<ELFT>>(C);
133   Sections.push_back(S);
134   S->OutSec = this;
135   this->updateAlignment(S->Alignment);
136   // Keep sh_entsize value of the input section to be able to perform merging
137   // later during a final linking using the generated relocatable object.
138   if (Config->Relocatable && (S->Flags & SHF_MERGE))
139     this->Entsize = S->Entsize;
140 }
141 
142 template <class ELFT>
143 void OutputSection<ELFT>::forEachInputSection(
144     std::function<void(InputSectionData *)> F) {
145   for (InputSection<ELFT> *S : Sections)
146     F(S);
147 }
148 
149 // This function is called after we sort input sections
150 // and scan relocations to setup sections' offsets.
151 template <class ELFT> void OutputSection<ELFT>::assignOffsets() {
152   uintX_t Off = this->Size;
153   for (InputSection<ELFT> *S : Sections) {
154     Off = alignTo(Off, S->Alignment);
155     S->OutSecOff = Off;
156     Off += S->getSize();
157   }
158   this->Size = Off;
159 }
160 
161 template <class ELFT>
162 void OutputSection<ELFT>::sort(
163     std::function<int(InputSection<ELFT> *S)> Order) {
164   typedef std::pair<unsigned, InputSection<ELFT> *> Pair;
165   auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
166 
167   std::vector<Pair> V;
168   for (InputSection<ELFT> *S : Sections)
169     V.push_back({Order(S), S});
170   std::stable_sort(V.begin(), V.end(), Comp);
171   Sections.clear();
172   for (Pair &P : V)
173     Sections.push_back(P.second);
174 }
175 
176 // Sorts input sections by section name suffixes, so that .foo.N comes
177 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
178 // We want to keep the original order if the priorities are the same
179 // because the compiler keeps the original initialization order in a
180 // translation unit and we need to respect that.
181 // For more detail, read the section of the GCC's manual about init_priority.
182 template <class ELFT> void OutputSection<ELFT>::sortInitFini() {
183   // Sort sections by priority.
184   sort([](InputSection<ELFT> *S) { return getPriority(S->Name); });
185 }
186 
187 // Returns true if S matches /Filename.?\.o$/.
188 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
189   if (!S.endswith(".o"))
190     return false;
191   S = S.drop_back(2);
192   if (S.endswith(Filename))
193     return true;
194   return !S.empty() && S.drop_back().endswith(Filename);
195 }
196 
197 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
198 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
199 
200 // .ctors and .dtors are sorted by this priority from highest to lowest.
201 //
202 //  1. The section was contained in crtbegin (crtbegin contains
203 //     some sentinel value in its .ctors and .dtors so that the runtime
204 //     can find the beginning of the sections.)
205 //
206 //  2. The section has an optional priority value in the form of ".ctors.N"
207 //     or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
208 //     they are compared as string rather than number.
209 //
210 //  3. The section is just ".ctors" or ".dtors".
211 //
212 //  4. The section was contained in crtend, which contains an end marker.
213 //
214 // In an ideal world, we don't need this function because .init_array and
215 // .ctors are duplicate features (and .init_array is newer.) However, there
216 // are too many real-world use cases of .ctors, so we had no choice to
217 // support that with this rather ad-hoc semantics.
218 template <class ELFT>
219 static bool compCtors(const InputSection<ELFT> *A,
220                       const InputSection<ELFT> *B) {
221   bool BeginA = isCrtbegin(A->getFile()->getName());
222   bool BeginB = isCrtbegin(B->getFile()->getName());
223   if (BeginA != BeginB)
224     return BeginA;
225   bool EndA = isCrtend(A->getFile()->getName());
226   bool EndB = isCrtend(B->getFile()->getName());
227   if (EndA != EndB)
228     return EndB;
229   StringRef X = A->Name;
230   StringRef Y = B->Name;
231   assert(X.startswith(".ctors") || X.startswith(".dtors"));
232   assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
233   X = X.substr(6);
234   Y = Y.substr(6);
235   if (X.empty() && Y.empty())
236     return false;
237   return X < Y;
238 }
239 
240 // Sorts input sections by the special rules for .ctors and .dtors.
241 // Unfortunately, the rules are different from the one for .{init,fini}_array.
242 // Read the comment above.
243 template <class ELFT> void OutputSection<ELFT>::sortCtorsDtors() {
244   std::stable_sort(Sections.begin(), Sections.end(), compCtors<ELFT>);
245 }
246 
247 // Fill [Buf, Buf + Size) with Filler. Filler is written in big
248 // endian order. This is used for linker script "=fillexp" command.
249 void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
250   uint8_t V[4];
251   write32be(V, Filler);
252   size_t I = 0;
253   for (; I + 4 < Size; I += 4)
254     memcpy(Buf + I, V, 4);
255   memcpy(Buf + I, V, Size - I);
256 }
257 
258 template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
259   Loc = Buf;
260   if (uint32_t Filler = Script<ELFT>::X->getFiller(this->Name))
261     fill(Buf, this->Size, Filler);
262 
263   auto Fn = [=](InputSection<ELFT> *IS) { IS->writeTo(Buf); };
264   forEach(Sections.begin(), Sections.end(), Fn);
265 
266   // Linker scripts may have BYTE()-family commands with which you
267   // can write arbitrary bytes to the output. Process them if any.
268   Script<ELFT>::X->writeDataBytes(this->Name, Buf);
269 }
270 
271 template <class ELFT>
272 EhOutputSection<ELFT>::EhOutputSection()
273     : OutputSectionBase(".eh_frame", SHT_PROGBITS, SHF_ALLOC) {}
274 
275 template <class ELFT>
276 void EhOutputSection<ELFT>::forEachInputSection(
277     std::function<void(InputSectionData *)> F) {
278   for (EhInputSection<ELFT> *S : Sections)
279     F(S);
280 }
281 
282 // Search for an existing CIE record or create a new one.
283 // CIE records from input object files are uniquified by their contents
284 // and where their relocations point to.
285 template <class ELFT>
286 template <class RelTy>
287 CieRecord *EhOutputSection<ELFT>::addCie(EhSectionPiece &Piece,
288                                          ArrayRef<RelTy> Rels) {
289   auto *Sec = cast<EhInputSection<ELFT>>(Piece.ID);
290   const endianness E = ELFT::TargetEndianness;
291   if (read32<E>(Piece.data().data() + 4) != 0)
292     fatal(toString(Sec) + ": CIE expected at beginning of .eh_frame");
293 
294   SymbolBody *Personality = nullptr;
295   unsigned FirstRelI = Piece.FirstRelocation;
296   if (FirstRelI != (unsigned)-1)
297     Personality = &Sec->getFile()->getRelocTargetSym(Rels[FirstRelI]);
298 
299   // Search for an existing CIE by CIE contents/relocation target pair.
300   CieRecord *Cie = &CieMap[{Piece.data(), Personality}];
301 
302   // If not found, create a new one.
303   if (Cie->Piece == nullptr) {
304     Cie->Piece = &Piece;
305     Cies.push_back(Cie);
306   }
307   return Cie;
308 }
309 
310 // There is one FDE per function. Returns true if a given FDE
311 // points to a live function.
312 template <class ELFT>
313 template <class RelTy>
314 bool EhOutputSection<ELFT>::isFdeLive(EhSectionPiece &Piece,
315                                       ArrayRef<RelTy> Rels) {
316   auto *Sec = cast<EhInputSection<ELFT>>(Piece.ID);
317   unsigned FirstRelI = Piece.FirstRelocation;
318   if (FirstRelI == (unsigned)-1)
319     fatal(toString(Sec) + ": FDE doesn't reference another section");
320   const RelTy &Rel = Rels[FirstRelI];
321   SymbolBody &B = Sec->getFile()->getRelocTargetSym(Rel);
322   auto *D = dyn_cast<DefinedRegular<ELFT>>(&B);
323   if (!D || !D->Section)
324     return false;
325   InputSectionBase<ELFT> *Target = D->Section->Repl;
326   return Target && Target->Live;
327 }
328 
329 // .eh_frame is a sequence of CIE or FDE records. In general, there
330 // is one CIE record per input object file which is followed by
331 // a list of FDEs. This function searches an existing CIE or create a new
332 // one and associates FDEs to the CIE.
333 template <class ELFT>
334 template <class RelTy>
335 void EhOutputSection<ELFT>::addSectionAux(EhInputSection<ELFT> *Sec,
336                                           ArrayRef<RelTy> Rels) {
337   const endianness E = ELFT::TargetEndianness;
338 
339   DenseMap<size_t, CieRecord *> OffsetToCie;
340   for (EhSectionPiece &Piece : Sec->Pieces) {
341     // The empty record is the end marker.
342     if (Piece.size() == 4)
343       return;
344 
345     size_t Offset = Piece.InputOff;
346     uint32_t ID = read32<E>(Piece.data().data() + 4);
347     if (ID == 0) {
348       OffsetToCie[Offset] = addCie(Piece, Rels);
349       continue;
350     }
351 
352     uint32_t CieOffset = Offset + 4 - ID;
353     CieRecord *Cie = OffsetToCie[CieOffset];
354     if (!Cie)
355       fatal(toString(Sec) + ": invalid CIE reference");
356 
357     if (!isFdeLive(Piece, Rels))
358       continue;
359     Cie->FdePieces.push_back(&Piece);
360     NumFdes++;
361   }
362 }
363 
364 template <class ELFT>
365 void EhOutputSection<ELFT>::addSection(InputSectionData *C) {
366   auto *Sec = cast<EhInputSection<ELFT>>(C);
367   Sec->OutSec = this;
368   this->updateAlignment(Sec->Alignment);
369   Sections.push_back(Sec);
370 
371   // .eh_frame is a sequence of CIE or FDE records. This function
372   // splits it into pieces so that we can call
373   // SplitInputSection::getSectionPiece on the section.
374   Sec->split();
375   if (Sec->Pieces.empty())
376     return;
377 
378   if (Sec->NumRelocations) {
379     if (Sec->AreRelocsRela)
380       addSectionAux(Sec, Sec->relas());
381     else
382       addSectionAux(Sec, Sec->rels());
383     return;
384   }
385   addSectionAux(Sec, makeArrayRef<Elf_Rela>(nullptr, nullptr));
386 }
387 
388 template <class ELFT>
389 static void writeCieFde(uint8_t *Buf, ArrayRef<uint8_t> D) {
390   memcpy(Buf, D.data(), D.size());
391 
392   // Fix the size field. -4 since size does not include the size field itself.
393   const endianness E = ELFT::TargetEndianness;
394   write32<E>(Buf, alignTo(D.size(), sizeof(typename ELFT::uint)) - 4);
395 }
396 
397 template <class ELFT> void EhOutputSection<ELFT>::finalize() {
398   if (this->Size)
399     return; // Already finalized.
400 
401   size_t Off = 0;
402   for (CieRecord *Cie : Cies) {
403     Cie->Piece->OutputOff = Off;
404     Off += alignTo(Cie->Piece->size(), sizeof(uintX_t));
405 
406     for (EhSectionPiece *Fde : Cie->FdePieces) {
407       Fde->OutputOff = Off;
408       Off += alignTo(Fde->size(), sizeof(uintX_t));
409     }
410   }
411   this->Size = Off;
412 }
413 
414 template <class ELFT> static uint64_t readFdeAddr(uint8_t *Buf, int Size) {
415   const endianness E = ELFT::TargetEndianness;
416   switch (Size) {
417   case DW_EH_PE_udata2:
418     return read16<E>(Buf);
419   case DW_EH_PE_udata4:
420     return read32<E>(Buf);
421   case DW_EH_PE_udata8:
422     return read64<E>(Buf);
423   case DW_EH_PE_absptr:
424     if (ELFT::Is64Bits)
425       return read64<E>(Buf);
426     return read32<E>(Buf);
427   }
428   fatal("unknown FDE size encoding");
429 }
430 
431 // Returns the VA to which a given FDE (on a mmap'ed buffer) is applied to.
432 // We need it to create .eh_frame_hdr section.
433 template <class ELFT>
434 typename ELFT::uint EhOutputSection<ELFT>::getFdePc(uint8_t *Buf, size_t FdeOff,
435                                                     uint8_t Enc) {
436   // The starting address to which this FDE applies is
437   // stored at FDE + 8 byte.
438   size_t Off = FdeOff + 8;
439   uint64_t Addr = readFdeAddr<ELFT>(Buf + Off, Enc & 0x7);
440   if ((Enc & 0x70) == DW_EH_PE_absptr)
441     return Addr;
442   if ((Enc & 0x70) == DW_EH_PE_pcrel)
443     return Addr + this->Addr + Off;
444   fatal("unknown FDE size relative encoding");
445 }
446 
447 template <class ELFT> void EhOutputSection<ELFT>::writeTo(uint8_t *Buf) {
448   const endianness E = ELFT::TargetEndianness;
449   for (CieRecord *Cie : Cies) {
450     size_t CieOffset = Cie->Piece->OutputOff;
451     writeCieFde<ELFT>(Buf + CieOffset, Cie->Piece->data());
452 
453     for (EhSectionPiece *Fde : Cie->FdePieces) {
454       size_t Off = Fde->OutputOff;
455       writeCieFde<ELFT>(Buf + Off, Fde->data());
456 
457       // FDE's second word should have the offset to an associated CIE.
458       // Write it.
459       write32<E>(Buf + Off + 4, Off + 4 - CieOffset);
460     }
461   }
462 
463   for (EhInputSection<ELFT> *S : Sections)
464     S->relocate(Buf, nullptr);
465 
466   // Construct .eh_frame_hdr. .eh_frame_hdr is a binary search table
467   // to get a FDE from an address to which FDE is applied. So here
468   // we obtain two addresses and pass them to EhFrameHdr object.
469   if (In<ELFT>::EhFrameHdr) {
470     for (CieRecord *Cie : Cies) {
471       uint8_t Enc = getFdeEncoding<ELFT>(Cie->Piece);
472       for (SectionPiece *Fde : Cie->FdePieces) {
473         uintX_t Pc = getFdePc(Buf, Fde->OutputOff, Enc);
474         uintX_t FdeVA = this->Addr + Fde->OutputOff;
475         In<ELFT>::EhFrameHdr->addFde(Pc, FdeVA);
476       }
477     }
478   }
479 }
480 
481 template <class ELFT>
482 MergeOutputSection<ELFT>::MergeOutputSection(StringRef Name, uint32_t Type,
483                                              uintX_t Flags, uintX_t Alignment)
484     : OutputSectionBase(Name, Type, Flags),
485       Builder(StringTableBuilder::RAW, Alignment) {}
486 
487 template <class ELFT> void MergeOutputSection<ELFT>::writeTo(uint8_t *Buf) {
488   Builder.write(Buf);
489 }
490 
491 template <class ELFT>
492 void MergeOutputSection<ELFT>::addSection(InputSectionData *C) {
493   auto *Sec = cast<MergeInputSection<ELFT>>(C);
494   Sec->OutSec = this;
495   this->updateAlignment(Sec->Alignment);
496   this->Entsize = Sec->Entsize;
497   Sections.push_back(Sec);
498 }
499 
500 template <class ELFT> bool MergeOutputSection<ELFT>::shouldTailMerge() const {
501   return (this->Flags & SHF_STRINGS) && Config->Optimize >= 2;
502 }
503 
504 template <class ELFT> void MergeOutputSection<ELFT>::finalizeTailMerge() {
505   // Add all string pieces to the string table builder to create section
506   // contents.
507   for (MergeInputSection<ELFT> *Sec : Sections)
508     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
509       if (Sec->Pieces[I].Live)
510         Builder.add(Sec->getData(I));
511 
512   // Fix the string table content. After this, the contents will never change.
513   Builder.finalize();
514   this->Size = Builder.getSize();
515 
516   // finalize() fixed tail-optimized strings, so we can now get
517   // offsets of strings. Get an offset for each string and save it
518   // to a corresponding StringPiece for easy access.
519   for (MergeInputSection<ELFT> *Sec : Sections)
520     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
521       if (Sec->Pieces[I].Live)
522         Sec->Pieces[I].OutputOff = Builder.getOffset(Sec->getData(I));
523 }
524 
525 template <class ELFT> void MergeOutputSection<ELFT>::finalizeNoTailMerge() {
526   // Add all string pieces to the string table builder to create section
527   // contents. Because we are not tail-optimizing, offsets of strings are
528   // fixed when they are added to the builder (string table builder contains
529   // a hash table from strings to offsets).
530   for (MergeInputSection<ELFT> *Sec : Sections)
531     for (size_t I = 0, E = Sec->Pieces.size(); I != E; ++I)
532       if (Sec->Pieces[I].Live)
533         Sec->Pieces[I].OutputOff = Builder.add(Sec->getData(I));
534 
535   Builder.finalizeInOrder();
536   this->Size = Builder.getSize();
537 }
538 
539 template <class ELFT> void MergeOutputSection<ELFT>::finalize() {
540   if (shouldTailMerge())
541     finalizeTailMerge();
542   else
543     finalizeNoTailMerge();
544 }
545 
546 template <class ELFT>
547 static typename ELFT::uint getOutFlags(InputSectionBase<ELFT> *S) {
548   return S->Flags & ~SHF_GROUP & ~SHF_COMPRESSED;
549 }
550 
551 namespace llvm {
552 template <> struct DenseMapInfo<lld::elf::SectionKey> {
553   static lld::elf::SectionKey getEmptyKey();
554   static lld::elf::SectionKey getTombstoneKey();
555   static unsigned getHashValue(const lld::elf::SectionKey &Val);
556   static bool isEqual(const lld::elf::SectionKey &LHS,
557                       const lld::elf::SectionKey &RHS);
558 };
559 }
560 
561 template <class ELFT>
562 static SectionKey createKey(InputSectionBase<ELFT> *C, StringRef OutsecName) {
563   //  The ELF spec just says
564   // ----------------------------------------------------------------
565   // In the first phase, input sections that match in name, type and
566   // attribute flags should be concatenated into single sections.
567   // ----------------------------------------------------------------
568   //
569   // However, it is clear that at least some flags have to be ignored for
570   // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
571   // ignored. We should not have two output .text sections just because one was
572   // in a group and another was not for example.
573   //
574   // It also seems that that wording was a late addition and didn't get the
575   // necessary scrutiny.
576   //
577   // Merging sections with different flags is expected by some users. One
578   // reason is that if one file has
579   //
580   // int *const bar __attribute__((section(".foo"))) = (int *)0;
581   //
582   // gcc with -fPIC will produce a read only .foo section. But if another
583   // file has
584   //
585   // int zed;
586   // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
587   //
588   // gcc with -fPIC will produce a read write section.
589   //
590   // Last but not least, when using linker script the merge rules are forced by
591   // the script. Unfortunately, linker scripts are name based. This means that
592   // expressions like *(.foo*) can refer to multiple input sections with
593   // different flags. We cannot put them in different output sections or we
594   // would produce wrong results for
595   //
596   // start = .; *(.foo.*) end = .; *(.bar)
597   //
598   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
599   // another. The problem is that there is no way to layout those output
600   // sections such that the .foo sections are the only thing between the start
601   // and end symbols.
602   //
603   // Given the above issues, we instead merge sections by name and error on
604   // incompatible types and flags.
605   //
606   // The exception being SHF_MERGE, where we create different output sections
607   // for each alignment. This makes each output section simple. In case of
608   // relocatable object generation we do not try to perform merging and treat
609   // SHF_MERGE sections as regular ones, but also create different output
610   // sections for them to allow merging at final linking stage.
611   //
612   // Fortunately, creating symbols in the middle of a merge section is not
613   // supported by bfd or gold, so the SHF_MERGE exception should not cause
614   // problems with most linker scripts.
615 
616   typedef typename ELFT::uint uintX_t;
617   uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
618 
619   uintX_t Alignment = 0;
620   if (isa<MergeInputSection<ELFT>>(C) ||
621       (Config->Relocatable && (C->Flags & SHF_MERGE)))
622     Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
623 
624   return SectionKey{OutsecName, Flags, Alignment};
625 }
626 
627 template <class ELFT> OutputSectionFactory<ELFT>::OutputSectionFactory() {}
628 
629 template <class ELFT> OutputSectionFactory<ELFT>::~OutputSectionFactory() {}
630 
631 template <class ELFT>
632 std::pair<OutputSectionBase *, bool>
633 OutputSectionFactory<ELFT>::create(InputSectionBase<ELFT> *C,
634                                    StringRef OutsecName) {
635   SectionKey Key = createKey(C, OutsecName);
636   return create(Key, C);
637 }
638 
639 static uint64_t getIncompatibleFlags(uint64_t Flags) {
640   return Flags & (SHF_ALLOC | SHF_TLS);
641 }
642 
643 template <class ELFT>
644 std::pair<OutputSectionBase *, bool>
645 OutputSectionFactory<ELFT>::create(const SectionKey &Key,
646                                    InputSectionBase<ELFT> *C) {
647   uintX_t Flags = getOutFlags(C);
648   OutputSectionBase *&Sec = Map[Key];
649   if (Sec) {
650     if (getIncompatibleFlags(Sec->Flags) != getIncompatibleFlags(C->Flags))
651       error("Section has flags incompatible with others with the same name " +
652             toString(C));
653     // Convert notbits to progbits if they are mixed. This happens is some
654     // linker scripts.
655     if (Sec->Type == SHT_NOBITS && C->Type == SHT_PROGBITS)
656       Sec->Type = SHT_PROGBITS;
657     if (Sec->Type != C->Type &&
658         !(Sec->Type == SHT_PROGBITS && C->Type == SHT_NOBITS))
659       error("Section has different type from others with the same name " +
660             toString(C));
661     Sec->Flags |= Flags;
662     return {Sec, false};
663   }
664 
665   uint32_t Type = C->Type;
666   switch (C->kind()) {
667   case InputSectionBase<ELFT>::Regular:
668   case InputSectionBase<ELFT>::Synthetic:
669     Sec = make<OutputSection<ELFT>>(Key.Name, Type, Flags);
670     break;
671   case InputSectionBase<ELFT>::EHFrame:
672     return {Out<ELFT>::EhFrame, false};
673   case InputSectionBase<ELFT>::Merge:
674     Sec = make<MergeOutputSection<ELFT>>(Key.Name, Type, Flags, Key.Alignment);
675     break;
676   }
677   return {Sec, true};
678 }
679 
680 SectionKey DenseMapInfo<SectionKey>::getEmptyKey() {
681   return SectionKey{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
682 }
683 
684 SectionKey DenseMapInfo<SectionKey>::getTombstoneKey() {
685   return SectionKey{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0};
686 }
687 
688 unsigned DenseMapInfo<SectionKey>::getHashValue(const SectionKey &Val) {
689   return hash_combine(Val.Name, Val.Flags, Val.Alignment);
690 }
691 
692 bool DenseMapInfo<SectionKey>::isEqual(const SectionKey &LHS,
693                                        const SectionKey &RHS) {
694   return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
695          LHS.Flags == RHS.Flags && LHS.Alignment == RHS.Alignment;
696 }
697 
698 namespace lld {
699 namespace elf {
700 
701 template void OutputSectionBase::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
702 template void OutputSectionBase::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
703 template void OutputSectionBase::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
704 template void OutputSectionBase::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
705 
706 template class OutputSection<ELF32LE>;
707 template class OutputSection<ELF32BE>;
708 template class OutputSection<ELF64LE>;
709 template class OutputSection<ELF64BE>;
710 
711 template class EhOutputSection<ELF32LE>;
712 template class EhOutputSection<ELF32BE>;
713 template class EhOutputSection<ELF64LE>;
714 template class EhOutputSection<ELF64BE>;
715 
716 template class MergeOutputSection<ELF32LE>;
717 template class MergeOutputSection<ELF32BE>;
718 template class MergeOutputSection<ELF64LE>;
719 template class MergeOutputSection<ELF64BE>;
720 
721 template class OutputSectionFactory<ELF32LE>;
722 template class OutputSectionFactory<ELF32BE>;
723 template class OutputSectionFactory<ELF64LE>;
724 template class OutputSectionFactory<ELF64BE>;
725 }
726 }
727