]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/OutputSections.cpp
Merge ^/head r320398 through r320572.
[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/BinaryFormat/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 std::vector<OutputSection *> elf::OutputSections;
45 std::vector<OutputSectionCommand *> elf::OutputSectionCommands;
46
47 uint32_t OutputSection::getPhdrFlags() const {
48   uint32_t Ret = PF_R;
49   if (Flags & SHF_WRITE)
50     Ret |= PF_W;
51   if (Flags & SHF_EXECINSTR)
52     Ret |= PF_X;
53   return Ret;
54 }
55
56 template <class ELFT>
57 void OutputSection::writeHeaderTo(typename ELFT::Shdr *Shdr) {
58   Shdr->sh_entsize = Entsize;
59   Shdr->sh_addralign = Alignment;
60   Shdr->sh_type = Type;
61   Shdr->sh_offset = Offset;
62   Shdr->sh_flags = Flags;
63   Shdr->sh_info = Info;
64   Shdr->sh_link = Link;
65   Shdr->sh_addr = Addr;
66   Shdr->sh_size = Size;
67   Shdr->sh_name = ShName;
68 }
69
70 OutputSection::OutputSection(StringRef Name, uint32_t Type, uint64_t Flags)
71     : SectionBase(Output, Name, Flags, /*Entsize*/ 0, /*Alignment*/ 1, Type,
72                   /*Info*/ 0,
73                   /*Link*/ 0),
74       SectionIndex(INT_MAX) {}
75
76 static uint64_t updateOffset(uint64_t Off, InputSection *S) {
77   Off = alignTo(Off, S->Alignment);
78   S->OutSecOff = Off;
79   return Off + S->getSize();
80 }
81
82 void OutputSection::addSection(InputSection *S) {
83   assert(S->Live);
84   Sections.push_back(S);
85   S->Parent = this;
86   this->updateAlignment(S->Alignment);
87
88   // The actual offsets will be computed by assignAddresses. For now, use
89   // crude approximation so that it is at least easy for other code to know the
90   // section order. It is also used to calculate the output section size early
91   // for compressed debug sections.
92   this->Size = updateOffset(Size, S);
93
94   // If this section contains a table of fixed-size entries, sh_entsize
95   // holds the element size. Consequently, if this contains two or more
96   // input sections, all of them must have the same sh_entsize. However,
97   // you can put different types of input sections into one output
98   // sectin by using linker scripts. I don't know what to do here.
99   // Probably we sholuld handle that as an error. But for now we just
100   // pick the largest sh_entsize.
101   this->Entsize = std::max(this->Entsize, S->Entsize);
102 }
103
104 // This function is called after we sort input sections
105 // and scan relocations to setup sections' offsets.
106 void OutputSection::assignOffsets() {
107   OutputSectionCommand *Cmd = Script->getCmd(this);
108   uint64_t Off = 0;
109   for (BaseCommand *Base : Cmd->Commands)
110     if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
111       for (InputSection *S : ISD->Sections)
112         Off = updateOffset(Off, S);
113   this->Size = Off;
114 }
115
116 void OutputSection::sort(std::function<int(InputSectionBase *S)> Order) {
117   typedef std::pair<unsigned, InputSection *> Pair;
118   auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
119
120   std::vector<Pair> V;
121   for (InputSection *S : Sections)
122     V.push_back({Order(S), S});
123   std::stable_sort(V.begin(), V.end(), Comp);
124   Sections.clear();
125   for (Pair &P : V)
126     Sections.push_back(P.second);
127 }
128
129 // Sorts input sections by section name suffixes, so that .foo.N comes
130 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
131 // We want to keep the original order if the priorities are the same
132 // because the compiler keeps the original initialization order in a
133 // translation unit and we need to respect that.
134 // For more detail, read the section of the GCC's manual about init_priority.
135 void OutputSection::sortInitFini() {
136   // Sort sections by priority.
137   sort([](InputSectionBase *S) { return getPriority(S->Name); });
138 }
139
140 // Returns true if S matches /Filename.?\.o$/.
141 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
142   if (!S.endswith(".o"))
143     return false;
144   S = S.drop_back(2);
145   if (S.endswith(Filename))
146     return true;
147   return !S.empty() && S.drop_back().endswith(Filename);
148 }
149
150 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
151 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
152
153 // .ctors and .dtors are sorted by this priority from highest to lowest.
154 //
155 //  1. The section was contained in crtbegin (crtbegin contains
156 //     some sentinel value in its .ctors and .dtors so that the runtime
157 //     can find the beginning of the sections.)
158 //
159 //  2. The section has an optional priority value in the form of ".ctors.N"
160 //     or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
161 //     they are compared as string rather than number.
162 //
163 //  3. The section is just ".ctors" or ".dtors".
164 //
165 //  4. The section was contained in crtend, which contains an end marker.
166 //
167 // In an ideal world, we don't need this function because .init_array and
168 // .ctors are duplicate features (and .init_array is newer.) However, there
169 // are too many real-world use cases of .ctors, so we had no choice to
170 // support that with this rather ad-hoc semantics.
171 static bool compCtors(const InputSection *A, const InputSection *B) {
172   bool BeginA = isCrtbegin(A->File->getName());
173   bool BeginB = isCrtbegin(B->File->getName());
174   if (BeginA != BeginB)
175     return BeginA;
176   bool EndA = isCrtend(A->File->getName());
177   bool EndB = isCrtend(B->File->getName());
178   if (EndA != EndB)
179     return EndB;
180   StringRef X = A->Name;
181   StringRef Y = B->Name;
182   assert(X.startswith(".ctors") || X.startswith(".dtors"));
183   assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
184   X = X.substr(6);
185   Y = Y.substr(6);
186   if (X.empty() && Y.empty())
187     return false;
188   return X < Y;
189 }
190
191 // Sorts input sections by the special rules for .ctors and .dtors.
192 // Unfortunately, the rules are different from the one for .{init,fini}_array.
193 // Read the comment above.
194 void OutputSection::sortCtorsDtors() {
195   std::stable_sort(Sections.begin(), Sections.end(), compCtors);
196 }
197
198 static SectionKey createKey(InputSectionBase *C, StringRef OutsecName) {
199   //  The ELF spec just says
200   // ----------------------------------------------------------------
201   // In the first phase, input sections that match in name, type and
202   // attribute flags should be concatenated into single sections.
203   // ----------------------------------------------------------------
204   //
205   // However, it is clear that at least some flags have to be ignored for
206   // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
207   // ignored. We should not have two output .text sections just because one was
208   // in a group and another was not for example.
209   //
210   // It also seems that that wording was a late addition and didn't get the
211   // necessary scrutiny.
212   //
213   // Merging sections with different flags is expected by some users. One
214   // reason is that if one file has
215   //
216   // int *const bar __attribute__((section(".foo"))) = (int *)0;
217   //
218   // gcc with -fPIC will produce a read only .foo section. But if another
219   // file has
220   //
221   // int zed;
222   // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
223   //
224   // gcc with -fPIC will produce a read write section.
225   //
226   // Last but not least, when using linker script the merge rules are forced by
227   // the script. Unfortunately, linker scripts are name based. This means that
228   // expressions like *(.foo*) can refer to multiple input sections with
229   // different flags. We cannot put them in different output sections or we
230   // would produce wrong results for
231   //
232   // start = .; *(.foo.*) end = .; *(.bar)
233   //
234   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
235   // another. The problem is that there is no way to layout those output
236   // sections such that the .foo sections are the only thing between the start
237   // and end symbols.
238   //
239   // Given the above issues, we instead merge sections by name and error on
240   // incompatible types and flags.
241
242   uint32_t Alignment = 0;
243   uint64_t Flags = 0;
244   if (Config->Relocatable && (C->Flags & SHF_MERGE)) {
245     Alignment = std::max<uint64_t>(C->Alignment, C->Entsize);
246     Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
247   }
248
249   return SectionKey{OutsecName, Flags, Alignment};
250 }
251
252 OutputSectionFactory::OutputSectionFactory(
253     std::vector<OutputSection *> &OutputSections)
254     : OutputSections(OutputSections) {}
255
256 static uint64_t getIncompatibleFlags(uint64_t Flags) {
257   return Flags & (SHF_ALLOC | SHF_TLS);
258 }
259
260 // We allow sections of types listed below to merged into a
261 // single progbits section. This is typically done by linker
262 // scripts. Merging nobits and progbits will force disk space
263 // to be allocated for nobits sections. Other ones don't require
264 // any special treatment on top of progbits, so there doesn't
265 // seem to be a harm in merging them.
266 static bool canMergeToProgbits(unsigned Type) {
267   return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY ||
268          Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY ||
269          Type == SHT_NOTE;
270 }
271
272 void elf::reportDiscarded(InputSectionBase *IS) {
273   if (!Config->PrintGcSections)
274     return;
275   message("removing unused section from '" + IS->Name + "' in file '" +
276           IS->File->getName() + "'");
277 }
278
279 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
280                                        StringRef OutsecName) {
281   // Sections with the SHT_GROUP attribute reach here only when the - r option
282   // is given. Such sections define "section groups", and InputFiles.cpp has
283   // dedup'ed section groups by their signatures. For the -r, we want to pass
284   // through all SHT_GROUP sections without merging them because merging them
285   // creates broken section contents.
286   if (IS->Type == SHT_GROUP) {
287     OutputSection *Out = nullptr;
288     addInputSec(IS, OutsecName, Out);
289     return;
290   }
291
292   // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
293   // relocation sections .rela.foo and .rela.bar for example. Most tools do
294   // not allow multiple REL[A] sections for output section. Hence we
295   // should combine these relocation sections into single output.
296   // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
297   // other REL[A] sections created by linker itself.
298   if (!isa<SyntheticSection>(IS) &&
299       (IS->Type == SHT_REL || IS->Type == SHT_RELA)) {
300     auto *Sec = cast<InputSection>(IS);
301     OutputSection *Out = Sec->getRelocatedSection()->getOutputSection();
302     addInputSec(IS, OutsecName, Out->RelocationSection);
303     return;
304   }
305
306   SectionKey Key = createKey(IS, OutsecName);
307   OutputSection *&Sec = Map[Key];
308   addInputSec(IS, OutsecName, Sec);
309 }
310
311 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
312                                        StringRef OutsecName,
313                                        OutputSection *&Sec) {
314   if (!IS->Live) {
315     reportDiscarded(IS);
316     return;
317   }
318
319   if (Sec) {
320     if (getIncompatibleFlags(Sec->Flags) != getIncompatibleFlags(IS->Flags))
321       error("incompatible section flags for " + Sec->Name +
322             "\n>>> " + toString(IS) + ": 0x" + utohexstr(IS->Flags) +
323             "\n>>> output section " + Sec->Name + ": 0x" +
324             utohexstr(Sec->Flags));
325     if (Sec->Type != IS->Type) {
326       if (canMergeToProgbits(Sec->Type) && canMergeToProgbits(IS->Type))
327         Sec->Type = SHT_PROGBITS;
328       else
329         error("section type mismatch for " + IS->Name +
330               "\n>>> " + toString(IS) + ": " +
331               getELFSectionTypeName(Config->EMachine, IS->Type) +
332               "\n>>> output section " + Sec->Name + ": " +
333               getELFSectionTypeName(Config->EMachine, Sec->Type));
334     }
335     Sec->Flags |= IS->Flags;
336   } else {
337     Sec = make<OutputSection>(OutsecName, IS->Type, IS->Flags);
338     OutputSections.push_back(Sec);
339   }
340
341   Sec->addSection(cast<InputSection>(IS));
342 }
343
344 OutputSectionFactory::~OutputSectionFactory() {}
345
346 SectionKey DenseMapInfo<SectionKey>::getEmptyKey() {
347   return SectionKey{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
348 }
349
350 SectionKey DenseMapInfo<SectionKey>::getTombstoneKey() {
351   return SectionKey{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0};
352 }
353
354 unsigned DenseMapInfo<SectionKey>::getHashValue(const SectionKey &Val) {
355   return hash_combine(Val.Name, Val.Flags, Val.Alignment);
356 }
357
358 bool DenseMapInfo<SectionKey>::isEqual(const SectionKey &LHS,
359                                        const SectionKey &RHS) {
360   return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
361          LHS.Flags == RHS.Flags && LHS.Alignment == RHS.Alignment;
362 }
363
364 uint64_t elf::getHeaderSize() {
365   if (Config->OFormatBinary)
366     return 0;
367   return Out::ElfHeader->Size + Out::ProgramHeaders->Size;
368 }
369
370 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
371 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
372 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
373 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);