1 //===- InputSection.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 "InputSection.h"
11 #include "Config.h"
12 #include "Error.h"
13 #include "InputFiles.h"
14 #include "OutputSections.h"
15 #include "Target.h"
16 
17 #include "llvm/Support/Endian.h"
18 
19 using namespace llvm;
20 using namespace llvm::ELF;
21 using namespace llvm::object;
22 using namespace llvm::support::endian;
23 
24 using namespace lld;
25 using namespace lld::elf;
26 
27 template <class ELFT>
28 InputSectionBase<ELFT>::InputSectionBase(elf::ObjectFile<ELFT> *File,
29                                          const Elf_Shdr *Header,
30                                          Kind SectionKind)
31     : Header(Header), File(File), SectionKind(SectionKind), Repl(this) {
32   // The garbage collector sets sections' Live bits.
33   // If GC is disabled, all sections are considered live by default.
34   Live = !Config->GcSections;
35 
36   // The ELF spec states that a value of 0 means the section has
37   // no alignment constraits.
38   Align = std::max<uintX_t>(Header->sh_addralign, 1);
39 }
40 
41 template <class ELFT> size_t InputSectionBase<ELFT>::getSize() const {
42   if (auto *D = dyn_cast<InputSection<ELFT>>(this))
43     if (D->getThunksSize() > 0)
44       return D->getThunkOff() + D->getThunksSize();
45   return Header->sh_size;
46 }
47 
48 template <class ELFT> StringRef InputSectionBase<ELFT>::getSectionName() const {
49   return check(File->getObj().getSectionName(this->Header));
50 }
51 
52 template <class ELFT>
53 ArrayRef<uint8_t> InputSectionBase<ELFT>::getSectionData() const {
54   return check(this->File->getObj().getSectionContents(this->Header));
55 }
56 
57 template <class ELFT>
58 typename ELFT::uint InputSectionBase<ELFT>::getOffset(uintX_t Offset) {
59   switch (SectionKind) {
60   case Regular:
61     return cast<InputSection<ELFT>>(this)->OutSecOff + Offset;
62   case EHFrame:
63     return cast<EHInputSection<ELFT>>(this)->getOffset(Offset);
64   case Merge:
65     return cast<MergeInputSection<ELFT>>(this)->getOffset(Offset);
66   case MipsReginfo:
67     // MIPS .reginfo sections are consumed by the linker,
68     // so it should never be copied to output.
69     llvm_unreachable("MIPS .reginfo reached writeTo().");
70   }
71   llvm_unreachable("invalid section kind");
72 }
73 
74 template <class ELFT>
75 typename ELFT::uint
76 InputSectionBase<ELFT>::getOffset(const DefinedRegular<ELFT> &Sym) {
77   return getOffset(Sym.Value);
78 }
79 
80 // Returns a section that Rel relocation is pointing to.
81 template <class ELFT>
82 InputSectionBase<ELFT> *
83 InputSectionBase<ELFT>::getRelocTarget(const Elf_Rel &Rel) const {
84   // Global symbol
85   uint32_t SymIndex = Rel.getSymbol(Config->Mips64EL);
86   SymbolBody &B = File->getSymbolBody(SymIndex).repl();
87   if (auto *D = dyn_cast<DefinedRegular<ELFT>>(&B))
88     if (D->Section)
89       return D->Section->Repl;
90   return nullptr;
91 }
92 
93 template <class ELFT>
94 InputSectionBase<ELFT> *
95 InputSectionBase<ELFT>::getRelocTarget(const Elf_Rela &Rel) const {
96   return getRelocTarget(reinterpret_cast<const Elf_Rel &>(Rel));
97 }
98 
99 template <class ELFT>
100 InputSection<ELFT>::InputSection(elf::ObjectFile<ELFT> *F,
101                                  const Elf_Shdr *Header)
102     : InputSectionBase<ELFT>(F, Header, Base::Regular) {}
103 
104 template <class ELFT>
105 bool InputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
106   return S->SectionKind == Base::Regular;
107 }
108 
109 template <class ELFT>
110 InputSectionBase<ELFT> *InputSection<ELFT>::getRelocatedSection() {
111   assert(this->Header->sh_type == SHT_RELA || this->Header->sh_type == SHT_REL);
112   ArrayRef<InputSectionBase<ELFT> *> Sections = this->File->getSections();
113   return Sections[this->Header->sh_info];
114 }
115 
116 template <class ELFT> void InputSection<ELFT>::addThunk(SymbolBody &Body) {
117   Body.ThunkIndex = Thunks.size();
118   Thunks.push_back(&Body);
119 }
120 
121 template <class ELFT> uint64_t InputSection<ELFT>::getThunkOff() const {
122   return this->Header->sh_size;
123 }
124 
125 template <class ELFT> uint64_t InputSection<ELFT>::getThunksSize() const {
126   return Thunks.size() * Target->ThunkSize;
127 }
128 
129 // This is used for -r. We can't use memcpy to copy relocations because we need
130 // to update symbol table offset and section index for each relocation. So we
131 // copy relocations one by one.
132 template <class ELFT>
133 template <class RelTy>
134 void InputSection<ELFT>::copyRelocations(uint8_t *Buf, ArrayRef<RelTy> Rels) {
135   InputSectionBase<ELFT> *RelocatedSection = getRelocatedSection();
136 
137   for (const RelTy &Rel : Rels) {
138     uint32_t SymIndex = Rel.getSymbol(Config->Mips64EL);
139     uint32_t Type = Rel.getType(Config->Mips64EL);
140     SymbolBody &Body = this->File->getSymbolBody(SymIndex).repl();
141 
142     RelTy *P = reinterpret_cast<RelTy *>(Buf);
143     Buf += sizeof(RelTy);
144 
145     P->r_offset = RelocatedSection->getOffset(Rel.r_offset);
146     P->setSymbolAndType(Body.DynsymIndex, Type, Config->Mips64EL);
147   }
148 }
149 
150 template <class RelTy>
151 static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
152   switch (Rel->getType(Config->Mips64EL)) {
153   case R_MIPS_HI16:
154     return R_MIPS_LO16;
155   case R_MIPS_GOT16:
156     return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
157   case R_MIPS_PCHI16:
158     return R_MIPS_PCLO16;
159   case R_MICROMIPS_HI16:
160     return R_MICROMIPS_LO16;
161   default:
162     return R_MIPS_NONE;
163   }
164 }
165 
166 template <endianness E> static int16_t readSignedLo16(uint8_t *Loc) {
167   return read32<E>(Loc) & 0xffff;
168 }
169 
170 template <class ELFT>
171 template <class RelTy>
172 int32_t
173 InputSectionBase<ELFT>::findMipsPairedAddend(uint8_t *Buf, uint8_t *BufLoc,
174                                              SymbolBody &Sym, const RelTy *Rel,
175                                              const RelTy *End) {
176   uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
177   uint32_t Type = getMipsPairType(Rel, Sym);
178 
179   // Some MIPS relocations use addend calculated from addend of the relocation
180   // itself and addend of paired relocation. ABI requires to compute such
181   // combined addend in case of REL relocation record format only.
182   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
183   if (RelTy::IsRela || Type == R_MIPS_NONE)
184     return 0;
185 
186   for (const RelTy *RI = Rel; RI != End; ++RI) {
187     if (RI->getType(Config->Mips64EL) != Type)
188       continue;
189     if (RI->getSymbol(Config->Mips64EL) != SymIndex)
190       continue;
191     uintX_t Offset = getOffset(RI->r_offset);
192     if (Offset == (uintX_t)-1)
193       break;
194     const endianness E = ELFT::TargetEndianness;
195     return ((read32<E>(BufLoc) & 0xffff) << 16) +
196            readSignedLo16<E>(Buf + Offset);
197   }
198   unsigned OldType = Rel->getType(Config->Mips64EL);
199   StringRef OldName = getELFRelocationTypeName(Config->EMachine, OldType);
200   StringRef NewName = getELFRelocationTypeName(Config->EMachine, Type);
201   warning("can't find matching " + NewName + " relocation for " + OldName);
202   return 0;
203 }
204 
205 template <class ELFT, class uintX_t>
206 static uintX_t adjustMipsSymVA(uint32_t Type, const elf::ObjectFile<ELFT> &File,
207                                const SymbolBody &Body, uintX_t AddrLoc,
208                                uintX_t SymVA) {
209   if (Type == R_MIPS_HI16 && &Body == Config->MipsGpDisp)
210     return getMipsGpAddr<ELFT>() - AddrLoc;
211   if (Type == R_MIPS_LO16 && &Body == Config->MipsGpDisp)
212     return getMipsGpAddr<ELFT>() - AddrLoc + 4;
213   if (&Body == Config->MipsLocalGp)
214     return getMipsGpAddr<ELFT>();
215   if (Body.isLocal() && (Type == R_MIPS_GPREL16 || Type == R_MIPS_GPREL32))
216     // We need to adjust SymVA value in case of R_MIPS_GPREL16/32
217     // relocations because they use the following expression to calculate
218     // the relocation's result for local symbol: S + A + GP0 - G.
219     return SymVA + File.getMipsGp0();
220   return SymVA;
221 }
222 
223 template <class ELFT, class uintX_t>
224 static uintX_t getMipsGotVA(const SymbolBody &Body, uintX_t SymVA,
225                             uint8_t *BufLoc) {
226   if (Body.isLocal())
227     // If relocation against MIPS local symbol requires GOT entry, this entry
228     // should be initialized by 'page address'. This address is high 16-bits
229     // of sum the symbol's value and the addend.
230     return Out<ELFT>::Got->getMipsLocalPageAddr(SymVA);
231   if (!Body.isPreemptible())
232     // For non-local symbols GOT entries should contain their full
233     // addresses. But if such symbol cannot be preempted, we do not
234     // have to put them into the "global" part of GOT and use dynamic
235     // linker to determine their actual addresses. That is why we
236     // create GOT entries for them in the "local" part of GOT.
237     return Out<ELFT>::Got->getMipsLocalFullAddr(Body);
238   return Body.getGotVA<ELFT>();
239 }
240 
241 template <class ELFT>
242 template <class RelTy>
243 void InputSectionBase<ELFT>::relocate(uint8_t *Buf, uint8_t *BufEnd,
244                                       ArrayRef<RelTy> Rels) {
245   size_t Num = Rels.end() - Rels.begin();
246   for (size_t I = 0; I < Num; ++I) {
247     const RelTy &RI = *(Rels.begin() + I);
248     uintX_t Offset = getOffset(RI.r_offset);
249     if (Offset == (uintX_t)-1)
250       continue;
251 
252     uintX_t A = getAddend<ELFT>(RI);
253     uint32_t SymIndex = RI.getSymbol(Config->Mips64EL);
254     uint32_t Type = RI.getType(Config->Mips64EL);
255     uint8_t *BufLoc = Buf + Offset;
256     uintX_t AddrLoc = OutSec->getVA() + Offset;
257 
258     if (Target->pointsToLocalDynamicGotEntry(Type) &&
259         !Target->canRelaxTls(Type, nullptr)) {
260       Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc,
261                           Out<ELFT>::Got->getTlsIndexVA() + A);
262       continue;
263     }
264 
265     SymbolBody &Body = File->getSymbolBody(SymIndex).repl();
266 
267     if (Target->canRelaxTls(Type, &Body)) {
268       uintX_t SymVA;
269       if (Target->needsGot(Type, Body))
270         SymVA = Body.getGotVA<ELFT>();
271       else
272         SymVA = Body.getVA<ELFT>();
273       // By optimizing TLS relocations, it is sometimes needed to skip
274       // relocations that immediately follow TLS relocations. This function
275       // knows how many slots we need to skip.
276       I += Target->relaxTls(BufLoc, BufEnd, Type, AddrLoc, SymVA, Body);
277       continue;
278     }
279 
280     // PPC64 has a special relocation representing the TOC base pointer
281     // that does not have a corresponding symbol.
282     if (Config->EMachine == EM_PPC64 && RI.getType(false) == R_PPC64_TOC) {
283       uintX_t SymVA = getPPC64TocBase() + A;
284       Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc, SymVA);
285       continue;
286     }
287 
288     if (Target->isTlsGlobalDynamicRel(Type) &&
289         !Target->canRelaxTls(Type, &Body)) {
290       Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc,
291                           Out<ELFT>::Got->getGlobalDynAddr(Body) + A);
292       continue;
293     }
294 
295     if (!RelTy::IsRela)
296       A += Target->getImplicitAddend(BufLoc, Type);
297     if (Config->EMachine == EM_MIPS)
298       A += findMipsPairedAddend(Buf, BufLoc, Body, &RI, Rels.end());
299     uintX_t SymVA = Body.getVA<ELFT>(A);
300 
301     if (Target->needsPlt(Type, Body)) {
302       SymVA = Body.getPltVA<ELFT>() + A;
303     } else if (Target->needsGot(Type, Body)) {
304       if (Config->EMachine == EM_MIPS)
305         SymVA = getMipsGotVA<ELFT>(Body, SymVA, BufLoc);
306       else
307         SymVA = Body.getGotVA<ELFT>() + A;
308       if (Body.isTls())
309         Type = Target->getTlsGotRel(Type);
310     } else if (Target->isSizeRel(Type) && Body.isPreemptible()) {
311       // A SIZE relocation is supposed to set a symbol size, but if a symbol
312       // can be preempted, the size at runtime may be different than link time.
313       // If that's the case, we leave the field alone rather than filling it
314       // with a possibly incorrect value.
315       continue;
316     } else if (Target->needsThunk(Type, *this->getFile(), Body)) {
317       // Get address of a thunk code related to the symbol.
318       SymVA = Body.getThunkVA<ELFT>();
319     } else if (!Target->needsCopyRel<ELFT>(Type, Body) &&
320                Body.isPreemptible()) {
321       continue;
322     } else if (Config->EMachine == EM_MIPS) {
323       SymVA = adjustMipsSymVA<ELFT>(Type, *File, Body, AddrLoc, SymVA);
324     }
325     if (Target->isSizeRel(Type))
326       SymVA = Body.getSize<ELFT>() + A;
327 
328     Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc, SymVA);
329   }
330 }
331 
332 template <class ELFT> void InputSection<ELFT>::writeTo(uint8_t *Buf) {
333   if (this->Header->sh_type == SHT_NOBITS)
334     return;
335   ELFFile<ELFT> &EObj = this->File->getObj();
336 
337   // If -r is given, then an InputSection may be a relocation section.
338   if (this->Header->sh_type == SHT_RELA) {
339     copyRelocations(Buf + OutSecOff, EObj.relas(this->Header));
340     return;
341   }
342   if (this->Header->sh_type == SHT_REL) {
343     copyRelocations(Buf + OutSecOff, EObj.rels(this->Header));
344     return;
345   }
346 
347   // Copy section contents from source object file to output file.
348   ArrayRef<uint8_t> Data = this->getSectionData();
349   memcpy(Buf + OutSecOff, Data.data(), Data.size());
350 
351   // Iterate over all relocation sections that apply to this section.
352   uint8_t *BufEnd = Buf + OutSecOff + Data.size();
353   for (const Elf_Shdr *RelSec : this->RelocSections) {
354     if (RelSec->sh_type == SHT_RELA)
355       this->relocate(Buf, BufEnd, EObj.relas(RelSec));
356     else
357       this->relocate(Buf, BufEnd, EObj.rels(RelSec));
358   }
359 
360   // The section might have a data/code generated by the linker and need
361   // to be written after the section. Usually these are thunks - small piece
362   // of code used to jump between "incompatible" functions like PIC and non-PIC
363   // or if the jump target too far and its address does not fit to the short
364   // jump istruction.
365   if (!Thunks.empty()) {
366     Buf += OutSecOff + getThunkOff();
367     for (const SymbolBody *S : Thunks) {
368       Target->writeThunk(Buf, S->getVA<ELFT>());
369       Buf += Target->ThunkSize;
370     }
371   }
372 }
373 
374 template <class ELFT>
375 void InputSection<ELFT>::replace(InputSection<ELFT> *Other) {
376   this->Align = std::max(this->Align, Other->Align);
377   Other->Repl = this->Repl;
378   Other->Live = false;
379 }
380 
381 template <class ELFT>
382 SplitInputSection<ELFT>::SplitInputSection(
383     elf::ObjectFile<ELFT> *File, const Elf_Shdr *Header,
384     typename InputSectionBase<ELFT>::Kind SectionKind)
385     : InputSectionBase<ELFT>(File, Header, SectionKind) {}
386 
387 template <class ELFT>
388 EHInputSection<ELFT>::EHInputSection(elf::ObjectFile<ELFT> *F,
389                                      const Elf_Shdr *Header)
390     : SplitInputSection<ELFT>(F, Header, InputSectionBase<ELFT>::EHFrame) {
391   // Mark .eh_frame sections as live by default because there are
392   // usually no relocations that point to .eh_frames. Otherwise,
393   // the garbage collector would drop all .eh_frame sections.
394   this->Live = true;
395 }
396 
397 template <class ELFT>
398 bool EHInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
399   return S->SectionKind == InputSectionBase<ELFT>::EHFrame;
400 }
401 
402 template <class ELFT>
403 typename ELFT::uint EHInputSection<ELFT>::getOffset(uintX_t Offset) {
404   // The file crtbeginT.o has relocations pointing to the start of an empty
405   // .eh_frame that is known to be the first in the link. It does that to
406   // identify the start of the output .eh_frame. Handle this special case.
407   if (this->getSectionHdr()->sh_size == 0)
408     return Offset;
409   std::pair<uintX_t, uintX_t> *I = this->getRangeAndSize(Offset).first;
410   uintX_t Base = I->second;
411   if (Base == uintX_t(-1))
412     return -1; // Not in the output
413 
414   uintX_t Addend = Offset - I->first;
415   return Base + Addend;
416 }
417 
418 template <class ELFT>
419 MergeInputSection<ELFT>::MergeInputSection(elf::ObjectFile<ELFT> *F,
420                                            const Elf_Shdr *Header)
421     : SplitInputSection<ELFT>(F, Header, InputSectionBase<ELFT>::Merge) {}
422 
423 template <class ELFT>
424 bool MergeInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
425   return S->SectionKind == InputSectionBase<ELFT>::Merge;
426 }
427 
428 template <class ELFT>
429 std::pair<std::pair<typename ELFT::uint, typename ELFT::uint> *,
430           typename ELFT::uint>
431 SplitInputSection<ELFT>::getRangeAndSize(uintX_t Offset) {
432   ArrayRef<uint8_t> D = this->getSectionData();
433   StringRef Data((const char *)D.data(), D.size());
434   uintX_t Size = Data.size();
435   if (Offset >= Size)
436     fatal("entry is past the end of the section");
437 
438   // Find the element this offset points to.
439   auto I = std::upper_bound(
440       Offsets.begin(), Offsets.end(), Offset,
441       [](const uintX_t &A, const std::pair<uintX_t, uintX_t> &B) {
442         return A < B.first;
443       });
444   uintX_t End = I == Offsets.end() ? Data.size() : I->first;
445   --I;
446   return std::make_pair(&*I, End);
447 }
448 
449 template <class ELFT>
450 typename ELFT::uint MergeInputSection<ELFT>::getOffset(uintX_t Offset) {
451   std::pair<std::pair<uintX_t, uintX_t> *, uintX_t> T =
452       this->getRangeAndSize(Offset);
453   std::pair<uintX_t, uintX_t> *I = T.first;
454   uintX_t End = T.second;
455   uintX_t Start = I->first;
456 
457   // Compute the Addend and if the Base is cached, return.
458   uintX_t Addend = Offset - Start;
459   uintX_t &Base = I->second;
460   if (Base != uintX_t(-1))
461     return Base + Addend;
462 
463   // Map the base to the offset in the output section and cache it.
464   ArrayRef<uint8_t> D = this->getSectionData();
465   StringRef Data((const char *)D.data(), D.size());
466   StringRef Entry = Data.substr(Start, End - Start);
467   Base =
468       static_cast<MergeOutputSection<ELFT> *>(this->OutSec)->getOffset(Entry);
469   return Base + Addend;
470 }
471 
472 template <class ELFT>
473 MipsReginfoInputSection<ELFT>::MipsReginfoInputSection(elf::ObjectFile<ELFT> *F,
474                                                        const Elf_Shdr *Hdr)
475     : InputSectionBase<ELFT>(F, Hdr, InputSectionBase<ELFT>::MipsReginfo) {
476   // Initialize this->Reginfo.
477   ArrayRef<uint8_t> D = this->getSectionData();
478   if (D.size() != sizeof(Elf_Mips_RegInfo<ELFT>))
479     fatal("invalid size of .reginfo section");
480   Reginfo = reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(D.data());
481 }
482 
483 template <class ELFT>
484 bool MipsReginfoInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
485   return S->SectionKind == InputSectionBase<ELFT>::MipsReginfo;
486 }
487 
488 template class elf::InputSectionBase<ELF32LE>;
489 template class elf::InputSectionBase<ELF32BE>;
490 template class elf::InputSectionBase<ELF64LE>;
491 template class elf::InputSectionBase<ELF64BE>;
492 
493 template class elf::InputSection<ELF32LE>;
494 template class elf::InputSection<ELF32BE>;
495 template class elf::InputSection<ELF64LE>;
496 template class elf::InputSection<ELF64BE>;
497 
498 template class elf::EHInputSection<ELF32LE>;
499 template class elf::EHInputSection<ELF32BE>;
500 template class elf::EHInputSection<ELF64LE>;
501 template class elf::EHInputSection<ELF64BE>;
502 
503 template class elf::MergeInputSection<ELF32LE>;
504 template class elf::MergeInputSection<ELF32BE>;
505 template class elf::MergeInputSection<ELF64LE>;
506 template class elf::MergeInputSection<ELF64BE>;
507 
508 template class elf::MipsReginfoInputSection<ELF32LE>;
509 template class elf::MipsReginfoInputSection<ELF32BE>;
510 template class elf::MipsReginfoInputSection<ELF64LE>;
511 template class elf::MipsReginfoInputSection<ELF64BE>;
512