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