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/Arrays.h"
16 #include "lld/Common/Memory.h"
17 #include "lld/Common/Strings.h"
18 #include "llvm/BinaryFormat/Dwarf.h"
19 #include "llvm/Config/llvm-config.h" // LLVM_ENABLE_ZLIB
20 #include "llvm/Support/MD5.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/Parallel.h"
23 #include "llvm/Support/SHA1.h"
24 #include "llvm/Support/TimeProfiler.h"
25 #if LLVM_ENABLE_ZLIB
26 #include <zlib.h>
27 #endif
28 
29 using namespace llvm;
30 using namespace llvm::dwarf;
31 using namespace llvm::object;
32 using namespace llvm::support::endian;
33 using namespace llvm::ELF;
34 using namespace lld;
35 using namespace lld::elf;
36 
37 uint8_t *Out::bufferStart;
38 PhdrEntry *Out::tlsPhdr;
39 OutputSection *Out::elfHeader;
40 OutputSection *Out::programHeaders;
41 OutputSection *Out::preinitArray;
42 OutputSection *Out::initArray;
43 OutputSection *Out::finiArray;
44 
45 SmallVector<OutputSection *, 0> elf::outputSections;
46 
47 uint32_t OutputSection::getPhdrFlags() const {
48   uint32_t ret = 0;
49   if (config->emachine != EM_ARM || !(flags & SHF_ARM_PURECODE))
50     ret |= PF_R;
51   if (flags & SHF_WRITE)
52     ret |= PF_W;
53   if (flags & SHF_EXECINSTR)
54     ret |= PF_X;
55   return ret;
56 }
57 
58 template <class ELFT>
59 void OutputSection::writeHeaderTo(typename ELFT::Shdr *shdr) {
60   shdr->sh_entsize = entsize;
61   shdr->sh_addralign = alignment;
62   shdr->sh_type = type;
63   shdr->sh_offset = offset;
64   shdr->sh_flags = flags;
65   shdr->sh_info = info;
66   shdr->sh_link = link;
67   shdr->sh_addr = addr;
68   shdr->sh_size = size;
69   shdr->sh_name = shName;
70 }
71 
72 OutputSection::OutputSection(StringRef name, uint32_t type, uint64_t flags)
73     : SectionCommand(OutputSectionKind),
74       SectionBase(Output, name, flags, /*Entsize*/ 0, /*Alignment*/ 1, type,
75                   /*Info*/ 0, /*Link*/ 0) {}
76 
77 // We allow sections of types listed below to merged into a
78 // single progbits section. This is typically done by linker
79 // scripts. Merging nobits and progbits will force disk space
80 // to be allocated for nobits sections. Other ones don't require
81 // any special treatment on top of progbits, so there doesn't
82 // seem to be a harm in merging them.
83 //
84 // NOTE: clang since rL252300 emits SHT_X86_64_UNWIND .eh_frame sections. Allow
85 // them to be merged into SHT_PROGBITS .eh_frame (GNU as .cfi_*).
86 static bool canMergeToProgbits(unsigned type) {
87   return type == SHT_NOBITS || type == SHT_PROGBITS || type == SHT_INIT_ARRAY ||
88          type == SHT_PREINIT_ARRAY || type == SHT_FINI_ARRAY ||
89          type == SHT_NOTE ||
90          (type == SHT_X86_64_UNWIND && config->emachine == EM_X86_64);
91 }
92 
93 // Record that isec will be placed in the OutputSection. isec does not become
94 // permanent until finalizeInputSections() is called. The function should not be
95 // used after finalizeInputSections() is called. If you need to add an
96 // InputSection post finalizeInputSections(), then you must do the following:
97 //
98 // 1. Find or create an InputSectionDescription to hold InputSection.
99 // 2. Add the InputSection to the InputSectionDescription::sections.
100 // 3. Call commitSection(isec).
101 void OutputSection::recordSection(InputSectionBase *isec) {
102   partition = isec->partition;
103   isec->parent = this;
104   if (commands.empty() || !isa<InputSectionDescription>(commands.back()))
105     commands.push_back(make<InputSectionDescription>(""));
106   auto *isd = cast<InputSectionDescription>(commands.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.
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 static MergeSyntheticSection *createMergeSynthetic(StringRef name,
161                                                    uint32_t type,
162                                                    uint64_t flags,
163                                                    uint32_t alignment) {
164   if ((flags & SHF_STRINGS) && config->optimize >= 2)
165     return make<MergeTailSection>(name, type, flags, alignment);
166   return make<MergeNoTailSection>(name, type, flags, alignment);
167 }
168 
169 // This function scans over the InputSectionBase list sectionBases to create
170 // InputSectionDescription::sections.
171 //
172 // It removes MergeInputSections from the input section array and adds
173 // new synthetic sections at the location of the first input section
174 // that it replaces. It then finalizes each synthetic section in order
175 // to compute an output offset for each piece of each input section.
176 void OutputSection::finalizeInputSections() {
177   std::vector<MergeSyntheticSection *> mergeSections;
178   for (SectionCommand *cmd : commands) {
179     auto *isd = dyn_cast<InputSectionDescription>(cmd);
180     if (!isd)
181       continue;
182     isd->sections.reserve(isd->sectionBases.size());
183     for (InputSectionBase *s : isd->sectionBases) {
184       MergeInputSection *ms = dyn_cast<MergeInputSection>(s);
185       if (!ms) {
186         isd->sections.push_back(cast<InputSection>(s));
187         continue;
188       }
189 
190       // We do not want to handle sections that are not alive, so just remove
191       // them instead of trying to merge.
192       if (!ms->isLive())
193         continue;
194 
195       auto i = llvm::find_if(mergeSections, [=](MergeSyntheticSection *sec) {
196         // While we could create a single synthetic section for two different
197         // values of Entsize, it is better to take Entsize into consideration.
198         //
199         // With a single synthetic section no two pieces with different Entsize
200         // could be equal, so we may as well have two sections.
201         //
202         // Using Entsize in here also allows us to propagate it to the synthetic
203         // section.
204         //
205         // SHF_STRINGS section with different alignments should not be merged.
206         return sec->flags == ms->flags && sec->entsize == ms->entsize &&
207                (sec->alignment == ms->alignment || !(sec->flags & SHF_STRINGS));
208       });
209       if (i == mergeSections.end()) {
210         MergeSyntheticSection *syn =
211             createMergeSynthetic(name, ms->type, ms->flags, ms->alignment);
212         mergeSections.push_back(syn);
213         i = std::prev(mergeSections.end());
214         syn->entsize = ms->entsize;
215         isd->sections.push_back(syn);
216       }
217       (*i)->addSection(ms);
218     }
219 
220     // sectionBases should not be used from this point onwards. Clear it to
221     // catch misuses.
222     isd->sectionBases.clear();
223 
224     // Some input sections may be removed from the list after ICF.
225     for (InputSection *s : isd->sections)
226       commitSection(s);
227   }
228   for (auto *ms : mergeSections)
229     ms->finalizeContents();
230 }
231 
232 static void sortByOrder(MutableArrayRef<InputSection *> in,
233                         llvm::function_ref<int(InputSectionBase *s)> order) {
234   std::vector<std::pair<int, InputSection *>> v;
235   for (InputSection *s : in)
236     v.push_back({order(s), s});
237   llvm::stable_sort(v, less_first());
238 
239   for (size_t i = 0; i < v.size(); ++i)
240     in[i] = v[i].second;
241 }
242 
243 uint64_t elf::getHeaderSize() {
244   if (config->oFormatBinary)
245     return 0;
246   return Out::elfHeader->size + Out::programHeaders->size;
247 }
248 
249 bool OutputSection::classof(const SectionCommand *c) {
250   return c->kind == OutputSectionKind;
251 }
252 
253 void OutputSection::sort(llvm::function_ref<int(InputSectionBase *s)> order) {
254   assert(isLive());
255   for (SectionCommand *b : commands)
256     if (auto *isd = dyn_cast<InputSectionDescription>(b))
257       sortByOrder(isd->sections, order);
258 }
259 
260 static void nopInstrFill(uint8_t *buf, size_t size) {
261   if (size == 0)
262     return;
263   unsigned i = 0;
264   if (size == 0)
265     return;
266   std::vector<std::vector<uint8_t>> nopFiller = *target->nopInstrs;
267   unsigned num = size / nopFiller.back().size();
268   for (unsigned c = 0; c < num; ++c) {
269     memcpy(buf + i, nopFiller.back().data(), nopFiller.back().size());
270     i += nopFiller.back().size();
271   }
272   unsigned remaining = size - i;
273   if (!remaining)
274     return;
275   assert(nopFiller[remaining - 1].size() == remaining);
276   memcpy(buf + i, nopFiller[remaining - 1].data(), remaining);
277 }
278 
279 // Fill [Buf, Buf + Size) with Filler.
280 // This is used for linker script "=fillexp" command.
281 static void fill(uint8_t *buf, size_t size,
282                  const std::array<uint8_t, 4> &filler) {
283   size_t i = 0;
284   for (; i + 4 < size; i += 4)
285     memcpy(buf + i, filler.data(), 4);
286   memcpy(buf + i, filler.data(), size - i);
287 }
288 
289 #if LLVM_ENABLE_ZLIB
290 static SmallVector<uint8_t, 0> deflateShard(ArrayRef<uint8_t> in, int level,
291                                             int flush) {
292   // 15 and 8 are default. windowBits=-15 is negative to generate raw deflate
293   // data with no zlib header or trailer.
294   z_stream s = {};
295   deflateInit2(&s, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);
296   s.next_in = const_cast<uint8_t *>(in.data());
297   s.avail_in = in.size();
298 
299   // Allocate a buffer of half of the input size, and grow it by 1.5x if
300   // insufficient.
301   SmallVector<uint8_t, 0> out;
302   size_t pos = 0;
303   out.resize_for_overwrite(std::max<size_t>(in.size() / 2, 64));
304   do {
305     if (pos == out.size())
306       out.resize_for_overwrite(out.size() * 3 / 2);
307     s.next_out = out.data() + pos;
308     s.avail_out = out.size() - pos;
309     (void)deflate(&s, flush);
310     pos = s.next_out - out.data();
311   } while (s.avail_out == 0);
312   assert(s.avail_in == 0);
313 
314   out.truncate(pos);
315   deflateEnd(&s);
316   return out;
317 }
318 #endif
319 
320 // Compress section contents if this section contains debug info.
321 template <class ELFT> void OutputSection::maybeCompress() {
322 #if LLVM_ENABLE_ZLIB
323   using Elf_Chdr = typename ELFT::Chdr;
324 
325   // Compress only DWARF debug sections.
326   if (!config->compressDebugSections || (flags & SHF_ALLOC) ||
327       !name.startswith(".debug_") || size == 0)
328     return;
329 
330   llvm::TimeTraceScope timeScope("Compress debug sections");
331 
332   // Write uncompressed data to a temporary zero-initialized buffer.
333   auto buf = std::make_unique<uint8_t[]>(size);
334   writeTo<ELFT>(buf.get());
335   // We chose 1 (Z_BEST_SPEED) as the default compression level because it is
336   // the fastest. If -O2 is given, we use level 6 to compress debug info more by
337   // ~15%. We found that level 7 to 9 doesn't make much difference (~1% more
338   // compression) while they take significant amount of time (~2x), so level 6
339   // seems enough.
340   const int level = config->optimize >= 2 ? 6 : Z_BEST_SPEED;
341 
342   // Split input into 1-MiB shards.
343   constexpr size_t shardSize = 1 << 20;
344   auto shardsIn = split(makeArrayRef<uint8_t>(buf.get(), size), shardSize);
345   const size_t numShards = shardsIn.size();
346 
347   // Compress shards and compute Alder-32 checksums. Use Z_SYNC_FLUSH for all
348   // shards but the last to flush the output to a byte boundary to be
349   // concatenated with the next shard.
350   auto shardsOut = std::make_unique<SmallVector<uint8_t, 0>[]>(numShards);
351   auto shardsAdler = std::make_unique<uint32_t[]>(numShards);
352   parallelForEachN(0, numShards, [&](size_t i) {
353     shardsOut[i] = deflateShard(shardsIn[i], level,
354                                 i != numShards - 1 ? Z_SYNC_FLUSH : Z_FINISH);
355     shardsAdler[i] = adler32(1, shardsIn[i].data(), shardsIn[i].size());
356   });
357 
358   // Update section size and combine Alder-32 checksums.
359   uint32_t checksum = 1;       // Initial Adler-32 value
360   compressed.uncompressedSize = size;
361   size = sizeof(Elf_Chdr) + 2; // Elf_Chdir and zlib header
362   for (size_t i = 0; i != numShards; ++i) {
363     size += shardsOut[i].size();
364     checksum = adler32_combine(checksum, shardsAdler[i], shardsIn[i].size());
365   }
366   size += 4; // checksum
367 
368   compressed.shards = std::move(shardsOut);
369   compressed.numShards = numShards;
370   compressed.checksum = checksum;
371   flags |= SHF_COMPRESSED;
372 #endif
373 }
374 
375 static void writeInt(uint8_t *buf, uint64_t data, uint64_t size) {
376   if (size == 1)
377     *buf = data;
378   else if (size == 2)
379     write16(buf, data);
380   else if (size == 4)
381     write32(buf, data);
382   else if (size == 8)
383     write64(buf, data);
384   else
385     llvm_unreachable("unsupported Size argument");
386 }
387 
388 template <class ELFT> void OutputSection::writeTo(uint8_t *buf) {
389   llvm::TimeTraceScope timeScope("Write sections", name);
390   if (type == SHT_NOBITS)
391     return;
392 
393   // If --compress-debug-section is specified and if this is a debug section,
394   // we've already compressed section contents. If that's the case,
395   // just write it down.
396   if (compressed.shards) {
397     auto *chdr = reinterpret_cast<typename ELFT::Chdr *>(buf);
398     chdr->ch_type = ELFCOMPRESS_ZLIB;
399     chdr->ch_size = compressed.uncompressedSize;
400     chdr->ch_addralign = alignment;
401     buf += sizeof(*chdr);
402 
403     // Compute shard offsets.
404     auto offsets = std::make_unique<size_t[]>(compressed.numShards);
405     offsets[0] = 2; // zlib header
406     for (size_t i = 1; i != compressed.numShards; ++i)
407       offsets[i] = offsets[i - 1] + compressed.shards[i - 1].size();
408 
409     buf[0] = 0x78; // CMF
410     buf[1] = 0x01; // FLG: best speed
411     parallelForEachN(0, compressed.numShards, [&](size_t i) {
412       memcpy(buf + offsets[i], compressed.shards[i].data(),
413              compressed.shards[i].size());
414     });
415 
416     write32be(buf + (size - sizeof(*chdr) - 4), compressed.checksum);
417     return;
418   }
419 
420   // Write leading padding.
421   SmallVector<InputSection *, 0> sections = getInputSections(*this);
422   std::array<uint8_t, 4> filler = getFiller();
423   bool nonZeroFiller = read32(filler.data()) != 0;
424   if (nonZeroFiller)
425     fill(buf, sections.empty() ? size : sections[0]->outSecOff, filler);
426 
427   parallelForEachN(0, sections.size(), [&](size_t i) {
428     InputSection *isec = sections[i];
429     isec->writeTo<ELFT>(buf + isec->outSecOff);
430 
431     // Fill gaps between sections.
432     if (nonZeroFiller) {
433       uint8_t *start = buf + isec->outSecOff + isec->getSize();
434       uint8_t *end;
435       if (i + 1 == sections.size())
436         end = buf + size;
437       else
438         end = buf + sections[i + 1]->outSecOff;
439       if (isec->nopFiller) {
440         assert(target->nopInstrs);
441         nopInstrFill(start, end - start);
442       } else
443         fill(start, end - start, filler);
444     }
445   });
446 
447   // Linker scripts may have BYTE()-family commands with which you
448   // can write arbitrary bytes to the output. Process them if any.
449   for (SectionCommand *cmd : commands)
450     if (auto *data = dyn_cast<ByteCommand>(cmd))
451       writeInt(buf + data->offset, data->expression().getValue(), data->size);
452 }
453 
454 static void finalizeShtGroup(OutputSection *os,
455                              InputSection *section) {
456   assert(config->relocatable);
457 
458   // sh_link field for SHT_GROUP sections should contain the section index of
459   // the symbol table.
460   os->link = in.symTab->getParent()->sectionIndex;
461 
462   // sh_info then contain index of an entry in symbol table section which
463   // provides signature of the section group.
464   ArrayRef<Symbol *> symbols = section->file->getSymbols();
465   os->info = in.symTab->getSymbolIndex(symbols[section->info]);
466 
467   // Some group members may be combined or discarded, so we need to compute the
468   // new size. The content will be rewritten in InputSection::copyShtGroup.
469   DenseSet<uint32_t> seen;
470   ArrayRef<InputSectionBase *> sections = section->file->getSections();
471   for (const uint32_t &idx : section->getDataAs<uint32_t>().slice(1))
472     if (OutputSection *osec = sections[read32(&idx)]->getOutputSection())
473       seen.insert(osec->sectionIndex);
474   os->size = (1 + seen.size()) * sizeof(uint32_t);
475 }
476 
477 void OutputSection::finalize() {
478   InputSection *first = getFirstInputSection(this);
479 
480   if (flags & SHF_LINK_ORDER) {
481     // We must preserve the link order dependency of sections with the
482     // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
483     // need to translate the InputSection sh_link to the OutputSection sh_link,
484     // all InputSections in the OutputSection have the same dependency.
485     if (auto *ex = dyn_cast<ARMExidxSyntheticSection>(first))
486       link = ex->getLinkOrderDep()->getParent()->sectionIndex;
487     else if (first->flags & SHF_LINK_ORDER)
488       if (auto *d = first->getLinkOrderDep())
489         link = d->getParent()->sectionIndex;
490   }
491 
492   if (type == SHT_GROUP) {
493     finalizeShtGroup(this, first);
494     return;
495   }
496 
497   if (!config->copyRelocs || (type != SHT_RELA && type != SHT_REL))
498     return;
499 
500   // Skip if 'first' is synthetic, i.e. not a section created by --emit-relocs.
501   // Normally 'type' was changed by 'first' so 'first' should be non-null.
502   // However, if the output section is .rela.dyn, 'type' can be set by the empty
503   // synthetic .rela.plt and first can be null.
504   if (!first || isa<SyntheticSection>(first))
505     return;
506 
507   link = in.symTab->getParent()->sectionIndex;
508   // sh_info for SHT_REL[A] sections should contain the section header index of
509   // the section to which the relocation applies.
510   InputSectionBase *s = first->getRelocatedSection();
511   info = s->getOutputSection()->sectionIndex;
512   flags |= SHF_INFO_LINK;
513 }
514 
515 // Returns true if S is in one of the many forms the compiler driver may pass
516 // crtbegin files.
517 //
518 // Gcc uses any of crtbegin[<empty>|S|T].o.
519 // Clang uses Gcc's plus clang_rt.crtbegin[-<arch>|<empty>].o.
520 
521 static bool isCrt(StringRef s, StringRef beginEnd) {
522   s = sys::path::filename(s);
523   if (!s.consume_back(".o"))
524     return false;
525   if (s.consume_front("clang_rt."))
526     return s.consume_front(beginEnd);
527   return s.consume_front(beginEnd) && s.size() <= 1;
528 }
529 
530 // .ctors and .dtors are sorted by this order:
531 //
532 // 1. .ctors/.dtors in crtbegin (which contains a sentinel value -1).
533 // 2. The section is named ".ctors" or ".dtors" (priority: 65536).
534 // 3. The section has an optional priority value in the form of ".ctors.N" or
535 //    ".dtors.N" where N is a number in the form of %05u (priority: 65535-N).
536 // 4. .ctors/.dtors in crtend (which contains a sentinel value 0).
537 //
538 // For 2 and 3, the sections are sorted by priority from high to low, e.g.
539 // .ctors (65536), .ctors.00100 (65436), .ctors.00200 (65336).  In GNU ld's
540 // internal linker scripts, the sorting is by string comparison which can
541 // achieve the same goal given the optional priority values are of the same
542 // length.
543 //
544 // In an ideal world, we don't need this function because .init_array and
545 // .ctors are duplicate features (and .init_array is newer.) However, there
546 // are too many real-world use cases of .ctors, so we had no choice to
547 // support that with this rather ad-hoc semantics.
548 static bool compCtors(const InputSection *a, const InputSection *b) {
549   bool beginA = isCrt(a->file->getName(), "crtbegin");
550   bool beginB = isCrt(b->file->getName(), "crtbegin");
551   if (beginA != beginB)
552     return beginA;
553   bool endA = isCrt(a->file->getName(), "crtend");
554   bool endB = isCrt(b->file->getName(), "crtend");
555   if (endA != endB)
556     return endB;
557   return getPriority(a->name) > getPriority(b->name);
558 }
559 
560 // Sorts input sections by the special rules for .ctors and .dtors.
561 // Unfortunately, the rules are different from the one for .{init,fini}_array.
562 // Read the comment above.
563 void OutputSection::sortCtorsDtors() {
564   assert(commands.size() == 1);
565   auto *isd = cast<InputSectionDescription>(commands[0]);
566   llvm::stable_sort(isd->sections, compCtors);
567 }
568 
569 // If an input string is in the form of "foo.N" where N is a number, return N
570 // (65535-N if .ctors.N or .dtors.N). Otherwise, returns 65536, which is one
571 // greater than the lowest priority.
572 int elf::getPriority(StringRef s) {
573   size_t pos = s.rfind('.');
574   if (pos == StringRef::npos)
575     return 65536;
576   int v = 65536;
577   if (to_integer(s.substr(pos + 1), v, 10) &&
578       (pos == 6 && (s.startswith(".ctors") || s.startswith(".dtors"))))
579     v = 65535 - v;
580   return v;
581 }
582 
583 InputSection *elf::getFirstInputSection(const OutputSection *os) {
584   for (SectionCommand *cmd : os->commands)
585     if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
586       if (!isd->sections.empty())
587         return isd->sections[0];
588   return nullptr;
589 }
590 
591 SmallVector<InputSection *, 0> elf::getInputSections(const OutputSection &os) {
592   SmallVector<InputSection *, 0> ret;
593   for (SectionCommand *cmd : os.commands)
594     if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
595       ret.insert(ret.end(), isd->sections.begin(), isd->sections.end());
596   return ret;
597 }
598 
599 // Sorts input sections by section name suffixes, so that .foo.N comes
600 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
601 // We want to keep the original order if the priorities are the same
602 // because the compiler keeps the original initialization order in a
603 // translation unit and we need to respect that.
604 // For more detail, read the section of the GCC's manual about init_priority.
605 void OutputSection::sortInitFini() {
606   // Sort sections by priority.
607   sort([](InputSectionBase *s) { return getPriority(s->name); });
608 }
609 
610 std::array<uint8_t, 4> OutputSection::getFiller() {
611   if (filler)
612     return *filler;
613   if (flags & SHF_EXECINSTR)
614     return target->trapInstr;
615   return {0, 0, 0, 0};
616 }
617 
618 void OutputSection::checkDynRelAddends(const uint8_t *bufStart) {
619   assert(config->writeAddends && config->checkDynamicRelocs);
620   assert(type == SHT_REL || type == SHT_RELA);
621   SmallVector<InputSection *, 0> sections = getInputSections(*this);
622   parallelForEachN(0, sections.size(), [&](size_t i) {
623     // When linking with -r or --emit-relocs we might also call this function
624     // for input .rel[a].<sec> sections which we simply pass through to the
625     // output. We skip over those and only look at the synthetic relocation
626     // sections created during linking.
627     const auto *sec = dyn_cast<RelocationBaseSection>(sections[i]);
628     if (!sec)
629       return;
630     for (const DynamicReloc &rel : sec->relocs) {
631       int64_t addend = rel.addend;
632       const OutputSection *relOsec = rel.inputSec->getOutputSection();
633       assert(relOsec != nullptr && "missing output section for relocation");
634       const uint8_t *relocTarget =
635           bufStart + relOsec->offset + rel.inputSec->getOffset(rel.offsetInSec);
636       // For SHT_NOBITS the written addend is always zero.
637       int64_t writtenAddend =
638           relOsec->type == SHT_NOBITS
639               ? 0
640               : target->getImplicitAddend(relocTarget, rel.type);
641       if (addend != writtenAddend)
642         internalLinkerError(
643             getErrorLocation(relocTarget),
644             "wrote incorrect addend value 0x" + utohexstr(writtenAddend) +
645                 " instead of 0x" + utohexstr(addend) +
646                 " for dynamic relocation " + toString(rel.type) +
647                 " at offset 0x" + utohexstr(rel.getOffset()) +
648                 (rel.sym ? " against symbol " + toString(*rel.sym) : ""));
649     }
650   });
651 }
652 
653 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
654 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
655 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
656 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
657 
658 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf);
659 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf);
660 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf);
661 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf);
662 
663 template void OutputSection::maybeCompress<ELF32LE>();
664 template void OutputSection::maybeCompress<ELF32BE>();
665 template void OutputSection::maybeCompress<ELF64LE>();
666 template void OutputSection::maybeCompress<ELF64BE>();
667