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