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