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 "lld/Common/Threads.h"
18 #include "llvm/BinaryFormat/Dwarf.h"
19 #include "llvm/Support/Compression.h"
20 #include "llvm/Support/MD5.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/SHA1.h"
23 
24 using namespace llvm;
25 using namespace llvm::dwarf;
26 using namespace llvm::object;
27 using namespace llvm::support::endian;
28 using namespace llvm::ELF;
29 
30 using namespace lld;
31 using namespace lld::elf;
32 
33 uint8_t *Out::BufferStart;
34 uint8_t Out::First;
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 std::vector<OutputSection *> 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     : BaseCommand(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 static bool canMergeToProgbits(unsigned Type) {
81   return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY ||
82          Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY ||
83          Type == SHT_NOTE;
84 }
85 
86 void OutputSection::addSection(InputSection *IS) {
87   if (!Live) {
88     // If IS is the first section to be added to this section,
89     // initialize Type, Entsize and flags from IS.
90     Live = true;
91     Type = IS->Type;
92     Entsize = IS->Entsize;
93     Flags = IS->Flags;
94   } else {
95     // Otherwise, check if new type or flags are compatible with existing ones.
96     unsigned Mask = SHF_TLS | SHF_LINK_ORDER;
97     if ((Flags & Mask) != (IS->Flags & Mask))
98       error("incompatible section flags for " + Name + "\n>>> " + toString(IS) +
99             ": 0x" + utohexstr(IS->Flags) + "\n>>> output section " + Name +
100             ": 0x" + utohexstr(Flags));
101 
102     if (Type != IS->Type) {
103       if (!canMergeToProgbits(Type) || !canMergeToProgbits(IS->Type))
104         error("section type mismatch for " + IS->Name + "\n>>> " +
105               toString(IS) + ": " +
106               getELFSectionTypeName(Config->EMachine, IS->Type) +
107               "\n>>> output section " + Name + ": " +
108               getELFSectionTypeName(Config->EMachine, Type));
109       Type = SHT_PROGBITS;
110     }
111   }
112 
113   IS->Parent = this;
114   uint64_t AndMask =
115       Config->EMachine == EM_ARM ? (uint64_t)SHF_ARM_PURECODE : 0;
116   uint64_t OrMask = ~AndMask;
117   uint64_t AndFlags = (Flags & IS->Flags) & AndMask;
118   uint64_t OrFlags = (Flags | IS->Flags) & OrMask;
119   Flags = AndFlags | OrFlags;
120 
121   Alignment = std::max(Alignment, IS->Alignment);
122 
123   // If this section contains a table of fixed-size entries, sh_entsize
124   // holds the element size. If it contains elements of different size we
125   // set sh_entsize to 0.
126   if (Entsize != IS->Entsize)
127     Entsize = 0;
128 
129   if (!IS->Assigned) {
130     IS->Assigned = true;
131     if (SectionCommands.empty() ||
132         !isa<InputSectionDescription>(SectionCommands.back()))
133       SectionCommands.push_back(make<InputSectionDescription>(""));
134     auto *ISD = cast<InputSectionDescription>(SectionCommands.back());
135     ISD->Sections.push_back(IS);
136   }
137 }
138 
139 static void sortByOrder(MutableArrayRef<InputSection *> In,
140                         llvm::function_ref<int(InputSectionBase *S)> Order) {
141   std::vector<std::pair<int, InputSection *>> V;
142   for (InputSection *S : In)
143     V.push_back({Order(S), S});
144   llvm::stable_sort(V, less_first());
145 
146   for (size_t I = 0; I < V.size(); ++I)
147     In[I] = V[I].second;
148 }
149 
150 uint64_t elf::getHeaderSize() {
151   if (Config->OFormatBinary)
152     return 0;
153   return Out::ElfHeader->Size + Out::ProgramHeaders->Size;
154 }
155 
156 bool OutputSection::classof(const BaseCommand *C) {
157   return C->Kind == OutputSectionKind;
158 }
159 
160 void OutputSection::sort(llvm::function_ref<int(InputSectionBase *S)> Order) {
161   assert(Live);
162   for (BaseCommand *B : SectionCommands)
163     if (auto *ISD = dyn_cast<InputSectionDescription>(B))
164       sortByOrder(ISD->Sections, Order);
165 }
166 
167 // Fill [Buf, Buf + Size) with Filler.
168 // This is used for linker script "=fillexp" command.
169 static void fill(uint8_t *Buf, size_t Size,
170                  const std::array<uint8_t, 4> &Filler) {
171   size_t I = 0;
172   for (; I + 4 < Size; I += 4)
173     memcpy(Buf + I, Filler.data(), 4);
174   memcpy(Buf + I, Filler.data(), Size - I);
175 }
176 
177 // Compress section contents if this section contains debug info.
178 template <class ELFT> void OutputSection::maybeCompress() {
179   using Elf_Chdr = typename ELFT::Chdr;
180 
181   // Compress only DWARF debug sections.
182   if (!Config->CompressDebugSections || (Flags & SHF_ALLOC) ||
183       !Name.startswith(".debug_"))
184     return;
185 
186   // Create a section header.
187   ZDebugHeader.resize(sizeof(Elf_Chdr));
188   auto *Hdr = reinterpret_cast<Elf_Chdr *>(ZDebugHeader.data());
189   Hdr->ch_type = ELFCOMPRESS_ZLIB;
190   Hdr->ch_size = Size;
191   Hdr->ch_addralign = Alignment;
192 
193   // Write section contents to a temporary buffer and compress it.
194   std::vector<uint8_t> Buf(Size);
195   writeTo<ELFT>(Buf.data());
196   if (Error E = zlib::compress(toStringRef(Buf), CompressedData))
197     fatal("compress failed: " + llvm::toString(std::move(E)));
198 
199   // Update section headers.
200   Size = sizeof(Elf_Chdr) + CompressedData.size();
201   Flags |= SHF_COMPRESSED;
202 }
203 
204 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
205   if (Size == 1)
206     *Buf = Data;
207   else if (Size == 2)
208     write16(Buf, Data);
209   else if (Size == 4)
210     write32(Buf, Data);
211   else if (Size == 8)
212     write64(Buf, Data);
213   else
214     llvm_unreachable("unsupported Size argument");
215 }
216 
217 template <class ELFT> void OutputSection::writeTo(uint8_t *Buf) {
218   if (Type == SHT_NOBITS)
219     return;
220 
221   // If -compress-debug-section is specified and if this is a debug seciton,
222   // we've already compressed section contents. If that's the case,
223   // just write it down.
224   if (!CompressedData.empty()) {
225     memcpy(Buf, ZDebugHeader.data(), ZDebugHeader.size());
226     memcpy(Buf + ZDebugHeader.size(), CompressedData.data(),
227            CompressedData.size());
228     return;
229   }
230 
231   // Write leading padding.
232   std::vector<InputSection *> Sections = getInputSections(this);
233   std::array<uint8_t, 4> Filler = getFiller();
234   bool NonZeroFiller = read32(Filler.data()) != 0;
235   if (NonZeroFiller)
236     fill(Buf, Sections.empty() ? Size : Sections[0]->OutSecOff, Filler);
237 
238   parallelForEachN(0, Sections.size(), [&](size_t I) {
239     InputSection *IS = Sections[I];
240     IS->writeTo<ELFT>(Buf);
241 
242     // Fill gaps between sections.
243     if (NonZeroFiller) {
244       uint8_t *Start = Buf + IS->OutSecOff + IS->getSize();
245       uint8_t *End;
246       if (I + 1 == Sections.size())
247         End = Buf + Size;
248       else
249         End = Buf + Sections[I + 1]->OutSecOff;
250       fill(Start, End - Start, Filler);
251     }
252   });
253 
254   // Linker scripts may have BYTE()-family commands with which you
255   // can write arbitrary bytes to the output. Process them if any.
256   for (BaseCommand *Base : SectionCommands)
257     if (auto *Data = dyn_cast<ByteCommand>(Base))
258       writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
259 }
260 
261 static void finalizeShtGroup(OutputSection *OS,
262                              InputSection *Section) {
263   assert(Config->Relocatable);
264 
265   // sh_link field for SHT_GROUP sections should contain the section index of
266   // the symbol table.
267   OS->Link = In.SymTab->getParent()->SectionIndex;
268 
269   // sh_info then contain index of an entry in symbol table section which
270   // provides signature of the section group.
271   ArrayRef<Symbol *> Symbols = Section->File->getSymbols();
272   OS->Info = In.SymTab->getSymbolIndex(Symbols[Section->Info]);
273 }
274 
275 void OutputSection::finalize() {
276   if (Type == SHT_NOBITS)
277     for (BaseCommand *Base : SectionCommands)
278       if (isa<ByteCommand>(Base))
279         Type = SHT_PROGBITS;
280 
281   std::vector<InputSection *> V = getInputSections(this);
282   InputSection *First = V.empty() ? nullptr : V[0];
283 
284   if (Flags & SHF_LINK_ORDER) {
285     // We must preserve the link order dependency of sections with the
286     // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
287     // need to translate the InputSection sh_link to the OutputSection sh_link,
288     // all InputSections in the OutputSection have the same dependency.
289     if (auto *EX = dyn_cast<ARMExidxSyntheticSection>(First))
290       Link = EX->getLinkOrderDep()->getParent()->SectionIndex;
291     else if (auto *D = First->getLinkOrderDep())
292       Link = D->getParent()->SectionIndex;
293   }
294 
295   if (Type == SHT_GROUP) {
296     finalizeShtGroup(this, First);
297     return;
298   }
299 
300   if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
301     return;
302 
303   if (isa<SyntheticSection>(First))
304     return;
305 
306   Link = In.SymTab->getParent()->SectionIndex;
307   // sh_info for SHT_REL[A] sections should contain the section header index of
308   // the section to which the relocation applies.
309   InputSectionBase *S = First->getRelocatedSection();
310   Info = S->getOutputSection()->SectionIndex;
311   Flags |= SHF_INFO_LINK;
312 }
313 
314 // Returns true if S matches /Filename.?\.o$/.
315 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
316   if (!S.endswith(".o"))
317     return false;
318   S = S.drop_back(2);
319   if (S.endswith(Filename))
320     return true;
321   return !S.empty() && S.drop_back().endswith(Filename);
322 }
323 
324 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
325 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
326 
327 // .ctors and .dtors are sorted by this priority from highest to lowest.
328 //
329 //  1. The section was contained in crtbegin (crtbegin contains
330 //     some sentinel value in its .ctors and .dtors so that the runtime
331 //     can find the beginning of the sections.)
332 //
333 //  2. The section has an optional priority value in the form of ".ctors.N"
334 //     or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
335 //     they are compared as string rather than number.
336 //
337 //  3. The section is just ".ctors" or ".dtors".
338 //
339 //  4. The section was contained in crtend, which contains an end marker.
340 //
341 // In an ideal world, we don't need this function because .init_array and
342 // .ctors are duplicate features (and .init_array is newer.) However, there
343 // are too many real-world use cases of .ctors, so we had no choice to
344 // support that with this rather ad-hoc semantics.
345 static bool compCtors(const InputSection *A, const InputSection *B) {
346   bool BeginA = isCrtbegin(A->File->getName());
347   bool BeginB = isCrtbegin(B->File->getName());
348   if (BeginA != BeginB)
349     return BeginA;
350   bool EndA = isCrtend(A->File->getName());
351   bool EndB = isCrtend(B->File->getName());
352   if (EndA != EndB)
353     return EndB;
354   StringRef X = A->Name;
355   StringRef Y = B->Name;
356   assert(X.startswith(".ctors") || X.startswith(".dtors"));
357   assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
358   X = X.substr(6);
359   Y = Y.substr(6);
360   return X < Y;
361 }
362 
363 // Sorts input sections by the special rules for .ctors and .dtors.
364 // Unfortunately, the rules are different from the one for .{init,fini}_array.
365 // Read the comment above.
366 void OutputSection::sortCtorsDtors() {
367   assert(SectionCommands.size() == 1);
368   auto *ISD = cast<InputSectionDescription>(SectionCommands[0]);
369   llvm::stable_sort(ISD->Sections, compCtors);
370 }
371 
372 // If an input string is in the form of "foo.N" where N is a number,
373 // return N. Otherwise, returns 65536, which is one greater than the
374 // lowest priority.
375 int elf::getPriority(StringRef S) {
376   size_t Pos = S.rfind('.');
377   if (Pos == StringRef::npos)
378     return 65536;
379   int V;
380   if (!to_integer(S.substr(Pos + 1), V, 10))
381     return 65536;
382   return V;
383 }
384 
385 std::vector<InputSection *> elf::getInputSections(OutputSection *OS) {
386   std::vector<InputSection *> Ret;
387   for (BaseCommand *Base : OS->SectionCommands)
388     if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
389       Ret.insert(Ret.end(), ISD->Sections.begin(), ISD->Sections.end());
390   return Ret;
391 }
392 
393 // Sorts input sections by section name suffixes, so that .foo.N comes
394 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
395 // We want to keep the original order if the priorities are the same
396 // because the compiler keeps the original initialization order in a
397 // translation unit and we need to respect that.
398 // For more detail, read the section of the GCC's manual about init_priority.
399 void OutputSection::sortInitFini() {
400   // Sort sections by priority.
401   sort([](InputSectionBase *S) { return getPriority(S->Name); });
402 }
403 
404 std::array<uint8_t, 4> OutputSection::getFiller() {
405   if (Filler)
406     return *Filler;
407   if (Flags & SHF_EXECINSTR)
408     return Target->TrapInstr;
409   return {0, 0, 0, 0};
410 }
411 
412 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
413 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
414 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
415 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
416 
417 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf);
418 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf);
419 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf);
420 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf);
421 
422 template void OutputSection::maybeCompress<ELF32LE>();
423 template void OutputSection::maybeCompress<ELF32BE>();
424 template void OutputSection::maybeCompress<ELF64LE>();
425 template void OutputSection::maybeCompress<ELF64BE>();
426