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 "SymbolTable.h"
13 #include "Target.h"
14 
15 using namespace llvm;
16 using namespace llvm::object;
17 using namespace llvm::ELF;
18 
19 using namespace lld;
20 using namespace lld::elf2;
21 
22 template <bool Is64Bits>
23 OutputSectionBase<Is64Bits>::OutputSectionBase(StringRef Name, uint32_t sh_type,
24                                                uintX_t sh_flags)
25     : Name(Name) {
26   memset(&Header, 0, sizeof(HeaderT));
27   Header.sh_type = sh_type;
28   Header.sh_flags = sh_flags;
29 }
30 
31 template <class ELFT> void GotSection<ELFT>::addEntry(SymbolBody *Sym) {
32   Sym->setGotIndex(Entries.size());
33   Entries.push_back(Sym);
34 }
35 
36 template <class ELFT>
37 typename GotSection<ELFT>::uintX_t
38 GotSection<ELFT>::getEntryAddr(const SymbolBody &B) const {
39   return this->getVA() + B.getGotIndex() * this->getAddrSize();
40 }
41 
42 template <class ELFT> void PltSection<ELFT>::writeTo(uint8_t *Buf) {
43   uintptr_t Start = reinterpret_cast<uintptr_t>(Buf);
44   ArrayRef<uint8_t> Jmp = {0xff, 0x25}; // jmpq *val(%rip)
45   for (const SymbolBody *E : Entries) {
46     uint64_t GotEntryAddr = GotSec.getEntryAddr(*E);
47     uintptr_t InstPos = reinterpret_cast<uintptr_t>(Buf);
48     uint64_t PltEntryAddr = (InstPos - Start) + this->getVA();
49     Target->writePltEntry(Buf, GotEntryAddr, PltEntryAddr);
50     Buf += 8;
51   }
52 }
53 
54 template <class ELFT> void PltSection<ELFT>::addEntry(SymbolBody *Sym) {
55   Sym->setPltIndex(Entries.size());
56   Entries.push_back(Sym);
57 }
58 
59 template <class ELFT>
60 typename PltSection<ELFT>::uintX_t
61 PltSection<ELFT>::getEntryAddr(const SymbolBody &B) const {
62   return this->getVA() + B.getPltIndex() * EntrySize;
63 }
64 
65 template <class ELFT> void RelocationSection<ELFT>::writeTo(uint8_t *Buf) {
66   const unsigned EntrySize = IsRela ? sizeof(Elf_Rela) : sizeof(Elf_Rel);
67   bool IsMips64EL = Relocs[0].C.getFile()->getObj()->isMips64EL();
68   for (const DynamicReloc<ELFT> &Rel : Relocs) {
69     auto *P = reinterpret_cast<Elf_Rel *>(Buf);
70     Buf += EntrySize;
71 
72     const InputSection<ELFT> &C = Rel.C;
73     const Elf_Rel &RI = Rel.RI;
74     OutputSection<ELFT> *Out = C.getOutputSection();
75     uint32_t SymIndex = RI.getSymbol(IsMips64EL);
76     const SymbolBody *Body = C.getFile()->getSymbolBody(SymIndex);
77     uint32_t Type = RI.getType(IsMips64EL);
78     if (Target->relocNeedsGot(Type)) {
79       P->r_offset = GotSec.getEntryAddr(*Body);
80       P->setSymbolAndType(Body->getDynamicSymbolTableIndex(),
81                           Target->getGotReloc(), IsMips64EL);
82     } else {
83       P->r_offset = RI.r_offset + C.getOutputSectionOff() + Out->getVA();
84       P->setSymbolAndType(Body->getDynamicSymbolTableIndex(), Type, IsMips64EL);
85       if (IsRela)
86         static_cast<Elf_Rela *>(P)->r_addend =
87             static_cast<const Elf_Rela &>(RI).r_addend;
88     }
89   }
90 }
91 
92 template <class ELFT> void RelocationSection<ELFT>::finalize() {
93   this->Header.sh_link = DynSymSec.getSectionIndex();
94   this->Header.sh_size = Relocs.size() * this->Header.sh_entsize;
95 }
96 
97 template <bool Is64Bits>
98 InterpSection<Is64Bits>::InterpSection()
99     : OutputSectionBase<Is64Bits>(".interp", llvm::ELF::SHT_PROGBITS,
100                                   llvm::ELF::SHF_ALLOC) {
101   this->Header.sh_size = Config->DynamicLinker.size() + 1;
102   this->Header.sh_addralign = 1;
103 }
104 
105 template <bool Is64Bits>
106 template <endianness E>
107 void OutputSectionBase<Is64Bits>::writeHeaderTo(
108     typename ELFFile<ELFType<E, Is64Bits>>::Elf_Shdr *SHdr) {
109   SHdr->sh_name = Header.sh_name;
110   SHdr->sh_type = Header.sh_type;
111   SHdr->sh_flags = Header.sh_flags;
112   SHdr->sh_addr = Header.sh_addr;
113   SHdr->sh_offset = Header.sh_offset;
114   SHdr->sh_size = Header.sh_size;
115   SHdr->sh_link = Header.sh_link;
116   SHdr->sh_info = Header.sh_info;
117   SHdr->sh_addralign = Header.sh_addralign;
118   SHdr->sh_entsize = Header.sh_entsize;
119 }
120 
121 template <bool Is64Bits> void InterpSection<Is64Bits>::writeTo(uint8_t *Buf) {
122   memcpy(Buf, Config->DynamicLinker.data(), Config->DynamicLinker.size());
123 }
124 
125 template <class ELFT> void HashTableSection<ELFT>::addSymbol(SymbolBody *S) {
126   StringRef Name = S->getName();
127   DynSymSec.addSymbol(Name);
128   Hashes.push_back(hash(Name));
129   S->setDynamicSymbolTableIndex(Hashes.size());
130 }
131 
132 template <class ELFT> void DynamicSection<ELFT>::finalize() {
133   typename Base::HeaderT &Header = this->Header;
134   Header.sh_link = DynStrSec.getSectionIndex();
135 
136   unsigned NumEntries = 0;
137   if (RelaDynSec.hasRelocs()) {
138     ++NumEntries; // DT_RELA / DT_REL
139     ++NumEntries; // DT_RELASZ / DTRELSZ
140   }
141   ++NumEntries; // DT_SYMTAB
142   ++NumEntries; // DT_STRTAB
143   ++NumEntries; // DT_STRSZ
144   ++NumEntries; // DT_HASH
145 
146   StringRef RPath = Config->RPath;
147   if (!RPath.empty()) {
148     ++NumEntries; // DT_RUNPATH
149     DynStrSec.add(RPath);
150   }
151 
152   const std::vector<std::unique_ptr<SharedFileBase>> &SharedFiles =
153       SymTab.getSharedFiles();
154   for (const std::unique_ptr<SharedFileBase> &File : SharedFiles)
155     DynStrSec.add(File->getName());
156   NumEntries += SharedFiles.size();
157 
158   ++NumEntries; // DT_NULL
159 
160   Header.sh_size = NumEntries * Header.sh_entsize;
161 }
162 
163 template <class ELFT> void DynamicSection<ELFT>::writeTo(uint8_t *Buf) {
164   typedef typename std::conditional<ELFT::Is64Bits, Elf64_Dyn, Elf32_Dyn>::type
165       Elf_Dyn;
166   auto *P = reinterpret_cast<Elf_Dyn *>(Buf);
167 
168   if (RelaDynSec.hasRelocs()) {
169     bool IsRela = RelaDynSec.isRela();
170     P->d_tag = IsRela ? DT_RELA : DT_REL;
171     P->d_un.d_ptr = RelaDynSec.getVA();
172     ++P;
173 
174     P->d_tag = IsRela ? DT_RELASZ : DT_RELSZ;
175     P->d_un.d_val = RelaDynSec.getSize();
176     ++P;
177   }
178 
179   P->d_tag = DT_SYMTAB;
180   P->d_un.d_ptr = DynSymSec.getVA();
181   ++P;
182 
183   P->d_tag = DT_STRTAB;
184   P->d_un.d_ptr = DynStrSec.getVA();
185   ++P;
186 
187   P->d_tag = DT_STRSZ;
188   P->d_un.d_val = DynStrSec.data().size();
189   ++P;
190 
191   P->d_tag = DT_HASH;
192   P->d_un.d_ptr = HashSec.getVA();
193   ++P;
194 
195   StringRef RPath = Config->RPath;
196   if (!RPath.empty()) {
197     P->d_tag = DT_RUNPATH;
198     P->d_un.d_val = DynStrSec.getFileOff(RPath);
199     ++P;
200   }
201 
202   const std::vector<std::unique_ptr<SharedFileBase>> &SharedFiles =
203       SymTab.getSharedFiles();
204   for (const std::unique_ptr<SharedFileBase> &File : SharedFiles) {
205     P->d_tag = DT_NEEDED;
206     P->d_un.d_val = DynStrSec.getFileOff(File->getName());
207     ++P;
208   }
209 
210   P->d_tag = DT_NULL;
211   P->d_un.d_val = 0;
212   ++P;
213 }
214 
215 template <class ELFT>
216 void OutputSection<ELFT>::addSection(InputSection<ELFT> *C) {
217   Sections.push_back(C);
218   C->setOutputSection(this);
219   uint32_t Align = C->getAlign();
220   if (Align > this->Header.sh_addralign)
221     this->Header.sh_addralign = Align;
222 
223   uintX_t Off = this->Header.sh_size;
224   Off = RoundUpToAlignment(Off, Align);
225   C->setOutputSectionOff(Off);
226   Off += C->getSize();
227   this->Header.sh_size = Off;
228 }
229 
230 template <class ELFT>
231 typename ELFFile<ELFT>::uintX_t
232 lld::elf2::getSymVA(const DefinedRegular<ELFT> *DR) {
233   const InputSection<ELFT> *SC = &DR->Section;
234   OutputSection<ELFT> *OS = SC->getOutputSection();
235   return OS->getVA() + SC->getOutputSectionOff() + DR->Sym.st_value;
236 }
237 
238 template <class ELFT>
239 typename ELFFile<ELFT>::uintX_t
240 lld::elf2::getLocalSymVA(const typename ELFFile<ELFT>::Elf_Sym *Sym,
241                          const ObjectFile<ELFT> &File) {
242   uint32_t SecIndex = Sym->st_shndx;
243 
244   if (SecIndex == SHN_XINDEX)
245     SecIndex = File.getObj()->getExtendedSymbolTableIndex(
246         Sym, File.getSymbolTable(), File.getSymbolTableShndx());
247   ArrayRef<InputSection<ELFT> *> Sections = File.getSections();
248   InputSection<ELFT> *Section = Sections[SecIndex];
249   OutputSection<ELFT> *Out = Section->getOutputSection();
250   return Out->getVA() + Section->getOutputSectionOff() + Sym->st_value;
251 }
252 
253 template <class ELFT> void OutputSection<ELFT>::writeTo(uint8_t *Buf) {
254   for (InputSection<ELFT> *C : Sections)
255     C->writeTo(Buf, BssSec, PltSec, GotSec);
256 }
257 
258 template <bool Is64Bits>
259 void StringTableSection<Is64Bits>::writeTo(uint8_t *Buf) {
260   StringRef Data = StrTabBuilder.data();
261   memcpy(Buf, Data.data(), Data.size());
262 }
263 
264 bool lld::elf2::includeInSymtab(const SymbolBody &B) {
265   if (B.isLazy())
266     return false;
267   if (!B.isUsedInRegularObj())
268     return false;
269   uint8_t V = B.getMostConstrainingVisibility();
270   if (V != STV_DEFAULT && V != STV_PROTECTED)
271     return false;
272   return true;
273 }
274 
275 bool lld::elf2::includeInDynamicSymtab(const SymbolBody &B) {
276   if (Config->ExportDynamic || Config->Shared)
277     return true;
278   return B.isUsedInDynamicReloc();
279 }
280 
281 template <class ELFT> void SymbolTableSection<ELFT>::writeTo(uint8_t *Buf) {
282   const OutputSection<ELFT> *Out = nullptr;
283   const InputSection<ELFT> *Section = nullptr;
284   Buf += sizeof(Elf_Sym);
285 
286   // All symbols with STB_LOCAL binding precede the weak and global symbols.
287   // .dynsym only contains global symbols.
288   if (!Config->DiscardAll && !StrTabSec.isDynamic()) {
289     for (const std::unique_ptr<ObjectFileBase> &FileB :
290          Table.getObjectFiles()) {
291       auto &File = cast<ObjectFile<ELFT>>(*FileB);
292       Elf_Sym_Range Syms = File.getLocalSymbols();
293       for (const Elf_Sym &Sym : Syms) {
294         auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
295         uint32_t SecIndex = Sym.st_shndx;
296         ErrorOr<StringRef> SymName = Sym.getName(File.getStringTable());
297         if (Config->DiscardLocals && SymName->startswith(".L"))
298           continue;
299         ESym->st_name = (SymName) ? StrTabSec.getFileOff(*SymName) : 0;
300         ESym->st_size = Sym.st_size;
301         ESym->setBindingAndType(Sym.getBinding(), Sym.getType());
302         if (SecIndex == SHN_XINDEX)
303           SecIndex = File.getObj()->getExtendedSymbolTableIndex(
304               &Sym, File.getSymbolTable(), File.getSymbolTableShndx());
305         ArrayRef<InputSection<ELFT> *> Sections = File.getSections();
306         Section = Sections[SecIndex];
307         assert(Section != nullptr);
308         Out = Section->getOutputSection();
309         assert(Out != nullptr);
310         ESym->st_shndx = Out->getSectionIndex();
311         ESym->st_value =
312             Out->getVA() + Section->getOutputSectionOff() + Sym.st_value;
313         Buf += sizeof(Elf_Sym);
314       }
315     }
316   }
317 
318   for (auto &P : Table.getSymbols()) {
319     StringRef Name = P.first;
320     Symbol *Sym = P.second;
321     SymbolBody *Body = Sym->Body;
322     if (!includeInSymtab(*Body))
323       continue;
324     if (StrTabSec.isDynamic() && !includeInDynamicSymtab(*Body))
325       continue;
326 
327     const Elf_Sym &InputSym = cast<ELFSymbolBody<ELFT>>(Body)->Sym;
328     auto *ESym = reinterpret_cast<Elf_Sym *>(Buf);
329     ESym->st_name = StrTabSec.getFileOff(Name);
330 
331     Out = nullptr;
332     Section = nullptr;
333 
334     switch (Body->kind()) {
335     case SymbolBody::DefinedRegularKind:
336       Section = &cast<DefinedRegular<ELFT>>(Body)->Section;
337       break;
338     case SymbolBody::DefinedCommonKind:
339       Out = &BssSec;
340       break;
341     case SymbolBody::UndefinedKind:
342     case SymbolBody::DefinedAbsoluteKind:
343     case SymbolBody::SharedKind:
344       break;
345     case SymbolBody::LazyKind:
346       llvm_unreachable("Lazy symbol got to output symbol table!");
347     }
348 
349     ESym->setBindingAndType(InputSym.getBinding(), InputSym.getType());
350     ESym->st_size = InputSym.st_size;
351     ESym->setVisibility(Body->getMostConstrainingVisibility());
352     if (InputSym.isAbsolute()) {
353       ESym->st_shndx = SHN_ABS;
354       ESym->st_value = InputSym.st_value;
355     }
356 
357     if (Section)
358       Out = Section->getOutputSection();
359 
360     if (Out) {
361       ESym->st_shndx = Out->getSectionIndex();
362       uintX_t VA = Out->getVA();
363       if (Section)
364         VA += Section->getOutputSectionOff();
365       if (auto *C = dyn_cast<DefinedCommon<ELFT>>(Body))
366         VA += C->OffsetInBSS;
367       else
368         VA += InputSym.st_value;
369       ESym->st_value = VA;
370     }
371 
372     Buf += sizeof(Elf_Sym);
373   }
374 }
375 
376 namespace lld {
377 namespace elf2 {
378 template class OutputSectionBase<false>;
379 template class OutputSectionBase<true>;
380 
381 template void OutputSectionBase<false>::writeHeaderTo<support::little>(
382     ELFFile<ELFType<support::little, false>>::Elf_Shdr *SHdr);
383 template void OutputSectionBase<true>::writeHeaderTo<support::little>(
384     ELFFile<ELFType<support::little, true>>::Elf_Shdr *SHdr);
385 template void OutputSectionBase<false>::writeHeaderTo<support::big>(
386     ELFFile<ELFType<support::big, false>>::Elf_Shdr *SHdr);
387 template void OutputSectionBase<true>::writeHeaderTo<support::big>(
388     ELFFile<ELFType<support::big, true>>::Elf_Shdr *SHdr);
389 
390 template class GotSection<ELF32LE>;
391 template class GotSection<ELF32BE>;
392 template class GotSection<ELF64LE>;
393 template class GotSection<ELF64BE>;
394 
395 template class PltSection<ELF32LE>;
396 template class PltSection<ELF32BE>;
397 template class PltSection<ELF64LE>;
398 template class PltSection<ELF64BE>;
399 
400 template class RelocationSection<ELF32LE>;
401 template class RelocationSection<ELF32BE>;
402 template class RelocationSection<ELF64LE>;
403 template class RelocationSection<ELF64BE>;
404 
405 template class InterpSection<false>;
406 template class InterpSection<true>;
407 
408 template class HashTableSection<ELF32LE>;
409 template class HashTableSection<ELF32BE>;
410 template class HashTableSection<ELF64LE>;
411 template class HashTableSection<ELF64BE>;
412 
413 template class DynamicSection<ELF32LE>;
414 template class DynamicSection<ELF32BE>;
415 template class DynamicSection<ELF64LE>;
416 template class DynamicSection<ELF64BE>;
417 
418 template class OutputSection<ELF32LE>;
419 template class OutputSection<ELF32BE>;
420 template class OutputSection<ELF64LE>;
421 template class OutputSection<ELF64BE>;
422 
423 template class StringTableSection<false>;
424 template class StringTableSection<true>;
425 
426 template class SymbolTableSection<ELF32LE>;
427 template class SymbolTableSection<ELF32BE>;
428 template class SymbolTableSection<ELF64LE>;
429 template class SymbolTableSection<ELF64BE>;
430 
431 template ELFFile<ELF32LE>::uintX_t getSymVA(const DefinedRegular<ELF32LE> *DR);
432 
433 template ELFFile<ELF32BE>::uintX_t getSymVA(const DefinedRegular<ELF32BE> *DR);
434 
435 template ELFFile<ELF64LE>::uintX_t getSymVA(const DefinedRegular<ELF64LE> *DR);
436 
437 template ELFFile<ELF64BE>::uintX_t getSymVA(const DefinedRegular<ELF64BE> *DR);
438 
439 template ELFFile<ELF32LE>::uintX_t
440 getLocalSymVA(const ELFFile<ELF32LE>::Elf_Sym *Sym,
441               const ObjectFile<ELF32LE> &File);
442 
443 template ELFFile<ELF32BE>::uintX_t
444 getLocalSymVA(const ELFFile<ELF32BE>::Elf_Sym *Sym,
445               const ObjectFile<ELF32BE> &File);
446 
447 template ELFFile<ELF64LE>::uintX_t
448 getLocalSymVA(const ELFFile<ELF64LE>::Elf_Sym *Sym,
449               const ObjectFile<ELF64LE> &File);
450 
451 template ELFFile<ELF64BE>::uintX_t
452 getLocalSymVA(const ELFFile<ELF64BE>::Elf_Sym *Sym,
453               const ObjectFile<ELF64BE> &File);
454 }
455 }
456