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 template <bool isRela>
134 void InputSectionBase<ELFT>::relocate(uint8_t *Buf, uint8_t *BufEnd,
135                                       RelIteratorRange<isRela> Rels) {
136   typedef Elf_Rel_Impl<ELFT, isRela> RelType;
137   size_t Num = Rels.end() - Rels.begin();
138   for (size_t I = 0; I < Num; ++I) {
139     const RelType &RI = *(Rels.begin() + I);
140     uint32_t SymIndex = RI.getSymbol(Config->Mips64EL);
141     uint32_t Type = RI.getType(Config->Mips64EL);
142     uintX_t Offset = getOffset(RI.r_offset);
143     if (Offset == (uintX_t)-1)
144       continue;
145 
146     uint8_t *BufLoc = Buf + Offset;
147     uintX_t AddrLoc = OutSec->getVA() + Offset;
148     auto NextRelocs = llvm::make_range(&RI, Rels.end());
149 
150     if (Target->isTlsLocalDynamicRel(Type) &&
151         !Target->canRelaxTls(Type, nullptr)) {
152       Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc,
153                           Out<ELFT>::Got->getTlsIndexVA() +
154                               getAddend<ELFT>(RI));
155       continue;
156     }
157 
158     const Elf_Shdr *SymTab = File->getSymbolTable();
159     SymbolBody *Body = nullptr;
160     if (SymIndex >= SymTab->sh_info)
161       Body = File->getSymbolBody(SymIndex)->repl();
162 
163     if (Target->canRelaxTls(Type, Body)) {
164       uintX_t SymVA;
165       if (!Body)
166         SymVA = getLocalRelTarget(*File, RI, 0);
167       else if (Target->needsGot(Type, *Body))
168         SymVA = Body->getGotVA<ELFT>();
169       else
170         SymVA = Body->getVA<ELFT>();
171       // By optimizing TLS relocations, it is sometimes needed to skip
172       // relocations that immediately follow TLS relocations. This function
173       // knows how many slots we need to skip.
174       I += Target->relaxTls(BufLoc, BufEnd, Type, AddrLoc, SymVA, Body);
175       continue;
176     }
177 
178     // Handle relocations for local symbols -- they never get
179     // resolved so we don't allocate a SymbolBody.
180     uintX_t A = getAddend<ELFT>(RI);
181     if (!Body) {
182       uintX_t SymVA = getLocalRelTarget(*File, RI, A);
183       if (Config->EMachine == EM_MIPS) {
184         if (Type == R_MIPS_GPREL16 || Type == R_MIPS_GPREL32)
185           // We need to adjust SymVA value in case of R_MIPS_GPREL16/32
186           // relocations because they use the following expression to calculate
187           // the relocation's result for local symbol: S + A + GP0 - G.
188           SymVA += File->getMipsGp0();
189         else if (Type == R_MIPS_GOT16)
190           // R_MIPS_GOT16 relocation against local symbol requires index of
191           // a local GOT entry which contains page address corresponds
192           // to the symbol address.
193           SymVA = Out<ELFT>::Got->getMipsLocalPageAddr(SymVA);
194       }
195       Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc, SymVA, 0,
196                           findMipsPairedReloc(Buf, SymIndex, Type, NextRelocs));
197       continue;
198     }
199 
200     if (Target->isTlsGlobalDynamicRel(Type) &&
201         !Target->canRelaxTls(Type, Body)) {
202       Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc,
203                           Out<ELFT>::Got->getGlobalDynAddr(*Body) +
204                               getAddend<ELFT>(RI));
205       continue;
206     }
207 
208     uintX_t SymVA = Body->getVA<ELFT>();
209     if (Target->needsPlt(Type, *Body)) {
210       SymVA = Body->getPltVA<ELFT>();
211     } else if (Target->needsGot(Type, *Body)) {
212       if (Config->EMachine == EM_MIPS && !canBePreempted(Body, true))
213         // Under some conditions relocations against non-local symbols require
214         // entries in the local part of MIPS GOT. In that case we need an entry
215         // initialized by full address of the symbol.
216         SymVA = Out<ELFT>::Got->getMipsLocalFullAddr(*Body);
217       else
218         SymVA = Body->getGotVA<ELFT>();
219       if (Body->IsTls)
220         Type = Target->getTlsGotRel(Type);
221     } else if (!Target->needsCopyRel(Type, *Body) &&
222                isa<SharedSymbol<ELFT>>(*Body)) {
223       continue;
224     } else if (Target->isTlsDynRel(Type, *Body)) {
225       continue;
226     } else if (Target->isSizeRel(Type) && canBePreempted(Body, false)) {
227       // A SIZE relocation is supposed to set a symbol size, but if a symbol
228       // can be preempted, the size at runtime may be different than link time.
229       // If that's the case, we leave the field alone rather than filling it
230       // with a possibly incorrect value.
231       continue;
232     } else if (Config->EMachine == EM_MIPS) {
233       if (Type == R_MIPS_HI16 && Body == Config->MipsGpDisp)
234         SymVA = getMipsGpAddr<ELFT>() - AddrLoc;
235       else if (Type == R_MIPS_LO16 && Body == Config->MipsGpDisp)
236         SymVA = getMipsGpAddr<ELFT>() - AddrLoc + 4;
237       else if (Body == Config->MipsLocalGp)
238         SymVA = getMipsGpAddr<ELFT>();
239     }
240     uintX_t Size = Body->getSize<ELFT>();
241     Target->relocateOne(BufLoc, BufEnd, Type, AddrLoc, SymVA + A, Size + A,
242                         findMipsPairedReloc(Buf, SymIndex, Type, NextRelocs));
243   }
244 }
245 
246 template <class ELFT> void InputSection<ELFT>::writeTo(uint8_t *Buf) {
247   if (this->Header->sh_type == SHT_NOBITS)
248     return;
249   // Copy section contents from source object file to output file.
250   ArrayRef<uint8_t> Data = this->getSectionData();
251   memcpy(Buf + OutSecOff, Data.data(), Data.size());
252 
253   ELFFile<ELFT> &EObj = this->File->getObj();
254   uint8_t *BufEnd = Buf + OutSecOff + Data.size();
255   // Iterate over all relocation sections that apply to this section.
256   for (const Elf_Shdr *RelSec : this->RelocSections) {
257     if (RelSec->sh_type == SHT_RELA)
258       this->relocate(Buf, BufEnd, EObj.relas(RelSec));
259     else
260       this->relocate(Buf, BufEnd, EObj.rels(RelSec));
261   }
262 }
263 
264 template <class ELFT>
265 SplitInputSection<ELFT>::SplitInputSection(
266     ObjectFile<ELFT> *File, const Elf_Shdr *Header,
267     typename InputSectionBase<ELFT>::Kind SectionKind)
268     : InputSectionBase<ELFT>(File, Header, SectionKind) {}
269 
270 template <class ELFT>
271 EHInputSection<ELFT>::EHInputSection(ObjectFile<ELFT> *F,
272                                      const Elf_Shdr *Header)
273     : SplitInputSection<ELFT>(F, Header, InputSectionBase<ELFT>::EHFrame) {
274   // Mark .eh_frame sections as live by default because there are
275   // usually no relocations that point to .eh_frames. Otherwise,
276   // the garbage collector would drop all .eh_frame sections.
277   this->Live = true;
278 }
279 
280 template <class ELFT>
281 bool EHInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
282   return S->SectionKind == InputSectionBase<ELFT>::EHFrame;
283 }
284 
285 template <class ELFT>
286 typename EHInputSection<ELFT>::uintX_t
287 EHInputSection<ELFT>::getOffset(uintX_t Offset) {
288   // The file crtbeginT.o has relocations pointing to the start of an empty
289   // .eh_frame that is known to be the first in the link. It does that to
290   // identify the start of the output .eh_frame. Handle this special case.
291   if (this->getSectionHdr()->sh_size == 0)
292     return Offset;
293   std::pair<uintX_t, uintX_t> *I = this->getRangeAndSize(Offset).first;
294   uintX_t Base = I->second;
295   if (Base == uintX_t(-1))
296     return -1; // Not in the output
297 
298   uintX_t Addend = Offset - I->first;
299   return Base + Addend;
300 }
301 
302 template <class ELFT>
303 MergeInputSection<ELFT>::MergeInputSection(ObjectFile<ELFT> *F,
304                                            const Elf_Shdr *Header)
305     : SplitInputSection<ELFT>(F, Header, InputSectionBase<ELFT>::Merge) {}
306 
307 template <class ELFT>
308 bool MergeInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
309   return S->SectionKind == InputSectionBase<ELFT>::Merge;
310 }
311 
312 template <class ELFT>
313 std::pair<std::pair<typename ELFFile<ELFT>::uintX_t,
314                     typename ELFFile<ELFT>::uintX_t> *,
315           typename ELFFile<ELFT>::uintX_t>
316 SplitInputSection<ELFT>::getRangeAndSize(uintX_t Offset) {
317   ArrayRef<uint8_t> D = this->getSectionData();
318   StringRef Data((const char *)D.data(), D.size());
319   uintX_t Size = Data.size();
320   if (Offset >= Size)
321     fatal("Entry is past the end of the section");
322 
323   // Find the element this offset points to.
324   auto I = std::upper_bound(
325       Offsets.begin(), Offsets.end(), Offset,
326       [](const uintX_t &A, const std::pair<uintX_t, uintX_t> &B) {
327         return A < B.first;
328       });
329   uintX_t End = I == Offsets.end() ? Data.size() : I->first;
330   --I;
331   return std::make_pair(&*I, End);
332 }
333 
334 template <class ELFT>
335 typename MergeInputSection<ELFT>::uintX_t
336 MergeInputSection<ELFT>::getOffset(uintX_t Offset) {
337   std::pair<std::pair<uintX_t, uintX_t> *, uintX_t> T =
338       this->getRangeAndSize(Offset);
339   std::pair<uintX_t, uintX_t> *I = T.first;
340   uintX_t End = T.second;
341   uintX_t Start = I->first;
342 
343   // Compute the Addend and if the Base is cached, return.
344   uintX_t Addend = Offset - Start;
345   uintX_t &Base = I->second;
346   if (Base != uintX_t(-1))
347     return Base + Addend;
348 
349   // Map the base to the offset in the output section and cache it.
350   ArrayRef<uint8_t> D = this->getSectionData();
351   StringRef Data((const char *)D.data(), D.size());
352   StringRef Entry = Data.substr(Start, End - Start);
353   Base =
354       static_cast<MergeOutputSection<ELFT> *>(this->OutSec)->getOffset(Entry);
355   return Base + Addend;
356 }
357 
358 template <class ELFT>
359 MipsReginfoInputSection<ELFT>::MipsReginfoInputSection(ObjectFile<ELFT> *F,
360                                                        const Elf_Shdr *Hdr)
361     : InputSectionBase<ELFT>(F, Hdr, InputSectionBase<ELFT>::MipsReginfo) {
362   // Initialize this->Reginfo.
363   ArrayRef<uint8_t> D = this->getSectionData();
364   if (D.size() != sizeof(Elf_Mips_RegInfo<ELFT>))
365     fatal("Invalid size of .reginfo section");
366   Reginfo = reinterpret_cast<const Elf_Mips_RegInfo<ELFT> *>(D.data());
367 }
368 
369 template <class ELFT>
370 bool MipsReginfoInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
371   return S->SectionKind == InputSectionBase<ELFT>::MipsReginfo;
372 }
373 
374 template class elf2::InputSectionBase<ELF32LE>;
375 template class elf2::InputSectionBase<ELF32BE>;
376 template class elf2::InputSectionBase<ELF64LE>;
377 template class elf2::InputSectionBase<ELF64BE>;
378 
379 template class elf2::InputSection<ELF32LE>;
380 template class elf2::InputSection<ELF32BE>;
381 template class elf2::InputSection<ELF64LE>;
382 template class elf2::InputSection<ELF64BE>;
383 
384 template class elf2::EHInputSection<ELF32LE>;
385 template class elf2::EHInputSection<ELF32BE>;
386 template class elf2::EHInputSection<ELF64LE>;
387 template class elf2::EHInputSection<ELF64BE>;
388 
389 template class elf2::MergeInputSection<ELF32LE>;
390 template class elf2::MergeInputSection<ELF32BE>;
391 template class elf2::MergeInputSection<ELF64LE>;
392 template class elf2::MergeInputSection<ELF64BE>;
393 
394 template class elf2::MipsReginfoInputSection<ELF32LE>;
395 template class elf2::MipsReginfoInputSection<ELF32BE>;
396 template class elf2::MipsReginfoInputSection<ELF64LE>;
397 template class elf2::MipsReginfoInputSection<ELF64BE>;
398