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"
14 #include "SymbolTable.h"
15 #include "SyntheticSections.h"
17 #include "lld/Common/Memory.h"
18 #include "lld/Common/Threads.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/Support/Compression.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 std::vector<OutputSection *> elf::OutputSections;
47 uint32_t OutputSection::getPhdrFlags() const {
49 if (Flags & SHF_WRITE)
51 if (Flags & SHF_EXECINSTR)
57 void OutputSection::writeHeaderTo(typename ELFT::Shdr *Shdr) {
58 Shdr->sh_entsize = Entsize;
59 Shdr->sh_addralign = Alignment;
61 Shdr->sh_offset = Offset;
62 Shdr->sh_flags = Flags;
67 Shdr->sh_name = ShName;
70 OutputSection::OutputSection(StringRef Name, uint32_t Type, uint64_t Flags)
71 : BaseCommand(OutputSectionKind),
72 SectionBase(Output, Name, Flags, /*Entsize*/ 0, /*Alignment*/ 1, Type,
75 SectionIndex(INT_MAX) {
79 // We allow sections of types listed below to merged into a
80 // single progbits section. This is typically done by linker
81 // scripts. Merging nobits and progbits will force disk space
82 // to be allocated for nobits sections. Other ones don't require
83 // any special treatment on top of progbits, so there doesn't
84 // seem to be a harm in merging them.
85 static bool canMergeToProgbits(unsigned Type) {
86 return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY ||
87 Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY ||
91 void OutputSection::addSection(InputSection *IS) {
93 // If IS is the first section to be added to this section,
94 // initialize Type and Entsize from IS.
97 Entsize = IS->Entsize;
99 // Otherwise, check if new type or flags are compatible with existing ones.
100 if ((Flags & (SHF_ALLOC | SHF_TLS)) != (IS->Flags & (SHF_ALLOC | SHF_TLS)))
101 error("incompatible section flags for " + Name + "\n>>> " + toString(IS) +
102 ": 0x" + utohexstr(IS->Flags) + "\n>>> output section " + Name +
103 ": 0x" + utohexstr(Flags));
105 if (Type != IS->Type) {
106 if (!canMergeToProgbits(Type) || !canMergeToProgbits(IS->Type))
107 error("section type mismatch for " + IS->Name + "\n>>> " +
108 toString(IS) + ": " +
109 getELFSectionTypeName(Config->EMachine, IS->Type) +
110 "\n>>> output section " + Name + ": " +
111 getELFSectionTypeName(Config->EMachine, Type));
118 Alignment = std::max(Alignment, IS->Alignment);
119 IS->OutSecOff = Size++;
121 // If this section contains a table of fixed-size entries, sh_entsize
122 // holds the element size. If it contains elements of different size we
123 // set sh_entsize to 0.
124 if (Entsize != IS->Entsize)
129 if (SectionCommands.empty() ||
130 !isa<InputSectionDescription>(SectionCommands.back()))
131 SectionCommands.push_back(make<InputSectionDescription>(""));
132 auto *ISD = cast<InputSectionDescription>(SectionCommands.back());
133 ISD->Sections.push_back(IS);
137 void elf::sortByOrder(MutableArrayRef<InputSection *> In,
138 std::function<int(InputSectionBase *S)> Order) {
139 typedef std::pair<int, InputSection *> Pair;
140 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
143 for (InputSection *S : In)
144 V.push_back({Order(S), S});
145 std::stable_sort(V.begin(), V.end(), Comp);
147 for (size_t I = 0; I < V.size(); ++I)
151 uint64_t elf::getHeaderSize() {
152 if (Config->OFormatBinary)
154 return Out::ElfHeader->Size + Out::ProgramHeaders->Size;
157 bool OutputSection::classof(const BaseCommand *C) {
158 return C->Kind == OutputSectionKind;
161 void OutputSection::sort(std::function<int(InputSectionBase *S)> Order) {
163 assert(SectionCommands.size() == 1);
164 sortByOrder(cast<InputSectionDescription>(SectionCommands[0])->Sections,
168 // Fill [Buf, Buf + Size) with Filler.
169 // This is used for linker script "=fillexp" command.
170 static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
172 for (; I + 4 < Size; I += 4)
173 memcpy(Buf + I, &Filler, 4);
174 memcpy(Buf + I, &Filler, Size - I);
177 // Compress section contents if this section contains debug info.
178 template <class ELFT> void OutputSection::maybeCompress() {
179 typedef typename ELFT::Chdr Elf_Chdr;
181 // Compress only DWARF debug sections.
182 if (!Config->CompressDebugSections || (Flags & SHF_ALLOC) ||
183 !Name.startswith(".debug_"))
186 // Calculate the section offsets and size pre-compression.
188 for (BaseCommand *Cmd : SectionCommands)
189 if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
190 for (InputSection *IS : ISD->Sections) {
191 IS->OutSecOff = alignTo(Size, IS->Alignment);
192 this->Size = IS->OutSecOff + IS->getSize();
195 // Create a section header.
196 ZDebugHeader.resize(sizeof(Elf_Chdr));
197 auto *Hdr = reinterpret_cast<Elf_Chdr *>(ZDebugHeader.data());
198 Hdr->ch_type = ELFCOMPRESS_ZLIB;
200 Hdr->ch_addralign = Alignment;
202 // Write section contents to a temporary buffer and compress it.
203 std::vector<uint8_t> Buf(Size);
204 writeTo<ELFT>(Buf.data());
205 if (Error E = zlib::compress(toStringRef(Buf), CompressedData))
206 fatal("compress failed: " + llvm::toString(std::move(E)));
208 // Update section headers.
209 Size = sizeof(Elf_Chdr) + CompressedData.size();
210 Flags |= SHF_COMPRESSED;
213 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
217 write16(Buf, Data, Config->Endianness);
219 write32(Buf, Data, Config->Endianness);
221 write64(Buf, Data, Config->Endianness);
223 llvm_unreachable("unsupported Size argument");
226 template <class ELFT> void OutputSection::writeTo(uint8_t *Buf) {
227 if (Type == SHT_NOBITS)
232 // If -compress-debug-section is specified and if this is a debug seciton,
233 // we've already compressed section contents. If that's the case,
234 // just write it down.
235 if (!CompressedData.empty()) {
236 memcpy(Buf, ZDebugHeader.data(), ZDebugHeader.size());
237 memcpy(Buf + ZDebugHeader.size(), CompressedData.data(),
238 CompressedData.size());
242 // Write leading padding.
243 std::vector<InputSection *> Sections;
244 for (BaseCommand *Cmd : SectionCommands)
245 if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
246 for (InputSection *IS : ISD->Sections)
248 Sections.push_back(IS);
249 uint32_t Filler = getFiller();
251 fill(Buf, Sections.empty() ? Size : Sections[0]->OutSecOff, Filler);
253 parallelForEachN(0, Sections.size(), [&](size_t I) {
254 InputSection *IS = Sections[I];
255 IS->writeTo<ELFT>(Buf);
257 // Fill gaps between sections.
259 uint8_t *Start = Buf + IS->OutSecOff + IS->getSize();
261 if (I + 1 == Sections.size())
264 End = Buf + Sections[I + 1]->OutSecOff;
265 fill(Start, End - Start, Filler);
269 // Linker scripts may have BYTE()-family commands with which you
270 // can write arbitrary bytes to the output. Process them if any.
271 for (BaseCommand *Base : SectionCommands)
272 if (auto *Data = dyn_cast<ByteCommand>(Base))
273 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
276 template <class ELFT>
277 static void finalizeShtGroup(OutputSection *OS,
278 InputSection *Section) {
279 assert(Config->Relocatable);
281 // sh_link field for SHT_GROUP sections should contain the section index of
283 OS->Link = InX::SymTab->getParent()->SectionIndex;
285 // sh_info then contain index of an entry in symbol table section which
286 // provides signature of the section group.
287 ObjFile<ELFT> *Obj = Section->getFile<ELFT>();
288 ArrayRef<Symbol *> Symbols = Obj->getSymbols();
289 OS->Info = InX::SymTab->getSymbolIndex(Symbols[Section->Info]);
292 template <class ELFT> void OutputSection::finalize() {
293 InputSection *First = nullptr;
294 for (BaseCommand *Base : SectionCommands) {
295 if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
296 if (ISD->Sections.empty())
298 if (First == nullptr)
299 First = ISD->Sections.front();
301 if (isa<ByteCommand>(Base) && Type == SHT_NOBITS)
305 if (Flags & SHF_LINK_ORDER) {
306 // We must preserve the link order dependency of sections with the
307 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
308 // need to translate the InputSection sh_link to the OutputSection sh_link,
309 // all InputSections in the OutputSection have the same dependency.
310 if (auto *D = First->getLinkOrderDep())
311 Link = D->getParent()->SectionIndex;
314 if (Type == SHT_GROUP) {
315 finalizeShtGroup<ELFT>(this, First);
319 if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
322 if (isa<SyntheticSection>(First))
325 Link = InX::SymTab->getParent()->SectionIndex;
326 // sh_info for SHT_REL[A] sections should contain the section header index of
327 // the section to which the relocation applies.
328 InputSectionBase *S = First->getRelocatedSection();
329 Info = S->getOutputSection()->SectionIndex;
330 Flags |= SHF_INFO_LINK;
333 // Returns true if S matches /Filename.?\.o$/.
334 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
335 if (!S.endswith(".o"))
338 if (S.endswith(Filename))
340 return !S.empty() && S.drop_back().endswith(Filename);
343 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
344 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
346 // .ctors and .dtors are sorted by this priority from highest to lowest.
348 // 1. The section was contained in crtbegin (crtbegin contains
349 // some sentinel value in its .ctors and .dtors so that the runtime
350 // can find the beginning of the sections.)
352 // 2. The section has an optional priority value in the form of ".ctors.N"
353 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
354 // they are compared as string rather than number.
356 // 3. The section is just ".ctors" or ".dtors".
358 // 4. The section was contained in crtend, which contains an end marker.
360 // In an ideal world, we don't need this function because .init_array and
361 // .ctors are duplicate features (and .init_array is newer.) However, there
362 // are too many real-world use cases of .ctors, so we had no choice to
363 // support that with this rather ad-hoc semantics.
364 static bool compCtors(const InputSection *A, const InputSection *B) {
365 bool BeginA = isCrtbegin(A->File->getName());
366 bool BeginB = isCrtbegin(B->File->getName());
367 if (BeginA != BeginB)
369 bool EndA = isCrtend(A->File->getName());
370 bool EndB = isCrtend(B->File->getName());
373 StringRef X = A->Name;
374 StringRef Y = B->Name;
375 assert(X.startswith(".ctors") || X.startswith(".dtors"));
376 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
379 if (X.empty() && Y.empty())
384 // Sorts input sections by the special rules for .ctors and .dtors.
385 // Unfortunately, the rules are different from the one for .{init,fini}_array.
386 // Read the comment above.
387 void OutputSection::sortCtorsDtors() {
388 assert(SectionCommands.size() == 1);
389 auto *ISD = cast<InputSectionDescription>(SectionCommands[0]);
390 std::stable_sort(ISD->Sections.begin(), ISD->Sections.end(), compCtors);
393 // If an input string is in the form of "foo.N" where N is a number,
394 // return N. Otherwise, returns 65536, which is one greater than the
396 int elf::getPriority(StringRef S) {
397 size_t Pos = S.rfind('.');
398 if (Pos == StringRef::npos)
401 if (!to_integer(S.substr(Pos + 1), V, 10))
406 // Sorts input sections by section name suffixes, so that .foo.N comes
407 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
408 // We want to keep the original order if the priorities are the same
409 // because the compiler keeps the original initialization order in a
410 // translation unit and we need to respect that.
411 // For more detail, read the section of the GCC's manual about init_priority.
412 void OutputSection::sortInitFini() {
413 // Sort sections by priority.
414 sort([](InputSectionBase *S) { return getPriority(S->Name); });
417 uint32_t OutputSection::getFiller() {
420 if (Flags & SHF_EXECINSTR)
421 return Target->TrapInstr;
425 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
426 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
427 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
428 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
430 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf);
431 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf);
432 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf);
433 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf);
435 template void OutputSection::maybeCompress<ELF32LE>();
436 template void OutputSection::maybeCompress<ELF32BE>();
437 template void OutputSection::maybeCompress<ELF64LE>();
438 template void OutputSection::maybeCompress<ELF64BE>();
440 template void OutputSection::finalize<ELF32LE>();
441 template void OutputSection::finalize<ELF32BE>();
442 template void OutputSection::finalize<ELF64LE>();
443 template void OutputSection::finalize<ELF64BE>();