1 //===- OutputSections.cpp -------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "OutputSections.h"
12 #include "LinkerScript.h"
15 #include "SymbolTable.h"
16 #include "SyntheticSections.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"
25 using namespace llvm::dwarf;
26 using namespace llvm::object;
27 using namespace llvm::support::endian;
28 using namespace llvm::ELF;
31 using namespace lld::elf;
34 OutputSection *Out::Opd;
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;
44 uint32_t OutputSection::getPhdrFlags() const {
46 if (Flags & SHF_WRITE)
48 if (Flags & SHF_EXECINSTR)
54 void OutputSection::writeHeaderTo(typename ELFT::Shdr *Shdr) {
55 Shdr->sh_entsize = Entsize;
56 Shdr->sh_addralign = Alignment;
58 Shdr->sh_offset = Offset;
59 Shdr->sh_flags = Flags;
64 Shdr->sh_name = ShName;
67 OutputSection::OutputSection(StringRef Name, uint32_t Type, uint64_t Flags)
68 : SectionBase(Output, Name, Flags, /*Entsize*/ 0, /*Alignment*/ 1, Type,
71 SectionIndex(INT_MAX) {}
73 static uint64_t updateOffset(uint64_t Off, InputSection *S) {
74 Off = alignTo(Off, S->Alignment);
76 return Off + S->getSize();
79 void OutputSection::addSection(InputSection *S) {
81 Sections.push_back(S);
83 this->updateAlignment(S->Alignment);
85 // The actual offsets will be computed by assignAddresses. For now, use
86 // crude approximation so that it is at least easy for other code to know the
87 // section order. It is also used to calculate the output section size early
88 // for compressed debug sections.
89 this->Size = updateOffset(Size, S);
91 // If this section contains a table of fixed-size entries, sh_entsize
92 // holds the element size. Consequently, if this contains two or more
93 // input sections, all of them must have the same sh_entsize. However,
94 // you can put different types of input sections into one output
95 // sectin by using linker scripts. I don't know what to do here.
96 // Probably we sholuld handle that as an error. But for now we just
97 // pick the largest sh_entsize.
98 this->Entsize = std::max(this->Entsize, S->Entsize);
101 // This function is called after we sort input sections
102 // and scan relocations to setup sections' offsets.
103 void OutputSection::assignOffsets() {
104 OutputSectionCommand *Cmd = Script->getCmd(this);
106 for (BaseCommand *Base : Cmd->Commands)
107 if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
108 for (InputSection *S : ISD->Sections)
109 Off = updateOffset(Off, S);
113 void OutputSection::sort(std::function<int(InputSectionBase *S)> Order) {
114 typedef std::pair<unsigned, InputSection *> Pair;
115 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
118 for (InputSection *S : Sections)
119 V.push_back({Order(S), S});
120 std::stable_sort(V.begin(), V.end(), Comp);
123 Sections.push_back(P.second);
126 // Sorts input sections by section name suffixes, so that .foo.N comes
127 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
128 // We want to keep the original order if the priorities are the same
129 // because the compiler keeps the original initialization order in a
130 // translation unit and we need to respect that.
131 // For more detail, read the section of the GCC's manual about init_priority.
132 void OutputSection::sortInitFini() {
133 // Sort sections by priority.
134 sort([](InputSectionBase *S) { return getPriority(S->Name); });
137 // Returns true if S matches /Filename.?\.o$/.
138 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
139 if (!S.endswith(".o"))
142 if (S.endswith(Filename))
144 return !S.empty() && S.drop_back().endswith(Filename);
147 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
148 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
150 // .ctors and .dtors are sorted by this priority from highest to lowest.
152 // 1. The section was contained in crtbegin (crtbegin contains
153 // some sentinel value in its .ctors and .dtors so that the runtime
154 // can find the beginning of the sections.)
156 // 2. The section has an optional priority value in the form of ".ctors.N"
157 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
158 // they are compared as string rather than number.
160 // 3. The section is just ".ctors" or ".dtors".
162 // 4. The section was contained in crtend, which contains an end marker.
164 // In an ideal world, we don't need this function because .init_array and
165 // .ctors are duplicate features (and .init_array is newer.) However, there
166 // are too many real-world use cases of .ctors, so we had no choice to
167 // support that with this rather ad-hoc semantics.
168 static bool compCtors(const InputSection *A, const InputSection *B) {
169 bool BeginA = isCrtbegin(A->File->getName());
170 bool BeginB = isCrtbegin(B->File->getName());
171 if (BeginA != BeginB)
173 bool EndA = isCrtend(A->File->getName());
174 bool EndB = isCrtend(B->File->getName());
177 StringRef X = A->Name;
178 StringRef Y = B->Name;
179 assert(X.startswith(".ctors") || X.startswith(".dtors"));
180 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
183 if (X.empty() && Y.empty())
188 // Sorts input sections by the special rules for .ctors and .dtors.
189 // Unfortunately, the rules are different from the one for .{init,fini}_array.
190 // Read the comment above.
191 void OutputSection::sortCtorsDtors() {
192 std::stable_sort(Sections.begin(), Sections.end(), compCtors);
195 static SectionKey createKey(InputSectionBase *C, StringRef OutsecName) {
196 // The ELF spec just says
197 // ----------------------------------------------------------------
198 // In the first phase, input sections that match in name, type and
199 // attribute flags should be concatenated into single sections.
200 // ----------------------------------------------------------------
202 // However, it is clear that at least some flags have to be ignored for
203 // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
204 // ignored. We should not have two output .text sections just because one was
205 // in a group and another was not for example.
207 // It also seems that that wording was a late addition and didn't get the
208 // necessary scrutiny.
210 // Merging sections with different flags is expected by some users. One
211 // reason is that if one file has
213 // int *const bar __attribute__((section(".foo"))) = (int *)0;
215 // gcc with -fPIC will produce a read only .foo section. But if another
219 // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
221 // gcc with -fPIC will produce a read write section.
223 // Last but not least, when using linker script the merge rules are forced by
224 // the script. Unfortunately, linker scripts are name based. This means that
225 // expressions like *(.foo*) can refer to multiple input sections with
226 // different flags. We cannot put them in different output sections or we
227 // would produce wrong results for
229 // start = .; *(.foo.*) end = .; *(.bar)
231 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
232 // another. The problem is that there is no way to layout those output
233 // sections such that the .foo sections are the only thing between the start
236 // Given the above issues, we instead merge sections by name and error on
237 // incompatible types and flags.
239 uint32_t Alignment = 0;
241 if (Config->Relocatable && (C->Flags & SHF_MERGE)) {
242 Alignment = std::max<uint64_t>(C->Alignment, C->Entsize);
243 Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
246 return SectionKey{OutsecName, Flags, Alignment};
249 OutputSectionFactory::OutputSectionFactory(
250 std::vector<OutputSection *> &OutputSections)
251 : OutputSections(OutputSections) {}
253 static uint64_t getIncompatibleFlags(uint64_t Flags) {
254 return Flags & (SHF_ALLOC | SHF_TLS);
257 // We allow sections of types listed below to merged into a
258 // single progbits section. This is typically done by linker
259 // scripts. Merging nobits and progbits will force disk space
260 // to be allocated for nobits sections. Other ones don't require
261 // any special treatment on top of progbits, so there doesn't
262 // seem to be a harm in merging them.
263 static bool canMergeToProgbits(unsigned Type) {
264 return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY ||
265 Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY ||
269 void elf::reportDiscarded(InputSectionBase *IS) {
270 if (!Config->PrintGcSections)
272 message("removing unused section from '" + IS->Name + "' in file '" +
273 IS->File->getName());
276 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
277 StringRef OutsecName) {
278 // Sections with the SHT_GROUP attribute reach here only when the - r option
279 // is given. Such sections define "section groups", and InputFiles.cpp has
280 // dedup'ed section groups by their signatures. For the -r, we want to pass
281 // through all SHT_GROUP sections without merging them because merging them
282 // creates broken section contents.
283 if (IS->Type == SHT_GROUP) {
284 OutputSection *Out = nullptr;
285 addInputSec(IS, OutsecName, Out);
289 // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
290 // relocation sections .rela.foo and .rela.bar for example. Most tools do
291 // not allow multiple REL[A] sections for output section. Hence we
292 // should combine these relocation sections into single output.
293 // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
294 // other REL[A] sections created by linker itself.
295 if (!isa<SyntheticSection>(IS) &&
296 (IS->Type == SHT_REL || IS->Type == SHT_RELA)) {
297 auto *Sec = cast<InputSection>(IS);
298 OutputSection *Out = Sec->getRelocatedSection()->getOutputSection();
299 addInputSec(IS, OutsecName, Out->RelocationSection);
303 SectionKey Key = createKey(IS, OutsecName);
304 OutputSection *&Sec = Map[Key];
305 return addInputSec(IS, OutsecName, Sec);
308 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
309 StringRef OutsecName,
310 OutputSection *&Sec) {
317 if (getIncompatibleFlags(Sec->Flags) != getIncompatibleFlags(IS->Flags))
318 error("incompatible section flags for " + Sec->Name +
319 "\n>>> " + toString(IS) + ": 0x" + utohexstr(IS->Flags) +
320 "\n>>> output section " + Sec->Name + ": 0x" +
321 utohexstr(Sec->Flags));
322 if (Sec->Type != IS->Type) {
323 if (canMergeToProgbits(Sec->Type) && canMergeToProgbits(IS->Type))
324 Sec->Type = SHT_PROGBITS;
326 error("section type mismatch for " + IS->Name +
327 "\n>>> " + toString(IS) + ": " +
328 getELFSectionTypeName(Config->EMachine, IS->Type) +
329 "\n>>> output section " + Sec->Name + ": " +
330 getELFSectionTypeName(Config->EMachine, Sec->Type));
332 Sec->Flags |= IS->Flags;
334 Sec = make<OutputSection>(OutsecName, IS->Type, IS->Flags);
335 OutputSections.push_back(Sec);
338 Sec->addSection(cast<InputSection>(IS));
341 OutputSectionFactory::~OutputSectionFactory() {}
343 SectionKey DenseMapInfo<SectionKey>::getEmptyKey() {
344 return SectionKey{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
347 SectionKey DenseMapInfo<SectionKey>::getTombstoneKey() {
348 return SectionKey{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0};
351 unsigned DenseMapInfo<SectionKey>::getHashValue(const SectionKey &Val) {
352 return hash_combine(Val.Name, Val.Flags, Val.Alignment);
355 bool DenseMapInfo<SectionKey>::isEqual(const SectionKey &LHS,
356 const SectionKey &RHS) {
357 return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
358 LHS.Flags == RHS.Flags && LHS.Alignment == RHS.Alignment;
361 uint64_t elf::getHeaderSize() {
362 if (Config->OFormatBinary)
364 return Out::ElfHeader->Size + Out::ProgramHeaders->Size;
367 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
368 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
369 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
370 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);