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