• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- OutputSections.cpp -------------------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "OutputSections.h"
10 #include "Config.h"
11 #include "LinkerScript.h"
12 #include "SymbolTable.h"
13 #include "SyntheticSections.h"
14 #include "Target.h"
15 #include "lld/Common/Memory.h"
16 #include "lld/Common/Strings.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/Support/Compression.h"
19 #include "llvm/Support/MD5.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/Parallel.h"
22 #include "llvm/Support/SHA1.h"
23 #include "llvm/Support/TimeProfiler.h"
24 #include <regex>
25 #include <unordered_set>
26 
27 using namespace llvm;
28 using namespace llvm::dwarf;
29 using namespace llvm::object;
30 using namespace llvm::support::endian;
31 using namespace llvm::ELF;
32 using namespace lld;
33 using namespace lld::elf;
34 
35 uint8_t *Out::bufferStart;
36 uint8_t Out::first;
37 PhdrEntry *Out::tlsPhdr;
38 OutputSection *Out::elfHeader;
39 OutputSection *Out::programHeaders;
40 OutputSection *Out::preinitArray;
41 OutputSection *Out::initArray;
42 OutputSection *Out::finiArray;
43 
44 std::vector<OutputSection *> elf::outputSections;
45 
getPhdrFlags() const46 uint32_t OutputSection::getPhdrFlags() const {
47   uint32_t ret = 0;
48   if (config->emachine != EM_ARM || !(flags & SHF_ARM_PURECODE))
49     ret |= PF_R;
50   if (flags & SHF_WRITE)
51     ret |= PF_W;
52   if (flags & SHF_EXECINSTR)
53     ret |= PF_X;
54   return ret;
55 }
56 
57 template <class ELFT>
writeHeaderTo(typename ELFT::Shdr * shdr)58 void OutputSection::writeHeaderTo(typename ELFT::Shdr *shdr) {
59   shdr->sh_entsize = entsize;
60   shdr->sh_addralign = alignment;
61   shdr->sh_type = type;
62   shdr->sh_offset = offset;
63   shdr->sh_flags = flags;
64   shdr->sh_info = info;
65   shdr->sh_link = link;
66   shdr->sh_addr = addr;
67   shdr->sh_size = size;
68   shdr->sh_name = shName;
69 }
70 
OutputSection(StringRef name,uint32_t type,uint64_t flags)71 OutputSection::OutputSection(StringRef name, uint32_t type, uint64_t flags)
72     : BaseCommand(OutputSectionKind),
73       SectionBase(Output, name, flags, /*Entsize*/ 0, /*Alignment*/ 1, type,
74                   /*Info*/ 0, /*Link*/ 0) {}
75 
76 // We allow sections of types listed below to merged into a
77 // single progbits section. This is typically done by linker
78 // scripts. Merging nobits and progbits will force disk space
79 // to be allocated for nobits sections. Other ones don't require
80 // any special treatment on top of progbits, so there doesn't
81 // seem to be a harm in merging them.
82 //
83 // NOTE: clang since rL252300 emits SHT_X86_64_UNWIND .eh_frame sections. Allow
84 // them to be merged into SHT_PROGBITS .eh_frame (GNU as .cfi_*).
canMergeToProgbits(unsigned type)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 ||
88          type == SHT_NOTE ||
89          (type == SHT_X86_64_UNWIND && config->emachine == EM_X86_64);
90 }
91 
92 // Record that isec will be placed in the OutputSection. isec does not become
93 // permanent until finalizeInputSections() is called. The function should not be
94 // used after finalizeInputSections() is called. If you need to add an
95 // InputSection post finalizeInputSections(), then you must do the following:
96 //
97 // 1. Find or create an InputSectionDescription to hold InputSection.
98 // 2. Add the InputSection to the InputSectionDescription::sections.
99 // 3. Call commitSection(isec).
recordSection(InputSectionBase * isec)100 void OutputSection::recordSection(InputSectionBase *isec) {
101   partition = isec->partition;
102   isec->parent = this;
103   if (sectionCommands.empty() ||
104       !isa<InputSectionDescription>(sectionCommands.back()))
105     sectionCommands.push_back(make<InputSectionDescription>(""));
106   auto *isd = cast<InputSectionDescription>(sectionCommands.back());
107   isd->sectionBases.push_back(isec);
108 }
109 
110 // Update fields (type, flags, alignment, etc) according to the InputSection
111 // isec. Also check whether the InputSection flags and type are consistent with
112 // other InputSections.
commitSection(InputSection * isec)113 void OutputSection::commitSection(InputSection *isec) {
114   if (!hasInputSections) {
115     // If IS is the first section to be added to this section,
116     // initialize type, entsize and flags from isec.
117     hasInputSections = true;
118     type = isec->type;
119     entsize = isec->entsize;
120     flags = isec->flags;
121   } else {
122     // Otherwise, check if new type or flags are compatible with existing ones.
123     if ((flags ^ isec->flags) & SHF_TLS)
124       error("incompatible section flags for " + name + "\n>>> " + toString(isec) +
125             ": 0x" + utohexstr(isec->flags) + "\n>>> output section " + name +
126             ": 0x" + utohexstr(flags));
127 
128     if (type != isec->type) {
129       if (!canMergeToProgbits(type) || !canMergeToProgbits(isec->type))
130         error("section type mismatch for " + isec->name + "\n>>> " +
131               toString(isec) + ": " +
132               getELFSectionTypeName(config->emachine, isec->type) +
133               "\n>>> output section " + name + ": " +
134               getELFSectionTypeName(config->emachine, type));
135       type = SHT_PROGBITS;
136     }
137   }
138   if (noload)
139     type = SHT_NOBITS;
140 
141   isec->parent = this;
142   uint64_t andMask =
143       config->emachine == EM_ARM ? (uint64_t)SHF_ARM_PURECODE : 0;
144   uint64_t orMask = ~andMask;
145   uint64_t andFlags = (flags & isec->flags) & andMask;
146   uint64_t orFlags = (flags | isec->flags) & orMask;
147   flags = andFlags | orFlags;
148   if (nonAlloc)
149     flags &= ~(uint64_t)SHF_ALLOC;
150 
151   alignment = std::max(alignment, isec->alignment);
152 
153   // If this section contains a table of fixed-size entries, sh_entsize
154   // holds the element size. If it contains elements of different size we
155   // set sh_entsize to 0.
156   if (entsize != isec->entsize)
157     entsize = 0;
158 }
159 
160 // This function scans over the InputSectionBase list sectionBases to create
161 // InputSectionDescription::sections.
162 //
163 // It removes MergeInputSections from the input section array and adds
164 // new synthetic sections at the location of the first input section
165 // that it replaces. It then finalizes each synthetic section in order
166 // to compute an output offset for each piece of each input section.
finalizeInputSections()167 void OutputSection::finalizeInputSections() {
168   std::vector<MergeSyntheticSection *> mergeSections;
169   for (BaseCommand *base : sectionCommands) {
170     auto *cmd = dyn_cast<InputSectionDescription>(base);
171     if (!cmd)
172       continue;
173     cmd->sections.reserve(cmd->sectionBases.size());
174     for (InputSectionBase *s : cmd->sectionBases) {
175       MergeInputSection *ms = dyn_cast<MergeInputSection>(s);
176       if (!ms) {
177         cmd->sections.push_back(cast<InputSection>(s));
178         continue;
179       }
180 
181       // We do not want to handle sections that are not alive, so just remove
182       // them instead of trying to merge.
183       if (!ms->isLive())
184         continue;
185 
186       auto i = llvm::find_if(mergeSections, [=](MergeSyntheticSection *sec) {
187         // While we could create a single synthetic section for two different
188         // values of Entsize, it is better to take Entsize into consideration.
189         //
190         // With a single synthetic section no two pieces with different Entsize
191         // could be equal, so we may as well have two sections.
192         //
193         // Using Entsize in here also allows us to propagate it to the synthetic
194         // section.
195         //
196         // SHF_STRINGS section with different alignments should not be merged.
197         return sec->flags == ms->flags && sec->entsize == ms->entsize &&
198                (sec->alignment == ms->alignment || !(sec->flags & SHF_STRINGS));
199       });
200       if (i == mergeSections.end()) {
201         MergeSyntheticSection *syn =
202             createMergeSynthetic(name, ms->type, ms->flags, ms->alignment);
203         mergeSections.push_back(syn);
204         i = std::prev(mergeSections.end());
205         syn->entsize = ms->entsize;
206         cmd->sections.push_back(syn);
207       }
208       (*i)->addSection(ms);
209     }
210 
211     // sectionBases should not be used from this point onwards. Clear it to
212     // catch misuses.
213     cmd->sectionBases.clear();
214 
215     // Some input sections may be removed from the list after ICF.
216     for (InputSection *s : cmd->sections)
217       commitSection(s);
218   }
219   for (auto *ms : mergeSections)
220     ms->finalizeContents();
221 }
222 
sortByOrder(MutableArrayRef<InputSection * > in,llvm::function_ref<int (InputSectionBase * s)> order)223 static void sortByOrder(MutableArrayRef<InputSection *> in,
224                         llvm::function_ref<int(InputSectionBase *s)> order) {
225   std::vector<std::pair<int, InputSection *>> v;
226   for (InputSection *s : in)
227     v.push_back({order(s), s});
228   llvm::stable_sort(v, less_first());
229 
230   for (size_t i = 0; i < v.size(); ++i)
231     in[i] = v[i].second;
232 }
233 
getHeaderSize()234 uint64_t elf::getHeaderSize() {
235   if (config->oFormatBinary)
236     return 0;
237   return Out::elfHeader->size + Out::programHeaders->size;
238 }
239 
classof(const BaseCommand * c)240 bool OutputSection::classof(const BaseCommand *c) {
241   return c->kind == OutputSectionKind;
242 }
243 
sort(llvm::function_ref<int (InputSectionBase * s)> order)244 void OutputSection::sort(llvm::function_ref<int(InputSectionBase *s)> order) {
245   assert(isLive());
246   for (BaseCommand *b : sectionCommands)
247     if (auto *isd = dyn_cast<InputSectionDescription>(b))
248       sortByOrder(isd->sections, order);
249 }
250 
nopInstrFill(uint8_t * buf,size_t size)251 static void nopInstrFill(uint8_t *buf, size_t size) {
252   if (size == 0)
253     return;
254   unsigned i = 0;
255   if (size == 0)
256     return;
257   std::vector<std::vector<uint8_t>> nopFiller = *target->nopInstrs;
258   unsigned num = size / nopFiller.back().size();
259   for (unsigned c = 0; c < num; ++c) {
260     memcpy(buf + i, nopFiller.back().data(), nopFiller.back().size());
261     i += nopFiller.back().size();
262   }
263   unsigned remaining = size - i;
264   if (!remaining)
265     return;
266   assert(nopFiller[remaining - 1].size() == remaining);
267   memcpy(buf + i, nopFiller[remaining - 1].data(), remaining);
268 }
269 
270 // Fill [Buf, Buf + Size) with Filler.
271 // This is used for linker script "=fillexp" command.
fill(uint8_t * buf,size_t size,const std::array<uint8_t,4> & filler)272 static void fill(uint8_t *buf, size_t size,
273                  const std::array<uint8_t, 4> &filler) {
274   size_t i = 0;
275   for (; i + 4 < size; i += 4)
276     memcpy(buf + i, filler.data(), 4);
277   memcpy(buf + i, filler.data(), size - i);
278 }
279 
280 // Compress section contents if this section contains debug info.
maybeCompress()281 template <class ELFT> void OutputSection::maybeCompress() {
282   using Elf_Chdr = typename ELFT::Chdr;
283 
284   // Compress only DWARF debug sections.
285   if (!config->compressDebugSections || (flags & SHF_ALLOC) ||
286       !name.startswith(".debug_"))
287     return;
288 
289   llvm::TimeTraceScope timeScope("Compress debug sections");
290 
291   // Create a section header.
292   zDebugHeader.resize(sizeof(Elf_Chdr));
293   auto *hdr = reinterpret_cast<Elf_Chdr *>(zDebugHeader.data());
294   hdr->ch_type = ELFCOMPRESS_ZLIB;
295   hdr->ch_size = size;
296   hdr->ch_addralign = alignment;
297 
298   // Write section contents to a temporary buffer and compress it.
299   std::vector<uint8_t> buf(size);
300   writeTo<ELFT>(buf.data());
301   // We chose 1 as the default compression level because it is the fastest. If
302   // -O2 is given, we use level 6 to compress debug info more by ~15%. We found
303   // that level 7 to 9 doesn't make much difference (~1% more compression) while
304   // they take significant amount of time (~2x), so level 6 seems enough.
305   if (Error e = zlib::compress(toStringRef(buf), compressedData,
306                                config->optimize >= 2 ? 6 : 1))
307     fatal("compress failed: " + llvm::toString(std::move(e)));
308 
309   // Update section headers.
310   size = sizeof(Elf_Chdr) + compressedData.size();
311   flags |= SHF_COMPRESSED;
312 }
313 
writeInt(uint8_t * buf,uint64_t data,uint64_t size)314 static void writeInt(uint8_t *buf, uint64_t data, uint64_t size) {
315   if (size == 1)
316     *buf = data;
317   else if (size == 2)
318     write16(buf, data);
319   else if (size == 4)
320     write32(buf, data);
321   else if (size == 8)
322     write64(buf, data);
323   else
324     llvm_unreachable("unsupported Size argument");
325 }
326 
writeTo(uint8_t * buf)327 template <class ELFT> void OutputSection::writeTo(uint8_t *buf) {
328   if (type == SHT_NOBITS)
329     return;
330 
331   // If -compress-debug-section is specified and if this is a debug section,
332   // we've already compressed section contents. If that's the case,
333   // just write it down.
334   if (!compressedData.empty()) {
335     memcpy(buf, zDebugHeader.data(), zDebugHeader.size());
336     memcpy(buf + zDebugHeader.size(), compressedData.data(),
337            compressedData.size());
338     return;
339   }
340 
341   // Write leading padding.
342   std::vector<InputSection *> sections = getInputSections(this);
343   std::array<uint8_t, 4> filler = getFiller();
344   bool nonZeroFiller = read32(filler.data()) != 0;
345   if (nonZeroFiller)
346     fill(buf, sections.empty() ? size : sections[0]->outSecOff, filler);
347 
348   parallelForEachN(0, sections.size(), [&](size_t i) {
349     InputSection *isec = sections[i];
350     isec->writeTo<ELFT>(buf);
351 
352     // Fill gaps between sections.
353     if (nonZeroFiller) {
354       uint8_t *start = buf + isec->outSecOff + isec->getSize();
355       uint8_t *end;
356       if (i + 1 == sections.size())
357         end = buf + size;
358       else
359         end = buf + sections[i + 1]->outSecOff;
360       if (isec->nopFiller) {
361         assert(target->nopInstrs);
362         nopInstrFill(start, end - start);
363       } else
364         fill(start, end - start, filler);
365     }
366   });
367 
368   // Linker scripts may have BYTE()-family commands with which you
369   // can write arbitrary bytes to the output. Process them if any.
370   for (BaseCommand *base : sectionCommands)
371     if (auto *data = dyn_cast<ByteCommand>(base))
372       writeInt(buf + data->offset, data->expression().getValue(), data->size);
373 }
374 
finalizeShtGroup(OutputSection * os,InputSection * section)375 static void finalizeShtGroup(OutputSection *os,
376                              InputSection *section) {
377   assert(config->relocatable);
378 
379   // sh_link field for SHT_GROUP sections should contain the section index of
380   // the symbol table.
381   os->link = in.symTab->getParent()->sectionIndex;
382 
383   // sh_info then contain index of an entry in symbol table section which
384   // provides signature of the section group.
385   ArrayRef<Symbol *> symbols = section->file->getSymbols();
386   os->info = in.symTab->getSymbolIndex(symbols[section->info]);
387 
388   // Some group members may be combined or discarded, so we need to compute the
389   // new size. The content will be rewritten in InputSection::copyShtGroup.
390   std::unordered_set<uint32_t> seen;
391   ArrayRef<InputSectionBase *> sections = section->file->getSections();
392   for (const uint32_t &idx : section->getDataAs<uint32_t>().slice(1))
393     if (OutputSection *osec = sections[read32(&idx)]->getOutputSection())
394       seen.insert(osec->sectionIndex);
395   os->size = (1 + seen.size()) * sizeof(uint32_t);
396 }
397 
finalize()398 void OutputSection::finalize() {
399   InputSection *first = getFirstInputSection(this);
400 
401   if (flags & SHF_LINK_ORDER) {
402     // We must preserve the link order dependency of sections with the
403     // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
404     // need to translate the InputSection sh_link to the OutputSection sh_link,
405     // all InputSections in the OutputSection have the same dependency.
406     if (auto *ex = dyn_cast<ARMExidxSyntheticSection>(first))
407       link = ex->getLinkOrderDep()->getParent()->sectionIndex;
408     else if (first->flags & SHF_LINK_ORDER)
409       if (auto *d = first->getLinkOrderDep())
410         link = d->getParent()->sectionIndex;
411   }
412 
413   if (type == SHT_GROUP) {
414     finalizeShtGroup(this, first);
415     return;
416   }
417 
418   if (!config->copyRelocs || (type != SHT_RELA && type != SHT_REL))
419     return;
420 
421   if (isa<SyntheticSection>(first))
422     return;
423 
424   link = in.symTab->getParent()->sectionIndex;
425   // sh_info for SHT_REL[A] sections should contain the section header index of
426   // the section to which the relocation applies.
427   InputSectionBase *s = first->getRelocatedSection();
428   info = s->getOutputSection()->sectionIndex;
429   flags |= SHF_INFO_LINK;
430 }
431 
432 // Returns true if S is in one of the many forms the compiler driver may pass
433 // crtbegin files.
434 //
435 // Gcc uses any of crtbegin[<empty>|S|T].o.
436 // Clang uses Gcc's plus clang_rt.crtbegin[<empty>|S|T][-<arch>|<empty>].o.
437 
isCrtbegin(StringRef s)438 static bool isCrtbegin(StringRef s) {
439   static std::regex re(R"((clang_rt\.)?crtbegin[ST]?(-.*)?\.o)");
440   s = sys::path::filename(s);
441   return std::regex_match(s.begin(), s.end(), re);
442 }
443 
isCrtend(StringRef s)444 static bool isCrtend(StringRef s) {
445   static std::regex re(R"((clang_rt\.)?crtend[ST]?(-.*)?\.o)");
446   s = sys::path::filename(s);
447   return std::regex_match(s.begin(), s.end(), re);
448 }
449 
450 // .ctors and .dtors are sorted by this order:
451 //
452 // 1. .ctors/.dtors in crtbegin (which contains a sentinel value -1).
453 // 2. The section is named ".ctors" or ".dtors" (priority: 65536).
454 // 3. The section has an optional priority value in the form of ".ctors.N" or
455 //    ".dtors.N" where N is a number in the form of %05u (priority: 65535-N).
456 // 4. .ctors/.dtors in crtend (which contains a sentinel value 0).
457 //
458 // For 2 and 3, the sections are sorted by priority from high to low, e.g.
459 // .ctors (65536), .ctors.00100 (65436), .ctors.00200 (65336).  In GNU ld's
460 // internal linker scripts, the sorting is by string comparison which can
461 // achieve the same goal given the optional priority values are of the same
462 // length.
463 //
464 // In an ideal world, we don't need this function because .init_array and
465 // .ctors are duplicate features (and .init_array is newer.) However, there
466 // are too many real-world use cases of .ctors, so we had no choice to
467 // support that with this rather ad-hoc semantics.
compCtors(const InputSection * a,const InputSection * b)468 static bool compCtors(const InputSection *a, const InputSection *b) {
469   bool beginA = isCrtbegin(a->file->getName());
470   bool beginB = isCrtbegin(b->file->getName());
471   if (beginA != beginB)
472     return beginA;
473   bool endA = isCrtend(a->file->getName());
474   bool endB = isCrtend(b->file->getName());
475   if (endA != endB)
476     return endB;
477   return getPriority(a->name) > getPriority(b->name);
478 }
479 
480 // Sorts input sections by the special rules for .ctors and .dtors.
481 // Unfortunately, the rules are different from the one for .{init,fini}_array.
482 // Read the comment above.
sortCtorsDtors()483 void OutputSection::sortCtorsDtors() {
484   assert(sectionCommands.size() == 1);
485   auto *isd = cast<InputSectionDescription>(sectionCommands[0]);
486   llvm::stable_sort(isd->sections, compCtors);
487 }
488 
489 // If an input string is in the form of "foo.N" where N is a number, return N
490 // (65535-N if .ctors.N or .dtors.N). Otherwise, returns 65536, which is one
491 // greater than the lowest priority.
getPriority(StringRef s)492 int elf::getPriority(StringRef s) {
493   size_t pos = s.rfind('.');
494   if (pos == StringRef::npos)
495     return 65536;
496   int v = 65536;
497   if (to_integer(s.substr(pos + 1), v, 10) &&
498       (pos == 6 && (s.startswith(".ctors") || s.startswith(".dtors"))))
499     v = 65535 - v;
500   return v;
501 }
502 
getFirstInputSection(const OutputSection * os)503 InputSection *elf::getFirstInputSection(const OutputSection *os) {
504   for (BaseCommand *base : os->sectionCommands)
505     if (auto *isd = dyn_cast<InputSectionDescription>(base))
506       if (!isd->sections.empty())
507         return isd->sections[0];
508   return nullptr;
509 }
510 
getInputSections(const OutputSection * os)511 std::vector<InputSection *> elf::getInputSections(const OutputSection *os) {
512   std::vector<InputSection *> ret;
513   for (BaseCommand *base : os->sectionCommands)
514     if (auto *isd = dyn_cast<InputSectionDescription>(base))
515       ret.insert(ret.end(), isd->sections.begin(), isd->sections.end());
516   return ret;
517 }
518 
519 // Sorts input sections by section name suffixes, so that .foo.N comes
520 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
521 // We want to keep the original order if the priorities are the same
522 // because the compiler keeps the original initialization order in a
523 // translation unit and we need to respect that.
524 // For more detail, read the section of the GCC's manual about init_priority.
sortInitFini()525 void OutputSection::sortInitFini() {
526   // Sort sections by priority.
527   sort([](InputSectionBase *s) { return getPriority(s->name); });
528 }
529 
getFiller()530 std::array<uint8_t, 4> OutputSection::getFiller() {
531   if (filler)
532     return *filler;
533   if (flags & SHF_EXECINSTR)
534     return target->trapInstr;
535   return {0, 0, 0, 0};
536 }
537 
538 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
539 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
540 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
541 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
542 
543 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf);
544 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf);
545 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf);
546 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf);
547 
548 template void OutputSection::maybeCompress<ELF32LE>();
549 template void OutputSection::maybeCompress<ELF32BE>();
550 template void OutputSection::maybeCompress<ELF64LE>();
551 template void OutputSection::maybeCompress<ELF64BE>();
552