1 //===- OutputSections.cpp -------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "OutputSections.h"
11 #include "LinkerScript.h"
12 #include "SymbolTable.h"
13 #include "SyntheticSections.h"
15 #include "lld/Common/Memory.h"
16 #include "lld/Common/Strings.h"
17 #include "lld/Common/Threads.h"
18 #include "llvm/BinaryFormat/Dwarf.h"
19 #include "llvm/Support/Compression.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;
33 uint8_t *Out::bufferStart;
35 PhdrEntry *Out::tlsPhdr;
36 OutputSection *Out::elfHeader;
37 OutputSection *Out::programHeaders;
38 OutputSection *Out::preinitArray;
39 OutputSection *Out::initArray;
40 OutputSection *Out::finiArray;
42 std::vector<OutputSection *> elf::outputSections;
44 uint32_t OutputSection::getPhdrFlags() const {
46 if (config->emachine != EM_ARM || !(flags & SHF_ARM_PURECODE))
48 if (flags & SHF_WRITE)
50 if (flags & SHF_EXECINSTR)
56 void OutputSection::writeHeaderTo(typename ELFT::Shdr *shdr) {
57 shdr->sh_entsize = entsize;
58 shdr->sh_addralign = alignment;
60 shdr->sh_offset = offset;
61 shdr->sh_flags = flags;
66 shdr->sh_name = shName;
69 OutputSection::OutputSection(StringRef name, uint32_t type, uint64_t flags)
70 : BaseCommand(OutputSectionKind),
71 SectionBase(Output, name, flags, /*Entsize*/ 0, /*Alignment*/ 1, type,
72 /*Info*/ 0, /*Link*/ 0) {}
74 // We allow sections of types listed below to merged into a
75 // single progbits section. This is typically done by linker
76 // scripts. Merging nobits and progbits will force disk space
77 // to be allocated for nobits sections. Other ones don't require
78 // any special treatment on top of progbits, so there doesn't
79 // seem to be a harm in merging them.
80 static bool canMergeToProgbits(unsigned type) {
81 return type == SHT_NOBITS || type == SHT_PROGBITS || type == SHT_INIT_ARRAY ||
82 type == SHT_PREINIT_ARRAY || type == SHT_FINI_ARRAY ||
86 void OutputSection::addSection(InputSection *isec) {
87 if (!hasInputSections) {
88 // If IS is the first section to be added to this section,
89 // initialize Partition, Type, Entsize and flags from IS.
90 hasInputSections = true;
91 partition = isec->partition;
93 entsize = isec->entsize;
96 // Otherwise, check if new type or flags are compatible with existing ones.
97 unsigned mask = SHF_TLS | SHF_LINK_ORDER;
98 if ((flags & mask) != (isec->flags & mask))
99 error("incompatible section flags for " + name + "\n>>> " + toString(isec) +
100 ": 0x" + utohexstr(isec->flags) + "\n>>> output section " + name +
101 ": 0x" + utohexstr(flags));
103 if (type != isec->type) {
104 if (!canMergeToProgbits(type) || !canMergeToProgbits(isec->type))
105 error("section type mismatch for " + isec->name + "\n>>> " +
106 toString(isec) + ": " +
107 getELFSectionTypeName(config->emachine, isec->type) +
108 "\n>>> output section " + name + ": " +
109 getELFSectionTypeName(config->emachine, type));
116 config->emachine == EM_ARM ? (uint64_t)SHF_ARM_PURECODE : 0;
117 uint64_t orMask = ~andMask;
118 uint64_t andFlags = (flags & isec->flags) & andMask;
119 uint64_t orFlags = (flags | isec->flags) & orMask;
120 flags = andFlags | orFlags;
122 alignment = std::max(alignment, isec->alignment);
124 // If this section contains a table of fixed-size entries, sh_entsize
125 // holds the element size. If it contains elements of different size we
126 // set sh_entsize to 0.
127 if (entsize != isec->entsize)
130 if (!isec->assigned) {
131 isec->assigned = true;
132 if (sectionCommands.empty() ||
133 !isa<InputSectionDescription>(sectionCommands.back()))
134 sectionCommands.push_back(make<InputSectionDescription>(""));
135 auto *isd = cast<InputSectionDescription>(sectionCommands.back());
136 isd->sections.push_back(isec);
140 static void sortByOrder(MutableArrayRef<InputSection *> in,
141 llvm::function_ref<int(InputSectionBase *s)> order) {
142 std::vector<std::pair<int, InputSection *>> v;
143 for (InputSection *s : in)
144 v.push_back({order(s), s});
145 llvm::stable_sort(v, less_first());
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(llvm::function_ref<int(InputSectionBase *s)> order) {
163 for (BaseCommand *b : sectionCommands)
164 if (auto *isd = dyn_cast<InputSectionDescription>(b))
165 sortByOrder(isd->sections, order);
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,
171 const std::array<uint8_t, 4> &filler) {
173 for (; i + 4 < size; i += 4)
174 memcpy(buf + i, filler.data(), 4);
175 memcpy(buf + i, filler.data(), size - i);
178 // Compress section contents if this section contains debug info.
179 template <class ELFT> void OutputSection::maybeCompress() {
180 using Elf_Chdr = typename ELFT::Chdr;
182 // Compress only DWARF debug sections.
183 if (!config->compressDebugSections || (flags & SHF_ALLOC) ||
184 !name.startswith(".debug_"))
187 // Create a section header.
188 zDebugHeader.resize(sizeof(Elf_Chdr));
189 auto *hdr = reinterpret_cast<Elf_Chdr *>(zDebugHeader.data());
190 hdr->ch_type = ELFCOMPRESS_ZLIB;
192 hdr->ch_addralign = alignment;
194 // Write section contents to a temporary buffer and compress it.
195 std::vector<uint8_t> buf(size);
196 writeTo<ELFT>(buf.data());
197 if (Error e = zlib::compress(toStringRef(buf), compressedData))
198 fatal("compress failed: " + llvm::toString(std::move(e)));
200 // Update section headers.
201 size = sizeof(Elf_Chdr) + compressedData.size();
202 flags |= SHF_COMPRESSED;
205 static void writeInt(uint8_t *buf, uint64_t data, uint64_t size) {
215 llvm_unreachable("unsupported Size argument");
218 template <class ELFT> void OutputSection::writeTo(uint8_t *buf) {
219 if (type == SHT_NOBITS)
222 // If -compress-debug-section is specified and if this is a debug seciton,
223 // we've already compressed section contents. If that's the case,
224 // just write it down.
225 if (!compressedData.empty()) {
226 memcpy(buf, zDebugHeader.data(), zDebugHeader.size());
227 memcpy(buf + zDebugHeader.size(), compressedData.data(),
228 compressedData.size());
232 // Write leading padding.
233 std::vector<InputSection *> sections = getInputSections(this);
234 std::array<uint8_t, 4> filler = getFiller();
235 bool nonZeroFiller = read32(filler.data()) != 0;
237 fill(buf, sections.empty() ? size : sections[0]->outSecOff, filler);
239 parallelForEachN(0, sections.size(), [&](size_t i) {
240 InputSection *isec = sections[i];
241 isec->writeTo<ELFT>(buf);
243 // Fill gaps between sections.
245 uint8_t *start = buf + isec->outSecOff + isec->getSize();
247 if (i + 1 == sections.size())
250 end = buf + sections[i + 1]->outSecOff;
251 fill(start, end - start, filler);
255 // Linker scripts may have BYTE()-family commands with which you
256 // can write arbitrary bytes to the output. Process them if any.
257 for (BaseCommand *base : sectionCommands)
258 if (auto *data = dyn_cast<ByteCommand>(base))
259 writeInt(buf + data->offset, data->expression().getValue(), data->size);
262 static void finalizeShtGroup(OutputSection *os,
263 InputSection *section) {
264 assert(config->relocatable);
266 // sh_link field for SHT_GROUP sections should contain the section index of
268 os->link = in.symTab->getParent()->sectionIndex;
270 // sh_info then contain index of an entry in symbol table section which
271 // provides signature of the section group.
272 ArrayRef<Symbol *> symbols = section->file->getSymbols();
273 os->info = in.symTab->getSymbolIndex(symbols[section->info]);
276 void OutputSection::finalize() {
277 std::vector<InputSection *> v = getInputSections(this);
278 InputSection *first = v.empty() ? nullptr : v[0];
280 if (flags & SHF_LINK_ORDER) {
281 // We must preserve the link order dependency of sections with the
282 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
283 // need to translate the InputSection sh_link to the OutputSection sh_link,
284 // all InputSections in the OutputSection have the same dependency.
285 if (auto *ex = dyn_cast<ARMExidxSyntheticSection>(first))
286 link = ex->getLinkOrderDep()->getParent()->sectionIndex;
287 else if (auto *d = first->getLinkOrderDep())
288 link = d->getParent()->sectionIndex;
291 if (type == SHT_GROUP) {
292 finalizeShtGroup(this, first);
296 if (!config->copyRelocs || (type != SHT_RELA && type != SHT_REL))
299 if (isa<SyntheticSection>(first))
302 link = in.symTab->getParent()->sectionIndex;
303 // sh_info for SHT_REL[A] sections should contain the section header index of
304 // the section to which the relocation applies.
305 InputSectionBase *s = first->getRelocatedSection();
306 info = s->getOutputSection()->sectionIndex;
307 flags |= SHF_INFO_LINK;
310 // Returns true if S matches /Filename.?\.o$/.
311 static bool isCrtBeginEnd(StringRef s, StringRef filename) {
312 if (!s.endswith(".o"))
315 if (s.endswith(filename))
317 return !s.empty() && s.drop_back().endswith(filename);
320 static bool isCrtbegin(StringRef s) { return isCrtBeginEnd(s, "crtbegin"); }
321 static bool isCrtend(StringRef s) { return isCrtBeginEnd(s, "crtend"); }
323 // .ctors and .dtors are sorted by this priority from highest to lowest.
325 // 1. The section was contained in crtbegin (crtbegin contains
326 // some sentinel value in its .ctors and .dtors so that the runtime
327 // can find the beginning of the sections.)
329 // 2. The section has an optional priority value in the form of ".ctors.N"
330 // or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
331 // they are compared as string rather than number.
333 // 3. The section is just ".ctors" or ".dtors".
335 // 4. The section was contained in crtend, which contains an end marker.
337 // In an ideal world, we don't need this function because .init_array and
338 // .ctors are duplicate features (and .init_array is newer.) However, there
339 // are too many real-world use cases of .ctors, so we had no choice to
340 // support that with this rather ad-hoc semantics.
341 static bool compCtors(const InputSection *a, const InputSection *b) {
342 bool beginA = isCrtbegin(a->file->getName());
343 bool beginB = isCrtbegin(b->file->getName());
344 if (beginA != beginB)
346 bool endA = isCrtend(a->file->getName());
347 bool endB = isCrtend(b->file->getName());
350 StringRef x = a->name;
351 StringRef y = b->name;
352 assert(x.startswith(".ctors") || x.startswith(".dtors"));
353 assert(y.startswith(".ctors") || y.startswith(".dtors"));
359 // Sorts input sections by the special rules for .ctors and .dtors.
360 // Unfortunately, the rules are different from the one for .{init,fini}_array.
361 // Read the comment above.
362 void OutputSection::sortCtorsDtors() {
363 assert(sectionCommands.size() == 1);
364 auto *isd = cast<InputSectionDescription>(sectionCommands[0]);
365 llvm::stable_sort(isd->sections, compCtors);
368 // If an input string is in the form of "foo.N" where N is a number,
369 // return N. Otherwise, returns 65536, which is one greater than the
371 int elf::getPriority(StringRef s) {
372 size_t pos = s.rfind('.');
373 if (pos == StringRef::npos)
376 if (!to_integer(s.substr(pos + 1), v, 10))
381 std::vector<InputSection *> elf::getInputSections(OutputSection *os) {
382 std::vector<InputSection *> ret;
383 for (BaseCommand *base : os->sectionCommands)
384 if (auto *isd = dyn_cast<InputSectionDescription>(base))
385 ret.insert(ret.end(), isd->sections.begin(), isd->sections.end());
389 // Sorts input sections by section name suffixes, so that .foo.N comes
390 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
391 // We want to keep the original order if the priorities are the same
392 // because the compiler keeps the original initialization order in a
393 // translation unit and we need to respect that.
394 // For more detail, read the section of the GCC's manual about init_priority.
395 void OutputSection::sortInitFini() {
396 // Sort sections by priority.
397 sort([](InputSectionBase *s) { return getPriority(s->name); });
400 std::array<uint8_t, 4> OutputSection::getFiller() {
403 if (flags & SHF_EXECINSTR)
404 return target->trapInstr;
408 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
409 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
410 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
411 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
413 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf);
414 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf);
415 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf);
416 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf);
418 template void OutputSection::maybeCompress<ELF32LE>();
419 template void OutputSection::maybeCompress<ELF32BE>();
420 template void OutputSection::maybeCompress<ELF64LE>();
421 template void OutputSection::maybeCompress<ELF64BE>();