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