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