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/Compression.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"
26 using namespace llvm::dwarf;
27 using namespace llvm::object;
28 using namespace llvm::support::endian;
29 using namespace llvm::ELF;
32 using namespace lld::elf;
35 OutputSection *Out::Opd;
37 PhdrEntry *Out::TlsPhdr;
38 OutputSection *Out::DebugInfo;
39 OutputSection *Out::ElfHeader;
40 OutputSection *Out::ProgramHeaders;
41 OutputSection *Out::PreinitArray;
42 OutputSection *Out::InitArray;
43 OutputSection *Out::FiniArray;
45 uint32_t OutputSection::getPhdrFlags() const {
47 if (Flags & SHF_WRITE)
49 if (Flags & SHF_EXECINSTR)
55 void OutputSection::writeHeaderTo(typename ELFT::Shdr *Shdr) {
56 Shdr->sh_entsize = Entsize;
57 Shdr->sh_addralign = Alignment;
59 Shdr->sh_offset = Offset;
60 Shdr->sh_flags = Flags;
65 Shdr->sh_name = ShName;
68 OutputSection::OutputSection(StringRef Name, uint32_t Type, uint64_t Flags)
69 : SectionBase(Output, Name, Flags, /*Entsize*/ 0, /*Alignment*/ 1, Type,
72 SectionIndex(INT_MAX) {}
74 static bool compareByFilePosition(InputSection *A, InputSection *B) {
75 // Synthetic doesn't have link order dependecy, stable_sort will keep it last
76 if (A->kind() == InputSectionBase::Synthetic ||
77 B->kind() == InputSectionBase::Synthetic)
79 auto *LA = cast<InputSection>(A->getLinkOrderDep());
80 auto *LB = cast<InputSection>(B->getLinkOrderDep());
81 OutputSection *AOut = LA->OutSec;
82 OutputSection *BOut = LB->OutSec;
84 return AOut->SectionIndex < BOut->SectionIndex;
85 return LA->OutSecOff < LB->OutSecOff;
88 // Compress section contents if this section contains debug info.
89 template <class ELFT> void OutputSection::maybeCompress() {
90 typedef typename ELFT::Chdr Elf_Chdr;
92 // Compress only DWARF debug sections.
93 if (!Config->CompressDebugSections || (Flags & SHF_ALLOC) ||
94 !Name.startswith(".debug_"))
97 // Create a section header.
98 ZDebugHeader.resize(sizeof(Elf_Chdr));
99 auto *Hdr = reinterpret_cast<Elf_Chdr *>(ZDebugHeader.data());
100 Hdr->ch_type = ELFCOMPRESS_ZLIB;
102 Hdr->ch_addralign = Alignment;
104 // Write section contents to a temporary buffer and compress it.
105 std::vector<uint8_t> Buf(Size);
106 Script->getCmd(this)->writeTo<ELFT>(Buf.data());
107 if (Error E = zlib::compress(toStringRef(Buf), CompressedData))
108 fatal("compress failed: " + llvm::toString(std::move(E)));
110 // Update section headers.
111 Size = sizeof(Elf_Chdr) + CompressedData.size();
112 Flags |= SHF_COMPRESSED;
115 template <class ELFT> static void finalizeShtGroup(OutputSection *Sec) {
116 // sh_link field for SHT_GROUP sections should contain the section index of
118 Sec->Link = InX::SymTab->OutSec->SectionIndex;
120 // sh_link then contain index of an entry in symbol table section which
121 // provides signature of the section group.
122 elf::ObjectFile<ELFT> *Obj = Sec->Sections[0]->getFile<ELFT>();
123 assert(Config->Relocatable && Sec->Sections.size() == 1);
124 ArrayRef<SymbolBody *> Symbols = Obj->getSymbols();
125 Sec->Info = InX::SymTab->getSymbolIndex(Symbols[Sec->Sections[0]->Info - 1]);
128 template <class ELFT> void OutputSection::finalize() {
129 if ((this->Flags & SHF_LINK_ORDER) && !this->Sections.empty()) {
130 std::sort(Sections.begin(), Sections.end(), compareByFilePosition);
133 // We must preserve the link order dependency of sections with the
134 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
135 // need to translate the InputSection sh_link to the OutputSection sh_link,
136 // all InputSections in the OutputSection have the same dependency.
137 if (auto *D = this->Sections.front()->getLinkOrderDep())
138 this->Link = D->OutSec->SectionIndex;
141 uint32_t Type = this->Type;
142 if (Type == SHT_GROUP) {
143 finalizeShtGroup<ELFT>(this);
147 if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
150 InputSection *First = Sections[0];
151 if (isa<SyntheticSection>(First))
154 this->Link = InX::SymTab->OutSec->SectionIndex;
155 // sh_info for SHT_REL[A] sections should contain the section header index of
156 // the section to which the relocation applies.
157 InputSectionBase *S = First->getRelocatedSection();
158 this->Info = S->OutSec->SectionIndex;
161 static uint64_t updateOffset(uint64_t Off, InputSection *S) {
162 Off = alignTo(Off, S->Alignment);
164 return Off + S->getSize();
167 void OutputSection::addSection(InputSection *S) {
169 Sections.push_back(S);
171 this->updateAlignment(S->Alignment);
173 // The actual offsets will be computed by assignAddresses. For now, use
174 // crude approximation so that it is at least easy for other code to know the
175 // section order. It is also used to calculate the output section size early
176 // for compressed debug sections.
177 this->Size = updateOffset(Size, S);
179 // If this section contains a table of fixed-size entries, sh_entsize
180 // holds the element size. Consequently, if this contains two or more
181 // input sections, all of them must have the same sh_entsize. However,
182 // you can put different types of input sections into one output
183 // sectin by using linker scripts. I don't know what to do here.
184 // Probably we sholuld handle that as an error. But for now we just
185 // pick the largest sh_entsize.
186 this->Entsize = std::max(this->Entsize, S->Entsize);
189 // This function is called after we sort input sections
190 // and scan relocations to setup sections' offsets.
191 void OutputSection::assignOffsets() {
193 for (InputSection *S : Sections)
194 Off = updateOffset(Off, S);
198 void OutputSection::sort(std::function<int(InputSectionBase *S)> Order) {
199 typedef std::pair<unsigned, InputSection *> Pair;
200 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
203 for (InputSection *S : Sections)
204 V.push_back({Order(S), S});
205 std::stable_sort(V.begin(), V.end(), Comp);
208 Sections.push_back(P.second);
211 // Sorts input sections by section name suffixes, so that .foo.N comes
212 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
213 // We want to keep the original order if the priorities are the same
214 // because the compiler keeps the original initialization order in a
215 // translation unit and we need to respect that.
216 // For more detail, read the section of the GCC's manual about init_priority.
217 void OutputSection::sortInitFini() {
218 // Sort sections by priority.
219 sort([](InputSectionBase *S) { return getPriority(S->Name); });
222 // Returns true if S matches /Filename.?\.o$/.
223 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
224 if (!S.endswith(".o"))
227 if (S.endswith(Filename))
229 return !S.empty() && S.drop_back().endswith(Filename);
232 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
233 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
235 // .ctors and .dtors are sorted by this priority from highest to lowest.
237 // 1. The section was contained in crtbegin (crtbegin contains
238 // some sentinel value in its .ctors and .dtors so that the runtime
239 // can find the beginning of the sections.)
241 // 2. The section has an optional priority value in the form of ".ctors.N"
242 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
243 // they are compared as string rather than number.
245 // 3. The section is just ".ctors" or ".dtors".
247 // 4. The section was contained in crtend, which contains an end marker.
249 // In an ideal world, we don't need this function because .init_array and
250 // .ctors are duplicate features (and .init_array is newer.) However, there
251 // are too many real-world use cases of .ctors, so we had no choice to
252 // support that with this rather ad-hoc semantics.
253 static bool compCtors(const InputSection *A, const InputSection *B) {
254 bool BeginA = isCrtbegin(A->File->getName());
255 bool BeginB = isCrtbegin(B->File->getName());
256 if (BeginA != BeginB)
258 bool EndA = isCrtend(A->File->getName());
259 bool EndB = isCrtend(B->File->getName());
262 StringRef X = A->Name;
263 StringRef Y = B->Name;
264 assert(X.startswith(".ctors") || X.startswith(".dtors"));
265 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
268 if (X.empty() && Y.empty())
273 // Sorts input sections by the special rules for .ctors and .dtors.
274 // Unfortunately, the rules are different from the one for .{init,fini}_array.
275 // Read the comment above.
276 void OutputSection::sortCtorsDtors() {
277 std::stable_sort(Sections.begin(), Sections.end(), compCtors);
280 static SectionKey createKey(InputSectionBase *C, StringRef OutsecName) {
281 // The ELF spec just says
282 // ----------------------------------------------------------------
283 // In the first phase, input sections that match in name, type and
284 // attribute flags should be concatenated into single sections.
285 // ----------------------------------------------------------------
287 // However, it is clear that at least some flags have to be ignored for
288 // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
289 // ignored. We should not have two output .text sections just because one was
290 // in a group and another was not for example.
292 // It also seems that that wording was a late addition and didn't get the
293 // necessary scrutiny.
295 // Merging sections with different flags is expected by some users. One
296 // reason is that if one file has
298 // int *const bar __attribute__((section(".foo"))) = (int *)0;
300 // gcc with -fPIC will produce a read only .foo section. But if another
304 // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
306 // gcc with -fPIC will produce a read write section.
308 // Last but not least, when using linker script the merge rules are forced by
309 // the script. Unfortunately, linker scripts are name based. This means that
310 // expressions like *(.foo*) can refer to multiple input sections with
311 // different flags. We cannot put them in different output sections or we
312 // would produce wrong results for
314 // start = .; *(.foo.*) end = .; *(.bar)
316 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
317 // another. The problem is that there is no way to layout those output
318 // sections such that the .foo sections are the only thing between the start
321 // Given the above issues, we instead merge sections by name and error on
322 // incompatible types and flags.
324 uint32_t Alignment = 0;
326 if (Config->Relocatable && (C->Flags & SHF_MERGE)) {
327 Alignment = std::max<uint64_t>(C->Alignment, C->Entsize);
328 Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
331 return SectionKey{OutsecName, Flags, Alignment};
334 OutputSectionFactory::OutputSectionFactory(
335 std::vector<OutputSection *> &OutputSections)
336 : OutputSections(OutputSections) {}
338 static uint64_t getIncompatibleFlags(uint64_t Flags) {
339 return Flags & (SHF_ALLOC | SHF_TLS);
342 // We allow sections of types listed below to merged into a
343 // single progbits section. This is typically done by linker
344 // scripts. Merging nobits and progbits will force disk space
345 // to be allocated for nobits sections. Other ones don't require
346 // any special treatment on top of progbits, so there doesn't
347 // seem to be a harm in merging them.
348 static bool canMergeToProgbits(unsigned Type) {
349 return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY ||
350 Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY ||
354 static void reportDiscarded(InputSectionBase *IS) {
355 if (!Config->PrintGcSections)
357 message("removing unused section from '" + IS->Name + "' in file '" +
358 IS->File->getName());
361 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
362 StringRef OutsecName) {
363 SectionKey Key = createKey(IS, OutsecName);
364 OutputSection *&Sec = Map[Key];
365 return addInputSec(IS, OutsecName, Sec);
368 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
369 StringRef OutsecName,
370 OutputSection *&Sec) {
376 uint64_t Flags = IS->Flags;
377 if (!Config->Relocatable)
378 Flags &= ~(uint64_t)SHF_GROUP;
381 if (getIncompatibleFlags(Sec->Flags) != getIncompatibleFlags(IS->Flags))
382 error("incompatible section flags for " + Sec->Name +
383 "\n>>> " + toString(IS) + ": 0x" + utohexstr(IS->Flags) +
384 "\n>>> output section " + Sec->Name + ": 0x" +
385 utohexstr(Sec->Flags));
386 if (Sec->Type != IS->Type) {
387 if (canMergeToProgbits(Sec->Type) && canMergeToProgbits(IS->Type))
388 Sec->Type = SHT_PROGBITS;
390 error("section type mismatch for " + IS->Name +
391 "\n>>> " + toString(IS) + ": " +
392 getELFSectionTypeName(Config->EMachine, IS->Type) +
393 "\n>>> output section " + Sec->Name + ": " +
394 getELFSectionTypeName(Config->EMachine, Sec->Type));
398 Sec = make<OutputSection>(OutsecName, IS->Type, Flags);
399 OutputSections.push_back(Sec);
402 Sec->addSection(cast<InputSection>(IS));
405 OutputSectionFactory::~OutputSectionFactory() {}
407 SectionKey DenseMapInfo<SectionKey>::getEmptyKey() {
408 return SectionKey{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
411 SectionKey DenseMapInfo<SectionKey>::getTombstoneKey() {
412 return SectionKey{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0};
415 unsigned DenseMapInfo<SectionKey>::getHashValue(const SectionKey &Val) {
416 return hash_combine(Val.Name, Val.Flags, Val.Alignment);
419 bool DenseMapInfo<SectionKey>::isEqual(const SectionKey &LHS,
420 const SectionKey &RHS) {
421 return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
422 LHS.Flags == RHS.Flags && LHS.Alignment == RHS.Alignment;
425 uint64_t elf::getHeaderSize() {
426 if (Config->OFormatBinary)
428 return Out::ElfHeader->Size + Out::ProgramHeaders->Size;
431 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
432 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
433 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
434 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
436 template void OutputSection::finalize<ELF32LE>();
437 template void OutputSection::finalize<ELF32BE>();
438 template void OutputSection::finalize<ELF64LE>();
439 template void OutputSection::finalize<ELF64BE>();
441 template void OutputSection::maybeCompress<ELF32LE>();
442 template void OutputSection::maybeCompress<ELF32BE>();
443 template void OutputSection::maybeCompress<ELF64LE>();
444 template void OutputSection::maybeCompress<ELF64BE>();