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