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