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 "Threads.h"
19 #include "llvm/Support/Compression.h"
20 #include "llvm/Support/Dwarf.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 uint32_t OutputSection::getPhdrFlags() const {
46   uint32_t Ret = PF_R;
47   if (Flags & SHF_WRITE)
48     Ret |= PF_W;
49   if (Flags & SHF_EXECINSTR)
50     Ret |= PF_X;
51   return Ret;
52 }
53 
54 template <class ELFT>
55 void OutputSection::writeHeaderTo(typename ELFT::Shdr *Shdr) {
56   Shdr->sh_entsize = Entsize;
57   Shdr->sh_addralign = Alignment;
58   Shdr->sh_type = Type;
59   Shdr->sh_offset = Offset;
60   Shdr->sh_flags = Flags;
61   Shdr->sh_info = Info;
62   Shdr->sh_link = Link;
63   Shdr->sh_addr = Addr;
64   Shdr->sh_size = Size;
65   Shdr->sh_name = ShName;
66 }
67 
68 OutputSection::OutputSection(StringRef Name, uint32_t Type, uint64_t Flags)
69     : SectionBase(Output, Name, Flags, /*Entsize*/ 0, /*Alignment*/ 1, Type,
70                   /*Info*/ 0,
71                   /*Link*/ 0) {}
72 
73 static bool compareByFilePosition(InputSection *A, InputSection *B) {
74   // Synthetic doesn't have link order dependecy, stable_sort will keep it last
75   if (A->kind() == InputSectionBase::Synthetic ||
76       B->kind() == InputSectionBase::Synthetic)
77     return false;
78   auto *LA = cast<InputSection>(A->getLinkOrderDep());
79   auto *LB = cast<InputSection>(B->getLinkOrderDep());
80   OutputSection *AOut = LA->OutSec;
81   OutputSection *BOut = LB->OutSec;
82   if (AOut != BOut)
83     return AOut->SectionIndex < BOut->SectionIndex;
84   return LA->OutSecOff < LB->OutSecOff;
85 }
86 
87 // Compressed sections has header which we create in this function.
88 // Format is explaned here:
89 // https://docs.oracle.com/cd/E53394_01/html/E54813/section_compression.html
90 template <class ELFT>
91 static std::vector<uint8_t> createHeader(size_t Size, uint32_t Alignment) {
92   const endianness E = ELFT::TargetEndianness;
93 
94   std::vector<uint8_t> Ret(sizeof(typename ELFT::Chdr));
95   uint8_t *Buf = &Ret[0];
96   write32<E>(Buf, ELFCOMPRESS_ZLIB);
97   Buf += 4;
98 
99   if (Config->Is64) {
100     Buf += sizeof(Elf64_Word); // Skip ch_reserved field.
101     write64<E>(Buf, Size);
102     Buf += sizeof(ELFT::Chdr::ch_size);
103     write64<E>(Buf, Alignment);
104     Buf += sizeof(ELFT::Chdr::ch_addralign);
105   } else {
106     write32<E>(Buf, Size);
107     Buf += sizeof(ELFT::Chdr::ch_size);
108     write32<E>(Buf, Alignment);
109     Buf += sizeof(ELFT::Chdr::ch_addralign);
110   }
111 
112   return Ret;
113 }
114 
115 template <class ELFT> void OutputSection::maybeCompress() {
116   // If -compress-debug-sections is specified, we compress output debug
117   // sections.
118   if (!Config->CompressDebugSections || !Name.startswith(".debug_") ||
119       (Flags & SHF_ALLOC))
120     return;
121 
122   this->Flags |= SHF_COMPRESSED;
123   CompressedHeader = createHeader<ELFT>(this->Size, this->Alignment);
124 
125   // Here we write relocated content of sections and compress it.
126   std::vector<uint8_t> Data(this->Size);
127   this->writeTo<ELFT>(&Data[0]);
128 
129   if (Error E = zlib::compress(StringRef((char *)Data.data(), Data.size()),
130                                CompressedData))
131     fatal("compress failed: " + llvm::toString(std::move(E)));
132 
133   this->Size = this->CompressedHeader.size() + this->CompressedData.size();
134 }
135 
136 template <class ELFT> void OutputSection::finalize() {
137   if ((this->Flags & SHF_LINK_ORDER) && !this->Sections.empty()) {
138     std::sort(Sections.begin(), Sections.end(), compareByFilePosition);
139     assignOffsets();
140 
141     // We must preserve the link order dependency of sections with the
142     // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
143     // need to translate the InputSection sh_link to the OutputSection sh_link,
144     // all InputSections in the OutputSection have the same dependency.
145     if (auto *D = this->Sections.front()->getLinkOrderDep())
146       this->Link = D->OutSec->SectionIndex;
147   }
148 
149   uint32_t Type = this->Type;
150   if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
151     return;
152 
153   InputSection *First = Sections[0];
154   if (isa<SyntheticSection>(First))
155     return;
156 
157   this->Link = In<ELFT>::SymTab->OutSec->SectionIndex;
158   // sh_info for SHT_REL[A] sections should contain the section header index of
159   // the section to which the relocation applies.
160   InputSectionBase *S = First->getRelocatedSection();
161   this->Info = S->OutSec->SectionIndex;
162 }
163 
164 void OutputSection::addSection(InputSection *S) {
165   assert(S->Live);
166   Sections.push_back(S);
167   S->OutSec = this;
168   this->updateAlignment(S->Alignment);
169 
170   // If this section contains a table of fixed-size entries, sh_entsize
171   // holds the element size. Consequently, if this contains two or more
172   // input sections, all of them must have the same sh_entsize. However,
173   // you can put different types of input sections into one output
174   // sectin by using linker scripts. I don't know what to do here.
175   // Probably we sholuld handle that as an error. But for now we just
176   // pick the largest sh_entsize.
177   this->Entsize = std::max(this->Entsize, S->Entsize);
178 }
179 
180 // This function is called after we sort input sections
181 // and scan relocations to setup sections' offsets.
182 void OutputSection::assignOffsets() {
183   uint64_t Off = 0;
184   for (InputSection *S : Sections) {
185     Off = alignTo(Off, S->Alignment);
186     S->OutSecOff = Off;
187     Off += S->getSize();
188   }
189   this->Size = Off;
190 }
191 
192 void OutputSection::sort(std::function<int(InputSectionBase *S)> Order) {
193   typedef std::pair<unsigned, InputSection *> Pair;
194   auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
195 
196   std::vector<Pair> V;
197   for (InputSection *S : Sections)
198     V.push_back({Order(S), S});
199   std::stable_sort(V.begin(), V.end(), Comp);
200   Sections.clear();
201   for (Pair &P : V)
202     Sections.push_back(P.second);
203 }
204 
205 // Sorts input sections by section name suffixes, so that .foo.N comes
206 // before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
207 // We want to keep the original order if the priorities are the same
208 // because the compiler keeps the original initialization order in a
209 // translation unit and we need to respect that.
210 // For more detail, read the section of the GCC's manual about init_priority.
211 void OutputSection::sortInitFini() {
212   // Sort sections by priority.
213   sort([](InputSectionBase *S) { return getPriority(S->Name); });
214 }
215 
216 // Returns true if S matches /Filename.?\.o$/.
217 static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
218   if (!S.endswith(".o"))
219     return false;
220   S = S.drop_back(2);
221   if (S.endswith(Filename))
222     return true;
223   return !S.empty() && S.drop_back().endswith(Filename);
224 }
225 
226 static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
227 static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
228 
229 // .ctors and .dtors are sorted by this priority from highest to lowest.
230 //
231 //  1. The section was contained in crtbegin (crtbegin contains
232 //     some sentinel value in its .ctors and .dtors so that the runtime
233 //     can find the beginning of the sections.)
234 //
235 //  2. The section has an optional priority value in the form of ".ctors.N"
236 //     or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
237 //     they are compared as string rather than number.
238 //
239 //  3. The section is just ".ctors" or ".dtors".
240 //
241 //  4. The section was contained in crtend, which contains an end marker.
242 //
243 // In an ideal world, we don't need this function because .init_array and
244 // .ctors are duplicate features (and .init_array is newer.) However, there
245 // are too many real-world use cases of .ctors, so we had no choice to
246 // support that with this rather ad-hoc semantics.
247 static bool compCtors(const InputSection *A, const InputSection *B) {
248   bool BeginA = isCrtbegin(A->File->getName());
249   bool BeginB = isCrtbegin(B->File->getName());
250   if (BeginA != BeginB)
251     return BeginA;
252   bool EndA = isCrtend(A->File->getName());
253   bool EndB = isCrtend(B->File->getName());
254   if (EndA != EndB)
255     return EndB;
256   StringRef X = A->Name;
257   StringRef Y = B->Name;
258   assert(X.startswith(".ctors") || X.startswith(".dtors"));
259   assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
260   X = X.substr(6);
261   Y = Y.substr(6);
262   if (X.empty() && Y.empty())
263     return false;
264   return X < Y;
265 }
266 
267 // Sorts input sections by the special rules for .ctors and .dtors.
268 // Unfortunately, the rules are different from the one for .{init,fini}_array.
269 // Read the comment above.
270 void OutputSection::sortCtorsDtors() {
271   std::stable_sort(Sections.begin(), Sections.end(), compCtors);
272 }
273 
274 // Fill [Buf, Buf + Size) with Filler.
275 // This is used for linker script "=fillexp" command.
276 static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
277   size_t I = 0;
278   for (; I + 4 < Size; I += 4)
279     memcpy(Buf + I, &Filler, 4);
280   memcpy(Buf + I, &Filler, Size - I);
281 }
282 
283 uint32_t OutputSection::getFiller() {
284   // Determine what to fill gaps between InputSections with, as specified by the
285   // linker script. If nothing is specified and this is an executable section,
286   // fall back to trap instructions to prevent bad diassembly and detect invalid
287   // jumps to padding.
288   if (Optional<uint32_t> Filler = Script->getFiller(Name))
289     return *Filler;
290   if (Flags & SHF_EXECINSTR)
291     return Target->TrapInstr;
292   return 0;
293 }
294 
295 template <class ELFT> void OutputSection::writeTo(uint8_t *Buf) {
296   Loc = Buf;
297 
298   // We may have already rendered compressed content when using
299   // -compress-debug-sections option. Write it together with header.
300   if (!CompressedData.empty()) {
301     memcpy(Buf, CompressedHeader.data(), CompressedHeader.size());
302     Buf += CompressedHeader.size();
303     memcpy(Buf, CompressedData.data(), CompressedData.size());
304     return;
305   }
306 
307   // Write leading padding.
308   uint32_t Filler = getFiller();
309   if (Filler)
310     fill(Buf, Sections.empty() ? Size : Sections[0]->OutSecOff, Filler);
311 
312   parallelFor(0, Sections.size(), [=](size_t I) {
313     InputSection *Sec = Sections[I];
314     Sec->writeTo<ELFT>(Buf);
315 
316     // Fill gaps between sections.
317     if (Filler) {
318       uint8_t *Start = Buf + Sec->OutSecOff + Sec->getSize();
319       uint8_t *End;
320       if (I + 1 == Sections.size())
321         End = Buf + Size;
322       else
323         End = Buf + Sections[I + 1]->OutSecOff;
324       fill(Start, End - Start, Filler);
325     }
326   });
327 
328   // Linker scripts may have BYTE()-family commands with which you
329   // can write arbitrary bytes to the output. Process them if any.
330   Script->writeDataBytes(Name, Buf);
331 }
332 
333 static uint64_t getOutFlags(InputSectionBase *S) {
334   return S->Flags & ~SHF_GROUP & ~SHF_COMPRESSED;
335 }
336 
337 static SectionKey createKey(InputSectionBase *C, StringRef OutsecName) {
338   //  The ELF spec just says
339   // ----------------------------------------------------------------
340   // In the first phase, input sections that match in name, type and
341   // attribute flags should be concatenated into single sections.
342   // ----------------------------------------------------------------
343   //
344   // However, it is clear that at least some flags have to be ignored for
345   // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
346   // ignored. We should not have two output .text sections just because one was
347   // in a group and another was not for example.
348   //
349   // It also seems that that wording was a late addition and didn't get the
350   // necessary scrutiny.
351   //
352   // Merging sections with different flags is expected by some users. One
353   // reason is that if one file has
354   //
355   // int *const bar __attribute__((section(".foo"))) = (int *)0;
356   //
357   // gcc with -fPIC will produce a read only .foo section. But if another
358   // file has
359   //
360   // int zed;
361   // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
362   //
363   // gcc with -fPIC will produce a read write section.
364   //
365   // Last but not least, when using linker script the merge rules are forced by
366   // the script. Unfortunately, linker scripts are name based. This means that
367   // expressions like *(.foo*) can refer to multiple input sections with
368   // different flags. We cannot put them in different output sections or we
369   // would produce wrong results for
370   //
371   // start = .; *(.foo.*) end = .; *(.bar)
372   //
373   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
374   // another. The problem is that there is no way to layout those output
375   // sections such that the .foo sections are the only thing between the start
376   // and end symbols.
377   //
378   // Given the above issues, we instead merge sections by name and error on
379   // incompatible types and flags.
380 
381   uint32_t Alignment = 0;
382   uint64_t Flags = 0;
383   if (Config->Relocatable && (C->Flags & SHF_MERGE)) {
384     Alignment = std::max<uint64_t>(C->Alignment, C->Entsize);
385     Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
386   }
387 
388   return SectionKey{OutsecName, Flags, Alignment};
389 }
390 
391 OutputSectionFactory::OutputSectionFactory(
392     std::vector<OutputSection *> &OutputSections)
393     : OutputSections(OutputSections) {}
394 
395 static uint64_t getIncompatibleFlags(uint64_t Flags) {
396   return Flags & (SHF_ALLOC | SHF_TLS);
397 }
398 
399 // We allow sections of types listed below to merged into a
400 // single progbits section. This is typically done by linker
401 // scripts. Merging nobits and progbits will force disk space
402 // to be allocated for nobits sections. Other ones don't require
403 // any special treatment on top of progbits, so there doesn't
404 // seem to be a harm in merging them.
405 static bool canMergeToProgbits(unsigned Type) {
406   return Type == SHT_NOBITS || Type == SHT_PROGBITS || Type == SHT_INIT_ARRAY ||
407          Type == SHT_PREINIT_ARRAY || Type == SHT_FINI_ARRAY ||
408          Type == SHT_NOTE;
409 }
410 
411 static void reportDiscarded(InputSectionBase *IS) {
412   if (!Config->PrintGcSections)
413     return;
414   message("removing unused section from '" + IS->Name + "' in file '" +
415           IS->File->getName());
416 }
417 
418 void OutputSectionFactory::addInputSec(InputSectionBase *IS,
419                                        StringRef OutsecName) {
420   if (!IS->Live) {
421     reportDiscarded(IS);
422     return;
423   }
424 
425   SectionKey Key = createKey(IS, OutsecName);
426   uint64_t Flags = getOutFlags(IS);
427   OutputSection *&Sec = Map[Key];
428   if (Sec) {
429     if (getIncompatibleFlags(Sec->Flags) != getIncompatibleFlags(IS->Flags))
430       error("Section has flags incompatible with others with the same name " +
431             toString(IS));
432     if (Sec->Type != IS->Type) {
433       if (canMergeToProgbits(Sec->Type) && canMergeToProgbits(IS->Type))
434         Sec->Type = SHT_PROGBITS;
435       else
436         error("Section has different type from others with the same name " +
437               toString(IS));
438     }
439     Sec->Flags |= Flags;
440   } else {
441     Sec = make<OutputSection>(Key.Name, IS->Type, Flags);
442     OutputSections.push_back(Sec);
443   }
444 
445   Sec->addSection(cast<InputSection>(IS));
446 }
447 
448 OutputSectionFactory::~OutputSectionFactory() {}
449 
450 SectionKey DenseMapInfo<SectionKey>::getEmptyKey() {
451   return SectionKey{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
452 }
453 
454 SectionKey DenseMapInfo<SectionKey>::getTombstoneKey() {
455   return SectionKey{DenseMapInfo<StringRef>::getTombstoneKey(), 0, 0};
456 }
457 
458 unsigned DenseMapInfo<SectionKey>::getHashValue(const SectionKey &Val) {
459   return hash_combine(Val.Name, Val.Flags, Val.Alignment);
460 }
461 
462 bool DenseMapInfo<SectionKey>::isEqual(const SectionKey &LHS,
463                                        const SectionKey &RHS) {
464   return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
465          LHS.Flags == RHS.Flags && LHS.Alignment == RHS.Alignment;
466 }
467 
468 uint64_t elf::getHeaderSize() {
469   if (Config->OFormatBinary)
470     return 0;
471   return Out::ElfHeader->Size + Out::ProgramHeaders->Size;
472 }
473 
474 template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);
475 template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);
476 template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);
477 template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);
478 
479 template void OutputSection::finalize<ELF32LE>();
480 template void OutputSection::finalize<ELF32BE>();
481 template void OutputSection::finalize<ELF64LE>();
482 template void OutputSection::finalize<ELF64BE>();
483 
484 template void OutputSection::maybeCompress<ELF32LE>();
485 template void OutputSection::maybeCompress<ELF32BE>();
486 template void OutputSection::maybeCompress<ELF64LE>();
487 template void OutputSection::maybeCompress<ELF64BE>();
488 
489 template void OutputSection::writeTo<ELF32LE>(uint8_t *Buf);
490 template void OutputSection::writeTo<ELF32BE>(uint8_t *Buf);
491 template void OutputSection::writeTo<ELF64LE>(uint8_t *Buf);
492 template void OutputSection::writeTo<ELF64BE>(uint8_t *Buf);
493