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