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/Support/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 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)
78 InputSection *LA = A->getLinkOrderDep();
79 InputSection *LB = B->getLinkOrderDep();
80 OutputSection *AOut = LA->getParent();
81 OutputSection *BOut = LB->getParent();
83 return AOut->SectionIndex < BOut->SectionIndex;
84 return LA->OutSecOff < LB->OutSecOff;
87 template <class ELFT> static void finalizeShtGroup(OutputSection *Sec) {
88 // sh_link field for SHT_GROUP sections should contain the section index of
90 Sec->Link = InX::SymTab->getParent()->SectionIndex;
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]);
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);
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;
113 uint32_t Type = this->Type;
114 if (Type == SHT_GROUP) {
115 finalizeShtGroup<ELFT>(this);
119 if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
122 InputSection *First = Sections[0];
123 if (isa<SyntheticSection>(First))
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;
133 static uint64_t updateOffset(uint64_t Off, InputSection *S) {
134 Off = alignTo(Off, S->Alignment);
136 return Off + S->getSize();
139 void OutputSection::addSection(InputSection *S) {
141 Sections.push_back(S);
143 this->updateAlignment(S->Alignment);
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);
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);
161 // This function is called after we sort input sections
162 // and scan relocations to setup sections' offsets.
163 void OutputSection::assignOffsets() {
165 for (InputSection *S : Sections)
166 Off = updateOffset(Off, S);
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; };
175 for (InputSection *S : Sections)
176 V.push_back({Order(S), S});
177 std::stable_sort(V.begin(), V.end(), Comp);
180 Sections.push_back(P.second);
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); });
194 // Returns true if S matches /Filename.?\.o$/.
195 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
196 if (!S.endswith(".o"))
199 if (S.endswith(Filename))
201 return !S.empty() && S.drop_back().endswith(Filename);
204 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
205 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
207 // .ctors and .dtors are sorted by this priority from highest to lowest.
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.)
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.
217 // 3. The section is just ".ctors" or ".dtors".
219 // 4. The section was contained in crtend, which contains an end marker.
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)
230 bool EndA = isCrtend(A->File->getName());
231 bool EndB = isCrtend(B->File->getName());
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"));
240 if (X.empty() && Y.empty())
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);
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 // ----------------------------------------------------------------
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.
264 // It also seems that that wording was a late addition and didn't get the
265 // necessary scrutiny.
267 // Merging sections with different flags is expected by some users. One
268 // reason is that if one file has
270 // int *const bar __attribute__((section(".foo"))) = (int *)0;
272 // gcc with -fPIC will produce a read only .foo section. But if another
276 // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
278 // gcc with -fPIC will produce a read write section.
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
286 // start = .; *(.foo.*) end = .; *(.bar)
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
293 // Given the above issues, we instead merge sections by name and error on
294 // incompatible types and flags.
296 uint32_t Alignment = 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);
303 return SectionKey{OutsecName, Flags, Alignment};
306 OutputSectionFactory::OutputSectionFactory(
307 std::vector<OutputSection *> &OutputSections)
308 : OutputSections(OutputSections) {}
310 static uint64_t getIncompatibleFlags(uint64_t Flags) {
311 return Flags & (SHF_ALLOC | SHF_TLS);
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 ||
326 void elf::reportDiscarded(InputSectionBase *IS) {
327 if (!Config->PrintGcSections)
329 message("removing unused section from '" + IS->Name + "' in file '" +
330 IS->File->getName());
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);
340 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
341 StringRef OutsecName,
342 OutputSection *&Sec) {
348 uint64_t Flags = IS->Flags;
349 if (!Config->Relocatable)
350 Flags &= ~(uint64_t)SHF_GROUP;
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;
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));
370 Sec = make<OutputSection>(OutsecName, IS->Type, Flags);
371 OutputSections.push_back(Sec);
374 Sec->addSection(cast<InputSection>(IS));
377 OutputSectionFactory::~OutputSectionFactory() {}
379 SectionKey DenseMapInfo<SectionKey>::getEmptyKey() {
380 return SectionKey{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
383 SectionKey DenseMapInfo<SectionKey>::getTombstoneKey() {
384 return SectionKey{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0};
387 unsigned DenseMapInfo<SectionKey>::getHashValue(const SectionKey &Val) {
388 return hash_combine(Val.Name, Val.Flags, Val.Alignment);
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;
397 uint64_t elf::getHeaderSize() {
398 if (Config->OFormatBinary)
400 return Out::ElfHeader->Size + Out::ProgramHeaders->Size;
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);
408 template void OutputSection::finalize<ELF32LE>();
409 template void OutputSection::finalize<ELF32BE>();
410 template void OutputSection::finalize<ELF64LE>();
411 template void OutputSection::finalize<ELF64BE>();