]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/OutputSections.cpp
Merge ^/head r319251 through r319479.
[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 "LinkerScript.h"
13 #include "Memory.h"
14 #include "Strings.h"
15 #include "SymbolTable.h"
16 #include "SyntheticSections.h"
17 #include "Target.h"
18 #include "Threads.h"
19 #include "llvm/Support/Dwarf.h"
20 #include "llvm/Support/MD5.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/SHA1.h"
23
24 using namespace llvm;
25 using namespace llvm::dwarf;
26 using namespace llvm::object;
27 using namespace llvm::support::endian;
28 using namespace llvm::ELF;
29
30 using namespace lld;
31 using namespace lld::elf;
32
33 uint8_t Out::First;
34 OutputSection *Out::Opd;
35 uint8_t *Out::OpdBuf;
36 PhdrEntry *Out::TlsPhdr;
37 OutputSection *Out::DebugInfo;
38 OutputSection *Out::ElfHeader;
39 OutputSection *Out::ProgramHeaders;
40 OutputSection *Out::PreinitArray;
41 OutputSection *Out::InitArray;
42 OutputSection *Out::FiniArray;
43
44 uint32_t OutputSection::getPhdrFlags() const {
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 OutputSection::writeHeaderTo(typename ELFT::Shdr *Shdr) {
55   Shdr->sh_entsize = Entsize;
56   Shdr->sh_addralign = Alignment;
57   Shdr->sh_type = Type;
58   Shdr->sh_offset = Offset;
59   Shdr->sh_flags = Flags;
60   Shdr->sh_info = Info;
61   Shdr->sh_link = Link;
62   Shdr->sh_addr = Addr;
63   Shdr->sh_size = Size;
64   Shdr->sh_name = ShName;
65 }
66
67 OutputSection::OutputSection(StringRef Name, uint32_t Type, uint64_t Flags)
68     : SectionBase(Output, Name, Flags, /*Entsize*/ 0, /*Alignment*/ 1, Type,
69                   /*Info*/ 0,
70                   /*Link*/ 0),
71       SectionIndex(INT_MAX) {}
72
73 static bool compareByFilePosition(InputSection *A, InputSection *B) {
74   // Synthetic doesn't have link order dependecy, stable_sort will keep it last
75   if (A->kind() == InputSectionBase::Synthetic ||
76       B->kind() == InputSectionBase::Synthetic)
77     return false;
78   InputSection *LA = A->getLinkOrderDep();
79   InputSection *LB = B->getLinkOrderDep();
80   OutputSection *AOut = LA->getParent();
81   OutputSection *BOut = LB->getParent();
82   if (AOut != BOut)
83     return AOut->SectionIndex < BOut->SectionIndex;
84   return LA->OutSecOff < LB->OutSecOff;
85 }
86
87 template <class ELFT> static void finalizeShtGroup(OutputSection *Sec) {
88   // sh_link field for SHT_GROUP sections should contain the section index of
89   // the symbol table.
90   Sec->Link = InX::SymTab->getParent()->SectionIndex;
91
92   // sh_info then contain index of an entry in symbol table section which
93   // provides signature of the section group.
94   elf::ObjectFile<ELFT> *Obj = Sec->Sections[0]->getFile<ELFT>();
95   assert(Config->Relocatable && Sec->Sections.size() == 1);
96   ArrayRef<SymbolBody *> Symbols = Obj->getSymbols();
97   Sec->Info = InX::SymTab->getSymbolIndex(Symbols[Sec->Sections[0]->Info - 1]);
98 }
99
100 template <class ELFT> void OutputSection::finalize() {
101   if ((this->Flags & SHF_LINK_ORDER) && !this->Sections.empty()) {
102     std::sort(Sections.begin(), Sections.end(), compareByFilePosition);
103     assignOffsets();
104
105     // We must preserve the link order dependency of sections with the
106     // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
107     // need to translate the InputSection sh_link to the OutputSection sh_link,
108     // all InputSections in the OutputSection have the same dependency.
109     if (auto *D = this->Sections.front()->getLinkOrderDep())
110       this->Link = D->getParent()->SectionIndex;
111   }
112
113   uint32_t Type = this->Type;
114   if (Type == SHT_GROUP) {
115     finalizeShtGroup<ELFT>(this);
116     return;
117   }
118
119   if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
120     return;
121
122   InputSection *First = Sections[0];
123   if (isa<SyntheticSection>(First))
124     return;
125
126   this->Link = InX::SymTab->getParent()->SectionIndex;
127   // sh_info for SHT_REL[A] sections should contain the section header index of
128   // the section to which the relocation applies.
129   InputSectionBase *S = First->getRelocatedSection();
130   Info = S->getOutputSection()->SectionIndex;
131 }
132
133 static uint64_t updateOffset(uint64_t Off, InputSection *S) {
134   Off = alignTo(Off, S->Alignment);
135   S->OutSecOff = Off;
136   return Off + S->getSize();
137 }
138
139 void OutputSection::addSection(InputSection *S) {
140   assert(S->Live);
141   Sections.push_back(S);
142   S->Parent = this;
143   this->updateAlignment(S->Alignment);
144
145   // The actual offsets will be computed by assignAddresses. For now, use
146   // crude approximation so that it is at least easy for other code to know the
147   // section order. It is also used to calculate the output section size early
148   // for compressed debug sections.
149   this->Size = updateOffset(Size, S);
150
151   // If this section contains a table of fixed-size entries, sh_entsize
152   // holds the element size. Consequently, if this contains two or more
153   // input sections, all of them must have the same sh_entsize. However,
154   // you can put different types of input sections into one output
155   // sectin by using linker scripts. I don't know what to do here.
156   // Probably we sholuld handle that as an error. But for now we just
157   // pick the largest sh_entsize.
158   this->Entsize = std::max(this->Entsize, S->Entsize);
159 }
160
161 // This function is called after we sort input sections
162 // and scan relocations to setup sections' offsets.
163 void OutputSection::assignOffsets() {
164   uint64_t Off = 0;
165   for (InputSection *S : Sections)
166     Off = updateOffset(Off, S);
167   this->Size = Off;
168 }
169
170 void OutputSection::sort(std::function<int(InputSectionBase *S)> Order) {
171   typedef std::pair<unsigned, InputSection *> Pair;
172   auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
173
174   std::vector<Pair> V;
175   for (InputSection *S : Sections)
176     V.push_back({Order(S), S});
177   std::stable_sort(V.begin(), V.end(), Comp);
178   Sections.clear();
179   for (Pair &P : V)
180     Sections.push_back(P.second);
181 }
182
183 // Sorts input sections by section name suffixes, so that .foo.N comes
184 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
185 // We want to keep the original order if the priorities are the same
186 // because the compiler keeps the original initialization order in a
187 // translation unit and we need to respect that.
188 // For more detail, read the section of the GCC's manual about init_priority.
189 void OutputSection::sortInitFini() {
190   // Sort sections by priority.
191   sort([](InputSectionBase *S) { return getPriority(S->Name); });
192 }
193
194 // Returns true if S matches /Filename.?\.o$/.
195 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
196   if (!S.endswith(".o"))
197     return false;
198   S = S.drop_back(2);
199   if (S.endswith(Filename))
200     return true;
201   return !S.empty() && S.drop_back().endswith(Filename);
202 }
203
204 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
205 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
206
207 // .ctors and .dtors are sorted by this priority from highest to lowest.
208 //
209 //  1. The section was contained in crtbegin (crtbegin contains
210 //     some sentinel value in its .ctors and .dtors so that the runtime
211 //     can find the beginning of the sections.)
212 //
213 //  2. The section has an optional priority value in the form of ".ctors.N"
214 //     or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
215 //     they are compared as string rather than number.
216 //
217 //  3. The section is just ".ctors" or ".dtors".
218 //
219 //  4. The section was contained in crtend, which contains an end marker.
220 //
221 // In an ideal world, we don't need this function because .init_array and
222 // .ctors are duplicate features (and .init_array is newer.) However, there
223 // are too many real-world use cases of .ctors, so we had no choice to
224 // support that with this rather ad-hoc semantics.
225 static bool compCtors(const InputSection *A, const InputSection *B) {
226   bool BeginA = isCrtbegin(A->File->getName());
227   bool BeginB = isCrtbegin(B->File->getName());
228   if (BeginA != BeginB)
229     return BeginA;
230   bool EndA = isCrtend(A->File->getName());
231   bool EndB = isCrtend(B->File->getName());
232   if (EndA != EndB)
233     return EndB;
234   StringRef X = A->Name;
235   StringRef Y = B->Name;
236   assert(X.startswith(".ctors") || X.startswith(".dtors"));
237   assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
238   X = X.substr(6);
239   Y = Y.substr(6);
240   if (X.empty() && Y.empty())
241     return false;
242   return X < Y;
243 }
244
245 // Sorts input sections by the special rules for .ctors and .dtors.
246 // Unfortunately, the rules are different from the one for .{init,fini}_array.
247 // Read the comment above.
248 void OutputSection::sortCtorsDtors() {
249   std::stable_sort(Sections.begin(), Sections.end(), compCtors);
250 }
251
252 static SectionKey createKey(InputSectionBase *C, StringRef OutsecName) {
253   //  The ELF spec just says
254   // ----------------------------------------------------------------
255   // In the first phase, input sections that match in name, type and
256   // attribute flags should be concatenated into single sections.
257   // ----------------------------------------------------------------
258   //
259   // However, it is clear that at least some flags have to be ignored for
260   // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
261   // ignored. We should not have two output .text sections just because one was
262   // in a group and another was not for example.
263   //
264   // It also seems that that wording was a late addition and didn't get the
265   // necessary scrutiny.
266   //
267   // Merging sections with different flags is expected by some users. One
268   // reason is that if one file has
269   //
270   // int *const bar __attribute__((section(".foo"))) = (int *)0;
271   //
272   // gcc with -fPIC will produce a read only .foo section. But if another
273   // file has
274   //
275   // int zed;
276   // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
277   //
278   // gcc with -fPIC will produce a read write section.
279   //
280   // Last but not least, when using linker script the merge rules are forced by
281   // the script. Unfortunately, linker scripts are name based. This means that
282   // expressions like *(.foo*) can refer to multiple input sections with
283   // different flags. We cannot put them in different output sections or we
284   // would produce wrong results for
285   //
286   // start = .; *(.foo.*) end = .; *(.bar)
287   //
288   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
289   // another. The problem is that there is no way to layout those output
290   // sections such that the .foo sections are the only thing between the start
291   // and end symbols.
292   //
293   // Given the above issues, we instead merge sections by name and error on
294   // incompatible types and flags.
295
296   uint32_t Alignment = 0;
297   uint64_t Flags = 0;
298   if (Config->Relocatable && (C->Flags & SHF_MERGE)) {
299     Alignment = std::max<uint64_t>(C->Alignment, C->Entsize);
300     Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
301   }
302
303   return SectionKey{OutsecName, Flags, Alignment};
304 }
305
306 OutputSectionFactory::OutputSectionFactory(
307     std::vector<OutputSection *> &OutputSections)
308     : OutputSections(OutputSections) {}
309
310 static uint64_t getIncompatibleFlags(uint64_t Flags) {
311   return Flags & (SHF_ALLOC | SHF_TLS);
312 }
313
314 // We allow sections of types listed below to merged into a
315 // single progbits section. This is typically done by linker
316 // scripts. Merging nobits and progbits will force disk space
317 // to be allocated for nobits sections. Other ones don't require
318 // any special treatment on top of progbits, so there doesn't
319 // seem to be a harm in merging them.
320 static bool canMergeToProgbits(unsigned Type) {
321   return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY ||
322          Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY ||
323          Type == SHT_NOTE;
324 }
325
326 void elf::reportDiscarded(InputSectionBase *IS) {
327   if (!Config->PrintGcSections)
328     return;
329   message("removing unused section from '" + IS->Name + "' in file '" +
330           IS->File->getName());
331 }
332
333 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
334                                        StringRef OutsecName) {
335   SectionKey Key = createKey(IS, OutsecName);
336   OutputSection *&Sec = Map[Key];
337   return addInputSec(IS, OutsecName, Sec);
338 }
339
340 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
341                                        StringRef OutsecName,
342                                        OutputSection *&Sec) {
343   if (!IS->Live) {
344     reportDiscarded(IS);
345     return;
346   }
347
348   uint64_t Flags = IS->Flags;
349   if (!Config->Relocatable)
350     Flags &= ~(uint64_t)SHF_GROUP;
351
352   if (Sec) {
353     if (getIncompatibleFlags(Sec->Flags) != getIncompatibleFlags(IS->Flags))
354       error("incompatible section flags for " + Sec->Name +
355             "\n>>> " + toString(IS) + ": 0x" + utohexstr(IS->Flags) +
356             "\n>>> output section " + Sec->Name + ": 0x" +
357             utohexstr(Sec->Flags));
358     if (Sec->Type != IS->Type) {
359       if (canMergeToProgbits(Sec->Type) && canMergeToProgbits(IS->Type))
360         Sec->Type = SHT_PROGBITS;
361       else
362         error("section type mismatch for " + IS->Name +
363               "\n>>> " + toString(IS) + ": " +
364               getELFSectionTypeName(Config->EMachine, IS->Type) +
365               "\n>>> output section " + Sec->Name + ": " +
366               getELFSectionTypeName(Config->EMachine, Sec->Type));
367     }
368     Sec->Flags |= Flags;
369   } else {
370     Sec = make<OutputSection>(OutsecName, IS->Type, Flags);
371     OutputSections.push_back(Sec);
372   }
373
374   Sec->addSection(cast<InputSection>(IS));
375 }
376
377 OutputSectionFactory::~OutputSectionFactory() {}
378
379 SectionKey DenseMapInfo<SectionKey>::getEmptyKey() {
380   return SectionKey{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
381 }
382
383 SectionKey DenseMapInfo<SectionKey>::getTombstoneKey() {
384   return SectionKey{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0};
385 }
386
387 unsigned DenseMapInfo<SectionKey>::getHashValue(const SectionKey &Val) {
388   return hash_combine(Val.Name, Val.Flags, Val.Alignment);
389 }
390
391 bool DenseMapInfo<SectionKey>::isEqual(const SectionKey &LHS,
392                                        const SectionKey &RHS) {
393   return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
394          LHS.Flags == RHS.Flags && LHS.Alignment == RHS.Alignment;
395 }
396
397 uint64_t elf::getHeaderSize() {
398   if (Config->OFormatBinary)
399     return 0;
400   return Out::ElfHeader->Size + Out::ProgramHeaders->Size;
401 }
402
403 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
404 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
405 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
406 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
407
408 template void OutputSection::finalize<ELF32LE>();
409 template void OutputSection::finalize<ELF32BE>();
410 template void OutputSection::finalize<ELF64LE>();
411 template void OutputSection::finalize<ELF64BE>();