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(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> StringRef InputSectionBase<ELFT>::getSectionName() const {
42   return check(File->getObj().getSectionName(this->Header));
43 }
44 
45 template <class ELFT>
46 ArrayRef<uint8_t> InputSectionBase<ELFT>::getSectionData() const {
47   return check(this->File->getObj().getSectionContents(this->Header));
48 }
49 
50 template <class ELFT>
51 typename ELFFile<ELFT>::uintX_t
52 InputSectionBase<ELFT>::getOffset(uintX_t Offset) {
53   switch (SectionKind) {
54   case Regular:
55     return cast<InputSection<ELFT>>(this)->OutSecOff + Offset;
56   case EHFrame:
57     return cast<EHInputSection<ELFT>>(this)->getOffset(Offset);
58   case Merge:
59     return cast<MergeInputSection<ELFT>>(this)->getOffset(Offset);
60   case MipsReginfo:
61     // MIPS .reginfo sections are consumed by the linker,
62     // so it should never be copied to output.
63     llvm_unreachable("MIPS .reginfo reached writeTo().");
64   }
65   llvm_unreachable("Invalid section kind");
66 }
67 
68 template <class ELFT>
69 typename ELFFile<ELFT>::uintX_t
70 InputSectionBase<ELFT>::getOffset(const Elf_Sym &Sym) {
71   return getOffset(Sym.st_value);
72 }
73 
74 // Returns a section that Rel relocation is pointing to.
75 template <class ELFT>
76 InputSectionBase<ELFT> *
77 InputSectionBase<ELFT>::getRelocTarget(const Elf_Rel &Rel) const {
78   // Global symbol
79   uint32_t SymIndex = Rel.getSymbol(Config->Mips64EL);
80   if (SymbolBody *B = File->getSymbolBody(SymIndex))
81     if (auto *D = dyn_cast<DefinedRegular<ELFT>>(B->repl()))
82       return D->Section->Repl;
83   // Local symbol
84   if (const Elf_Sym *Sym = File->getLocalSymbol(SymIndex))
85     if (InputSectionBase<ELFT> *Sec = File->getSection(*Sym))
86       return Sec;
87   return nullptr;
88 }
89 
90 template <class ELFT>
91 InputSectionBase<ELFT> *
92 InputSectionBase<ELFT>::getRelocTarget(const Elf_Rela &Rel) const {
93   return getRelocTarget(reinterpret_cast<const Elf_Rel &>(Rel));
94 }
95 
96 template <class ELFT>
97 InputSection<ELFT>::InputSection(ObjectFile<ELFT> *F, const Elf_Shdr *Header)
98     : InputSectionBase<ELFT>(F, Header, Base::Regular) {}
99 
100 template <class ELFT>
101 bool InputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
102   return S->SectionKind == Base::Regular;
103 }
104 
105 template <class ELFT>
106 InputSectionBase<ELFT> *InputSection<ELFT>::getRelocatedSection() {
107   assert(this->Header->sh_type == SHT_RELA || this->Header->sh_type == SHT_REL);
108   ArrayRef<InputSectionBase<ELFT> *> Sections = this->File->getSections();
109   return Sections[this->Header->sh_info];
110 }
111 
112 // This is used for -r. We can't use memcpy to copy relocations because we need
113 // to update symbol table offset and section index for each relocation. So we
114 // copy relocations one by one.
115 template <class ELFT>
116 template <bool isRela>
117 void InputSection<ELFT>::copyRelocations(uint8_t *Buf,
118                                          RelIteratorRange<isRela> Rels) {
119   typedef Elf_Rel_Impl<ELFT, isRela> RelType;
120   InputSectionBase<ELFT> *RelocatedSection = getRelocatedSection();
121 
122   for (const RelType &Rel : Rels) {
123     uint32_t SymIndex = Rel.getSymbol(Config->Mips64EL);
124     uint32_t Type = Rel.getType(Config->Mips64EL);
125     const Elf_Shdr *SymTab = this->File->getSymbolTable();
126 
127     RelType *P = reinterpret_cast<RelType *>(Buf);
128     Buf += sizeof(RelType);
129 
130     // Relocation against local symbol here means that it is probably
131     // rel[a].eh_frame section which has references to sections in r_info field.
132     if (SymIndex < SymTab->sh_info) {
133       const Elf_Sym *Sym = this->File->getLocalSymbol(SymIndex);
134       uint32_t Idx = Out<ELFT>::SymTab->Locals[Sym];
135       P->r_offset = RelocatedSection->getOffset(Rel.r_offset);
136       P->setSymbolAndType(Idx, Type, Config->Mips64EL);
137       continue;
138     }
139 
140     SymbolBody *Body = this->File->getSymbolBody(SymIndex)->repl();
141     P->r_offset = RelocatedSection->getOffset(Rel.r_offset);
142     P->setSymbolAndType(Body->DynsymIndex, Type, Config->Mips64EL);
143   }
144 }
145 
146 static uint32_t getMipsPairedRelocType(uint32_t Type) {
147   if (Config->EMachine != EM_MIPS)
148     return R_MIPS_NONE;
149   switch (Type) {
150   case R_MIPS_HI16:
151     return R_MIPS_LO16;
152   case R_MIPS_PCHI16:
153     return R_MIPS_PCLO16;
154   case R_MICROMIPS_HI16:
155     return R_MICROMIPS_LO16;
156   default:
157     return R_MIPS_NONE;
158   }
159 }
160 
161 template <class ELFT>
162 template <bool isRela>
163 uint8_t *
164 InputSectionBase<ELFT>::findMipsPairedReloc(uint8_t *Buf, uint32_t SymIndex,
165                                             uint32_t Type,
166                                             RelIteratorRange<isRela> Rels) {
167   // Some MIPS relocations use addend calculated from addend of the relocation
168   // itself and addend of paired relocation. ABI requires to compute such
169   // combined addend in case of REL relocation record format only.
170   // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
171   if (isRela || Type == R_MIPS_NONE)
172     return nullptr;
173   for (const auto &RI : Rels) {
174     if (RI.getType(Config->Mips64EL) != Type)
175       continue;
176     if (RI.getSymbol(Config->Mips64EL) != SymIndex)
177       continue;
178     uintX_t Offset = getOffset(RI.r_offset);
179     if (Offset == (uintX_t)-1)
180       return nullptr;
181     return Buf + Offset;
182   }
183   return nullptr;
184 }
185 
186 template <class ELFT>
187 template <bool isRela>
188 void InputSectionBase<ELFT>::relocate(uint8_t *Buf, uint8_t *BufEnd,
189                                       RelIteratorRange<isRela> Rels) {
190   typedef Elf_Rel_Impl<ELFT, isRela> RelType;
191   size_t Num = Rels.end() - Rels.begin();
192   for (size_t I = 0; I < Num; ++I) {
193     const RelType &RI = *(Rels.begin() + I);
194     uint32_t SymIndex = RI.getSymbol(Config->Mips64EL);
195     uint32_t Type = RI.getType(Config->Mips64EL);
196     uintX_t Offset = getOffset(RI.r_offset);
197     if (Offset == (uintX_t)-1)
198       continue;
199 
200     uint8_t *BufLoc = Buf + Offset;
201     uintX_t AddrLoc = OutSec->getVA() + Offset;
202     auto NextRelocs = llvm::make_range(&RI, Rels.end());
203 
204     if (Target->pointsToLocalDynamicGotEntry(Type) &&
205         !Target->canRelaxTls(Type, nullptr)) {
206       Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc,
207                           Out<ELFT>::Got->getTlsIndexVA() +
208                               getAddend<ELFT>(RI));
209       continue;
210     }
211 
212     const Elf_Shdr *SymTab = File->getSymbolTable();
213     SymbolBody *Body = nullptr;
214     if (SymIndex >= SymTab->sh_info)
215       Body = File->getSymbolBody(SymIndex)->repl();
216 
217     if (Target->canRelaxTls(Type, Body)) {
218       uintX_t SymVA;
219       if (!Body)
220         SymVA = getLocalRelTarget(*File, RI, 0);
221       else if (Target->needsGot(Type, *Body))
222         SymVA = Body->getGotVA<ELFT>();
223       else
224         SymVA = Body->getVA<ELFT>();
225       // By optimizing TLS relocations, it is sometimes needed to skip
226       // relocations that immediately follow TLS relocations. This function
227       // knows how many slots we need to skip.
228       I += Target->relaxTls(BufLoc, BufEnd, Type, AddrLoc, SymVA, Body);
229       continue;
230     }
231 
232     // Handle relocations for local symbols -- they never get
233     // resolved so we don't allocate a SymbolBody.
234     uintX_t A = getAddend<ELFT>(RI);
235     if (!Body) {
236       uintX_t SymVA = getLocalRelTarget(*File, RI, A);
237       uint8_t *PairedLoc = nullptr;
238       if (Config->EMachine == EM_MIPS) {
239         if (Type == R_MIPS_GPREL16 || Type == R_MIPS_GPREL32)
240           // We need to adjust SymVA value in case of R_MIPS_GPREL16/32
241           // relocations because they use the following expression to calculate
242           // the relocation's result for local symbol: S + A + GP0 - G.
243           SymVA += File->getMipsGp0();
244         else if (Type == R_MIPS_GOT16) {
245           // R_MIPS_GOT16 relocation against local symbol requires index of
246           // a local GOT entry which contains page address corresponds
247           // to sum of the symbol address and addend. The addend in that case
248           // is calculated using addends from R_MIPS_GOT16 and paired
249           // R_MIPS_LO16 relocations.
250           const endianness E = ELFT::TargetEndianness;
251           uint8_t *LowLoc =
252               findMipsPairedReloc(Buf, SymIndex, R_MIPS_LO16, NextRelocs);
253           uint64_t AHL = read32<E>(BufLoc) << 16;
254           if (LowLoc)
255             AHL += SignExtend64<16>(read32<E>(LowLoc));
256           SymVA = Out<ELFT>::Got->getMipsLocalPageAddr(SymVA + AHL);
257         } else
258           PairedLoc = findMipsPairedReloc(
259               Buf, SymIndex, getMipsPairedRelocType(Type), NextRelocs);
260       }
261       Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc, SymVA, 0, PairedLoc);
262       continue;
263     }
264 
265     if (Target->isTlsGlobalDynamicRel(Type) &&
266         !Target->canRelaxTls(Type, Body)) {
267       Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc,
268                           Out<ELFT>::Got->getGlobalDynAddr(*Body) +
269                               getAddend<ELFT>(RI));
270       continue;
271     }
272 
273     uintX_t SymVA = Body->getVA<ELFT>();
274     bool CBP = canBePreempted(Body);
275     if (Target->needsPlt<ELFT>(Type, *Body)) {
276       SymVA = Body->getPltVA<ELFT>();
277     } else if (Target->needsGot(Type, *Body)) {
278       if (Config->EMachine == EM_MIPS && !CBP)
279         // Under some conditions relocations against non-local symbols require
280         // entries in the local part of MIPS GOT. In that case we need an entry
281         // initialized by full address of the symbol.
282         SymVA = Out<ELFT>::Got->getMipsLocalFullAddr(*Body);
283       else
284         SymVA = Body->getGotVA<ELFT>();
285       if (Body->IsTls)
286         Type = Target->getTlsGotRel(Type);
287     } else if (!Target->needsCopyRel<ELFT>(Type, *Body) &&
288                isa<SharedSymbol<ELFT>>(*Body)) {
289       continue;
290     } else if (Target->isTlsDynRel(Type, *Body)) {
291       continue;
292     } else if (Target->isSizeRel(Type) && CBP) {
293       // A SIZE relocation is supposed to set a symbol size, but if a symbol
294       // can be preempted, the size at runtime may be different than link time.
295       // If that's the case, we leave the field alone rather than filling it
296       // with a possibly incorrect value.
297       continue;
298     } else if (Config->EMachine == EM_MIPS) {
299       if (Type == R_MIPS_HI16 && Body == Config->MipsGpDisp)
300         SymVA = getMipsGpAddr<ELFT>() - AddrLoc;
301       else if (Type == R_MIPS_LO16 && Body == Config->MipsGpDisp)
302         SymVA = getMipsGpAddr<ELFT>() - AddrLoc + 4;
303       else if (Body == Config->MipsLocalGp)
304         SymVA = getMipsGpAddr<ELFT>();
305     }
306     uintX_t Size = Body->getSize<ELFT>();
307     Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc, SymVA + A, Size + A,
308                         findMipsPairedReloc(Buf, SymIndex,
309                                             getMipsPairedRelocType(Type),
310                                             NextRelocs));
311   }
312 }
313 
314 template <class ELFT> void InputSection<ELFT>::writeTo(uint8_t *Buf) {
315   if (this->Header->sh_type == SHT_NOBITS)
316     return;
317   // Copy section contents from source object file to output file.
318   ArrayRef<uint8_t> Data = this->getSectionData();
319   ELFFile<ELFT> &EObj = this->File->getObj();
320 
321   // That happens with -r. In that case we need fix the relocation position and
322   // target. No relocations are applied.
323   if (this->Header->sh_type == SHT_RELA) {
324     this->copyRelocations(Buf + OutSecOff, EObj.relas(this->Header));
325     return;
326   }
327   if (this->Header->sh_type == SHT_REL) {
328     this->copyRelocations(Buf + OutSecOff, EObj.rels(this->Header));
329     return;
330   }
331 
332   memcpy(Buf + OutSecOff, Data.data(), Data.size());
333 
334   uint8_t *BufEnd = Buf + OutSecOff + Data.size();
335   // Iterate over all relocation sections that apply to this section.
336   for (const Elf_Shdr *RelSec : this->RelocSections) {
337     if (RelSec->sh_type == SHT_RELA)
338       this->relocate(Buf, BufEnd, EObj.relas(RelSec));
339     else
340       this->relocate(Buf, BufEnd, EObj.rels(RelSec));
341   }
342 }
343 
344 template <class ELFT>
345 void InputSection<ELFT>::replace(InputSection<ELFT> *Other) {
346   this->Align = std::max(this->Align, Other->Align);
347   Other->Repl = this->Repl;
348   Other->Live = false;
349 }
350 
351 template <class ELFT>
352 SplitInputSection<ELFT>::SplitInputSection(
353     ObjectFile<ELFT> *File, const Elf_Shdr *Header,
354     typename InputSectionBase<ELFT>::Kind SectionKind)
355     : InputSectionBase<ELFT>(File, Header, SectionKind) {}
356 
357 template <class ELFT>
358 EHInputSection<ELFT>::EHInputSection(ObjectFile<ELFT> *F,
359                                      const Elf_Shdr *Header)
360     : SplitInputSection<ELFT>(F, Header, InputSectionBase<ELFT>::EHFrame) {
361   // Mark .eh_frame sections as live by default because there are
362   // usually no relocations that point to .eh_frames. Otherwise,
363   // the garbage collector would drop all .eh_frame sections.
364   this->Live = true;
365 }
366 
367 template <class ELFT>
368 bool EHInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
369   return S->SectionKind == InputSectionBase<ELFT>::EHFrame;
370 }
371 
372 template <class ELFT>
373 typename EHInputSection<ELFT>::uintX_t
374 EHInputSection<ELFT>::getOffset(uintX_t Offset) {
375   // The file crtbeginT.o has relocations pointing to the start of an empty
376   // .eh_frame that is known to be the first in the link. It does that to
377   // identify the start of the output .eh_frame. Handle this special case.
378   if (this->getSectionHdr()->sh_size == 0)
379     return Offset;
380   std::pair<uintX_t, uintX_t> *I = this->getRangeAndSize(Offset).first;
381   uintX_t Base = I->second;
382   if (Base == uintX_t(-1))
383     return -1; // Not in the output
384 
385   uintX_t Addend = Offset - I->first;
386   return Base + Addend;
387 }
388 
389 template <class ELFT>
390 MergeInputSection<ELFT>::MergeInputSection(ObjectFile<ELFT> *F,
391                                            const Elf_Shdr *Header)
392     : SplitInputSection<ELFT>(F, Header, InputSectionBase<ELFT>::Merge) {}
393 
394 template <class ELFT>
395 bool MergeInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
396   return S->SectionKind == InputSectionBase<ELFT>::Merge;
397 }
398 
399 template <class ELFT>
400 std::pair<std::pair<typename ELFFile<ELFT>::uintX_t,
401                     typename ELFFile<ELFT>::uintX_t> *,
402           typename ELFFile<ELFT>::uintX_t>
403 SplitInputSection<ELFT>::getRangeAndSize(uintX_t Offset) {
404   ArrayRef<uint8_t> D = this->getSectionData();
405   StringRef Data((const char *)D.data(), D.size());
406   uintX_t Size = Data.size();
407   if (Offset >= Size)
408     fatal("Entry is past the end of the section");
409 
410   // Find the element this offset points to.
411   auto I = std::upper_bound(
412       Offsets.begin(), Offsets.end(), Offset,
413       [](const uintX_t &A, const std::pair<uintX_t, uintX_t> &B) {
414         return A < B.first;
415       });
416   uintX_t End = I == Offsets.end() ? Data.size() : I->first;
417   --I;
418   return std::make_pair(&*I, End);
419 }
420 
421 template <class ELFT>
422 typename MergeInputSection<ELFT>::uintX_t
423 MergeInputSection<ELFT>::getOffset(uintX_t Offset) {
424   std::pair<std::pair<uintX_t, uintX_t> *, uintX_t> T =
425       this->getRangeAndSize(Offset);
426   std::pair<uintX_t, uintX_t> *I = T.first;
427   uintX_t End = T.second;
428   uintX_t Start = I->first;
429 
430   // Compute the Addend and if the Base is cached, return.
431   uintX_t Addend = Offset - Start;
432   uintX_t &Base = I->second;
433   if (Base != uintX_t(-1))
434     return Base + Addend;
435 
436   // Map the base to the offset in the output section and cache it.
437   ArrayRef<uint8_t> D = this->getSectionData();
438   StringRef Data((const char *)D.data(), D.size());
439   StringRef Entry = Data.substr(Start, End - Start);
440   Base =
441       static_cast<MergeOutputSection<ELFT> *>(this->OutSec)->getOffset(Entry);
442   return Base + Addend;
443 }
444 
445 template <class ELFT>
446 MipsReginfoInputSection<ELFT>::MipsReginfoInputSection(ObjectFile<ELFT> *F,
447                                                        const Elf_Shdr *Hdr)
448     : InputSectionBase<ELFT>(F, Hdr, InputSectionBase<ELFT>::MipsReginfo) {
449   // Initialize this->Reginfo.
450   ArrayRef<uint8_t> D = this->getSectionData();
451   if (D.size() != sizeof(Elf_Mips_RegInfo<ELFT>))
452     fatal("Invalid size of .reginfo section");
453   Reginfo = reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(D.data());
454 }
455 
456 template <class ELFT>
457 bool MipsReginfoInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
458   return S->SectionKind == InputSectionBase<ELFT>::MipsReginfo;
459 }
460 
461 template class elf::InputSectionBase<ELF32LE>;
462 template class elf::InputSectionBase<ELF32BE>;
463 template class elf::InputSectionBase<ELF64LE>;
464 template class elf::InputSectionBase<ELF64BE>;
465 
466 template class elf::InputSection<ELF32LE>;
467 template class elf::InputSection<ELF32BE>;
468 template class elf::InputSection<ELF64LE>;
469 template class elf::InputSection<ELF64BE>;
470 
471 template class elf::EHInputSection<ELF32LE>;
472 template class elf::EHInputSection<ELF32BE>;
473 template class elf::EHInputSection<ELF64LE>;
474 template class elf::EHInputSection<ELF64BE>;
475 
476 template class elf::MergeInputSection<ELF32LE>;
477 template class elf::MergeInputSection<ELF32BE>;
478 template class elf::MergeInputSection<ELF64LE>;
479 template class elf::MergeInputSection<ELF64BE>;
480 
481 template class elf::MipsReginfoInputSection<ELF32LE>;
482 template class elf::MipsReginfoInputSection<ELF32BE>;
483 template class elf::MipsReginfoInputSection<ELF64LE>;
484 template class elf::MipsReginfoInputSection<ELF64BE>;
485