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 
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 static void 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   for (BaseCommand *B : SectionCommands)
170     if (auto *ISD = dyn_cast<InputSectionDescription>(B))
171       sortByOrder(ISD->Sections, 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);
215   else if (Size == 4)
216     write32(Buf, Data);
217   else if (Size == 8)
218     write64(Buf, Data);
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 = getInputSections(this);
241   uint32_t Filler = getFiller();
242   if (Filler)
243     fill(Buf, Sections.empty() ? Size : Sections[0]->OutSecOff, Filler);
244 
245   parallelForEachN(0, Sections.size(), [&](size_t I) {
246     InputSection *IS = Sections[I];
247     IS->writeTo<ELFT>(Buf);
248 
249     // Fill gaps between sections.
250     if (Filler) {
251       uint8_t *Start = Buf + IS->OutSecOff + IS->getSize();
252       uint8_t *End;
253       if (I + 1 == Sections.size())
254         End = Buf + Size;
255       else
256         End = Buf + Sections[I + 1]->OutSecOff;
257       fill(Start, End - Start, Filler);
258     }
259   });
260 
261   // Linker scripts may have BYTE()-family commands with which you
262   // can write arbitrary bytes to the output. Process them if any.
263   for (BaseCommand *Base : SectionCommands)
264     if (auto *Data = dyn_cast<ByteCommand>(Base))
265       writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
266 }
267 
268 template <class ELFT>
269 static void finalizeShtGroup(OutputSection *OS,
270                              InputSection *Section) {
271   assert(Config->Relocatable);
272 
273   // sh_link field for SHT_GROUP sections should contain the section index of
274   // the symbol table.
275   OS->Link = InX::SymTab->getParent()->SectionIndex;
276 
277   // sh_info then contain index of an entry in symbol table section which
278   // provides signature of the section group.
279   ObjFile<ELFT> *Obj = Section->getFile<ELFT>();
280   ArrayRef<Symbol *> Symbols = Obj->getSymbols();
281   OS->Info = InX::SymTab->getSymbolIndex(Symbols[Section->Info]);
282 }
283 
284 template <class ELFT> void OutputSection::finalize() {
285   if (Type == SHT_NOBITS)
286     for (BaseCommand *Base : SectionCommands)
287       if (isa<ByteCommand>(Base))
288         Type = SHT_PROGBITS;
289 
290   std::vector<InputSection *> V = getInputSections(this);
291   InputSection *First = V.empty() ? nullptr : V[0];
292 
293   if (Flags & SHF_LINK_ORDER) {
294     // We must preserve the link order dependency of sections with the
295     // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
296     // need to translate the InputSection sh_link to the OutputSection sh_link,
297     // all InputSections in the OutputSection have the same dependency.
298     if (auto *D = First->getLinkOrderDep())
299       Link = D->getParent()->SectionIndex;
300   }
301 
302   if (Type == SHT_GROUP) {
303     finalizeShtGroup<ELFT>(this, First);
304     return;
305   }
306 
307   if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
308     return;
309 
310   if (isa<SyntheticSection>(First))
311     return;
312 
313   Link = InX::SymTab->getParent()->SectionIndex;
314   // sh_info for SHT_REL[A] sections should contain the section header index of
315   // the section to which the relocation applies.
316   InputSectionBase *S = First->getRelocatedSection();
317   Info = S->getOutputSection()->SectionIndex;
318   Flags |= SHF_INFO_LINK;
319 }
320 
321 // Returns true if S matches /Filename.?\.o$/.
322 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
323   if (!S.endswith(".o"))
324     return false;
325   S = S.drop_back(2);
326   if (S.endswith(Filename))
327     return true;
328   return !S.empty() && S.drop_back().endswith(Filename);
329 }
330 
331 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
332 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
333 
334 // .ctors and .dtors are sorted by this priority from highest to lowest.
335 //
336 //  1. The section was contained in crtbegin (crtbegin contains
337 //     some sentinel value in its .ctors and .dtors so that the runtime
338 //     can find the beginning of the sections.)
339 //
340 //  2. The section has an optional priority value in the form of ".ctors.N"
341 //     or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
342 //     they are compared as string rather than number.
343 //
344 //  3. The section is just ".ctors" or ".dtors".
345 //
346 //  4. The section was contained in crtend, which contains an end marker.
347 //
348 // In an ideal world, we don't need this function because .init_array and
349 // .ctors are duplicate features (and .init_array is newer.) However, there
350 // are too many real-world use cases of .ctors, so we had no choice to
351 // support that with this rather ad-hoc semantics.
352 static bool compCtors(const InputSection *A, const InputSection *B) {
353   bool BeginA = isCrtbegin(A->File->getName());
354   bool BeginB = isCrtbegin(B->File->getName());
355   if (BeginA != BeginB)
356     return BeginA;
357   bool EndA = isCrtend(A->File->getName());
358   bool EndB = isCrtend(B->File->getName());
359   if (EndA != EndB)
360     return EndB;
361   StringRef X = A->Name;
362   StringRef Y = B->Name;
363   assert(X.startswith(".ctors") || X.startswith(".dtors"));
364   assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
365   X = X.substr(6);
366   Y = Y.substr(6);
367   return X < Y;
368 }
369 
370 // Sorts input sections by the special rules for .ctors and .dtors.
371 // Unfortunately, the rules are different from the one for .{init,fini}_array.
372 // Read the comment above.
373 void OutputSection::sortCtorsDtors() {
374   assert(SectionCommands.size() == 1);
375   auto *ISD = cast<InputSectionDescription>(SectionCommands[0]);
376   std::stable_sort(ISD->Sections.begin(), ISD->Sections.end(), compCtors);
377 }
378 
379 // If an input string is in the form of "foo.N" where N is a number,
380 // return N. Otherwise, returns 65536, which is one greater than the
381 // lowest priority.
382 int elf::getPriority(StringRef S) {
383   size_t Pos = S.rfind('.');
384   if (Pos == StringRef::npos)
385     return 65536;
386   int V;
387   if (!to_integer(S.substr(Pos + 1), V, 10))
388     return 65536;
389   return V;
390 }
391 
392 std::vector<InputSection *> elf::getInputSections(OutputSection *OS) {
393   std::vector<InputSection *> Ret;
394   for (BaseCommand *Base : OS->SectionCommands)
395     if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
396       Ret.insert(Ret.end(), ISD->Sections.begin(), ISD->Sections.end());
397   return Ret;
398 }
399 
400 // Sorts input sections by section name suffixes, so that .foo.N comes
401 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
402 // We want to keep the original order if the priorities are the same
403 // because the compiler keeps the original initialization order in a
404 // translation unit and we need to respect that.
405 // For more detail, read the section of the GCC's manual about init_priority.
406 void OutputSection::sortInitFini() {
407   // Sort sections by priority.
408   sort([](InputSectionBase *S) { return getPriority(S->Name); });
409 }
410 
411 uint32_t OutputSection::getFiller() {
412   if (Filler)
413     return *Filler;
414   if (Flags & SHF_EXECINSTR)
415     return Target->TrapInstr;
416   return 0;
417 }
418 
419 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
420 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
421 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
422 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
423 
424 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf);
425 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf);
426 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf);
427 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf);
428 
429 template void OutputSection::maybeCompress<ELF32LE>();
430 template void OutputSection::maybeCompress<ELF32BE>();
431 template void OutputSection::maybeCompress<ELF64LE>();
432 template void OutputSection::maybeCompress<ELF64BE>();
433 
434 template void OutputSection::finalize<ELF32LE>();
435 template void OutputSection::finalize<ELF32BE>();
436 template void OutputSection::finalize<ELF64LE>();
437 template void OutputSection::finalize<ELF64BE>();
438