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