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,
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 auto *LA = cast<InputSection>(A->getLinkOrderDep());
79 auto *LB = cast<InputSection>(B->getLinkOrderDep());
80 OutputSection *AOut = LA->OutSec;
81 OutputSection *BOut = LB->OutSec;
83 return AOut->SectionIndex < BOut->SectionIndex;
84 return LA->OutSecOff < LB->OutSecOff;
87 // Compress section contents if this section contains debug info.
88 template <class ELFT> void OutputSection::maybeCompress() {
89 typedef typename ELFT::Chdr Elf_Chdr;
91 // Compress only DWARF debug sections.
92 if (!Config->CompressDebugSections || (Flags & SHF_ALLOC) ||
93 !Name.startswith(".debug_"))
96 // Create a section header.
97 ZDebugHeader.resize(sizeof(Elf_Chdr));
98 auto *Hdr = reinterpret_cast<Elf_Chdr *>(ZDebugHeader.data());
99 Hdr->ch_type = ELFCOMPRESS_ZLIB;
101 Hdr->ch_addralign = Alignment;
103 // Write section contents to a temporary buffer and compress it.
104 std::vector<uint8_t> Buf(Size);
105 writeTo<ELFT>(Buf.data());
106 if (Error E = zlib::compress(toStringRef(Buf), CompressedData))
107 fatal("compress failed: " + llvm::toString(std::move(E)));
109 // Update section headers.
110 Size = sizeof(Elf_Chdr) + CompressedData.size();
111 Flags |= SHF_COMPRESSED;
114 template <class ELFT> void OutputSection::finalize() {
115 if ((this->Flags & SHF_LINK_ORDER) && !this->Sections.empty()) {
116 std::sort(Sections.begin(), Sections.end(), compareByFilePosition);
119 // We must preserve the link order dependency of sections with the
120 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
121 // need to translate the InputSection sh_link to the OutputSection sh_link,
122 // all InputSections in the OutputSection have the same dependency.
123 if (auto *D = this->Sections.front()->getLinkOrderDep())
124 this->Link = D->OutSec->SectionIndex;
127 uint32_t Type = this->Type;
128 if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
131 InputSection *First = Sections[0];
132 if (isa<SyntheticSection>(First))
135 this->Link = In<ELFT>::SymTab->OutSec->SectionIndex;
136 // sh_info for SHT_REL[A] sections should contain the section header index of
137 // the section to which the relocation applies.
138 InputSectionBase *S = First->getRelocatedSection();
139 this->Info = S->OutSec->SectionIndex;
142 void OutputSection::addSection(InputSection *S) {
144 Sections.push_back(S);
146 this->updateAlignment(S->Alignment);
148 // If this section contains a table of fixed-size entries, sh_entsize
149 // holds the element size. Consequently, if this contains two or more
150 // input sections, all of them must have the same sh_entsize. However,
151 // you can put different types of input sections into one output
152 // sectin by using linker scripts. I don't know what to do here.
153 // Probably we sholuld handle that as an error. But for now we just
154 // pick the largest sh_entsize.
155 this->Entsize = std::max(this->Entsize, S->Entsize);
158 // This function is called after we sort input sections
159 // and scan relocations to setup sections' offsets.
160 void OutputSection::assignOffsets() {
162 for (InputSection *S : Sections) {
163 Off = alignTo(Off, S->Alignment);
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 // Fill [Buf, Buf + Size) with Filler.
253 // This is used for linker script "=fillexp" command.
254 static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
256 for (; I + 4 < Size; I += 4)
257 memcpy(Buf + I, &Filler, 4);
258 memcpy(Buf + I, &Filler, Size - I);
261 uint32_t OutputSection::getFiller() {
262 // Determine what to fill gaps between InputSections with, as specified by the
263 // linker script. If nothing is specified and this is an executable section,
264 // fall back to trap instructions to prevent bad diassembly and detect invalid
266 if (Optional<uint32_t> Filler = Script->getFiller(Name))
268 if (Flags & SHF_EXECINSTR)
269 return Target->TrapInstr;
273 template <class ELFT> void OutputSection::writeTo(uint8_t *Buf) {
276 // We may have already rendered compressed content when using
277 // -compress-debug-sections option. Write it together with header.
278 if (!CompressedData.empty()) {
279 memcpy(Buf, ZDebugHeader.data(), ZDebugHeader.size());
280 memcpy(Buf + ZDebugHeader.size(), CompressedData.data(),
281 CompressedData.size());
285 // Write leading padding.
286 uint32_t Filler = getFiller();
288 fill(Buf, Sections.empty() ? Size : Sections[0]->OutSecOff, Filler);
290 parallelFor(0, Sections.size(), [=](size_t I) {
291 InputSection *Sec = Sections[I];
292 Sec->writeTo<ELFT>(Buf);
294 // Fill gaps between sections.
296 uint8_t *Start = Buf + Sec->OutSecOff + Sec->getSize();
298 if (I + 1 == Sections.size())
301 End = Buf + Sections[I + 1]->OutSecOff;
302 fill(Start, End - Start, Filler);
306 // Linker scripts may have BYTE()-family commands with which you
307 // can write arbitrary bytes to the output. Process them if any.
308 Script->writeDataBytes(Name, Buf);
311 static uint64_t getOutFlags(InputSectionBase *S) {
312 return S->Flags & ~SHF_GROUP & ~SHF_COMPRESSED;
315 static SectionKey createKey(InputSectionBase *C, StringRef OutsecName) {
316 // The ELF spec just says
317 // ----------------------------------------------------------------
318 // In the first phase, input sections that match in name, type and
319 // attribute flags should be concatenated into single sections.
320 // ----------------------------------------------------------------
322 // However, it is clear that at least some flags have to be ignored for
323 // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
324 // ignored. We should not have two output .text sections just because one was
325 // in a group and another was not for example.
327 // It also seems that that wording was a late addition and didn't get the
328 // necessary scrutiny.
330 // Merging sections with different flags is expected by some users. One
331 // reason is that if one file has
333 // int *const bar __attribute__((section(".foo"))) = (int *)0;
335 // gcc with -fPIC will produce a read only .foo section. But if another
339 // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
341 // gcc with -fPIC will produce a read write section.
343 // Last but not least, when using linker script the merge rules are forced by
344 // the script. Unfortunately, linker scripts are name based. This means that
345 // expressions like *(.foo*) can refer to multiple input sections with
346 // different flags. We cannot put them in different output sections or we
347 // would produce wrong results for
349 // start = .; *(.foo.*) end = .; *(.bar)
351 // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
352 // another. The problem is that there is no way to layout those output
353 // sections such that the .foo sections are the only thing between the start
356 // Given the above issues, we instead merge sections by name and error on
357 // incompatible types and flags.
359 uint32_t Alignment = 0;
361 if (Config->Relocatable && (C->Flags & SHF_MERGE)) {
362 Alignment = std::max<uint64_t>(C->Alignment, C->Entsize);
363 Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
366 return SectionKey{OutsecName, Flags, Alignment};
369 OutputSectionFactory::OutputSectionFactory(
370 std::vector<OutputSection *> &OutputSections)
371 : OutputSections(OutputSections) {}
373 static uint64_t getIncompatibleFlags(uint64_t Flags) {
374 return Flags & (SHF_ALLOC | SHF_TLS);
377 // We allow sections of types listed below to merged into a
378 // single progbits section. This is typically done by linker
379 // scripts. Merging nobits and progbits will force disk space
380 // to be allocated for nobits sections. Other ones don't require
381 // any special treatment on top of progbits, so there doesn't
382 // seem to be a harm in merging them.
383 static bool canMergeToProgbits(unsigned Type) {
384 return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY ||
385 Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY ||
389 static void reportDiscarded(InputSectionBase *IS) {
390 if (!Config->PrintGcSections)
392 message("removing unused section from '" + IS->Name + "' in file '" +
393 IS->File->getName());
396 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
397 StringRef OutsecName) {
403 SectionKey Key = createKey(IS, OutsecName);
404 uint64_t Flags = getOutFlags(IS);
405 OutputSection *&Sec = Map[Key];
407 if (getIncompatibleFlags(Sec->Flags) != getIncompatibleFlags(IS->Flags))
408 error("Section has flags incompatible with others with the same name " +
410 if (Sec->Type != IS->Type) {
411 if (canMergeToProgbits(Sec->Type) && canMergeToProgbits(IS->Type))
412 Sec->Type = SHT_PROGBITS;
414 error("Section has different type from others with the same name " +
419 Sec = make<OutputSection>(Key.Name, IS->Type, Flags);
420 OutputSections.push_back(Sec);
423 Sec->addSection(cast<InputSection>(IS));
426 OutputSectionFactory::~OutputSectionFactory() {}
428 SectionKey DenseMapInfo<SectionKey>::getEmptyKey() {
429 return SectionKey{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
432 SectionKey DenseMapInfo<SectionKey>::getTombstoneKey() {
433 return SectionKey{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0};
436 unsigned DenseMapInfo<SectionKey>::getHashValue(const SectionKey &Val) {
437 return hash_combine(Val.Name, Val.Flags, Val.Alignment);
440 bool DenseMapInfo<SectionKey>::isEqual(const SectionKey &LHS,
441 const SectionKey &RHS) {
442 return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
443 LHS.Flags == RHS.Flags && LHS.Alignment == RHS.Alignment;
446 uint64_t elf::getHeaderSize() {
447 if (Config->OFormatBinary)
449 return Out::ElfHeader->Size + Out::ProgramHeaders->Size;
452 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
453 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
454 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
455 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
457 template void OutputSection::finalize<ELF32LE>();
458 template void OutputSection::finalize<ELF32BE>();
459 template void OutputSection::finalize<ELF64LE>();
460 template void OutputSection::finalize<ELF64BE>();
462 template void OutputSection::maybeCompress<ELF32LE>();
463 template void OutputSection::maybeCompress<ELF32BE>();
464 template void OutputSection::maybeCompress<ELF64LE>();
465 template void OutputSection::maybeCompress<ELF64BE>();
467 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf);
468 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf);
469 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf);
470 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf);