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