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