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