• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- InputSection.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "InputSection.h"
10 #include "Config.h"
11 #include "EhFrame.h"
12 #include "InputFiles.h"
13 #include "LinkerScript.h"
14 #include "OutputSections.h"
15 #include "Relocations.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "SyntheticSections.h"
19 #include "Target.h"
20 #include "Thunks.h"
21 #include "lld/Common/ErrorHandler.h"
22 #include "lld/Common/Memory.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Compression.h"
25 #include "llvm/Support/Endian.h"
26 #include "llvm/Support/Threading.h"
27 #include "llvm/Support/xxhash.h"
28 #include <algorithm>
29 #include <mutex>
30 #include <set>
31 #include <unordered_set>
32 #include <vector>
33 
34 using namespace llvm;
35 using namespace llvm::ELF;
36 using namespace llvm::object;
37 using namespace llvm::support;
38 using namespace llvm::support::endian;
39 using namespace llvm::sys;
40 using namespace lld;
41 using namespace lld::elf;
42 
43 std::vector<InputSectionBase *> elf::inputSections;
44 DenseSet<std::pair<const Symbol *, uint64_t>> elf::ppc64noTocRelax;
45 
46 // Returns a string to construct an error message.
toString(const InputSectionBase * sec)47 std::string lld::toString(const InputSectionBase *sec) {
48   return (toString(sec->file) + ":(" + sec->name + ")").str();
49 }
50 
51 template <class ELFT>
getSectionContents(ObjFile<ELFT> & file,const typename ELFT::Shdr & hdr)52 static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &file,
53                                             const typename ELFT::Shdr &hdr) {
54   if (hdr.sh_type == SHT_NOBITS)
55     return makeArrayRef<uint8_t>(nullptr, hdr.sh_size);
56   return check(file.getObj().getSectionContents(hdr));
57 }
58 
InputSectionBase(InputFile * file,uint64_t flags,uint32_t type,uint64_t entsize,uint32_t link,uint32_t info,uint32_t alignment,ArrayRef<uint8_t> data,StringRef name,Kind sectionKind)59 InputSectionBase::InputSectionBase(InputFile *file, uint64_t flags,
60                                    uint32_t type, uint64_t entsize,
61                                    uint32_t link, uint32_t info,
62                                    uint32_t alignment, ArrayRef<uint8_t> data,
63                                    StringRef name, Kind sectionKind)
64     : SectionBase(sectionKind, name, flags, entsize, alignment, type, info,
65                   link),
66       file(file), rawData(data) {
67   // In order to reduce memory allocation, we assume that mergeable
68   // sections are smaller than 4 GiB, which is not an unreasonable
69   // assumption as of 2017.
70   if (sectionKind == SectionBase::Merge && rawData.size() > UINT32_MAX)
71     error(toString(this) + ": section too large");
72 
73   numRelocations = 0;
74   areRelocsRela = false;
75 
76   // The ELF spec states that a value of 0 means the section has
77   // no alignment constraints.
78   uint32_t v = std::max<uint32_t>(alignment, 1);
79   if (!isPowerOf2_64(v))
80     fatal(toString(this) + ": sh_addralign is not a power of 2");
81   this->alignment = v;
82 
83   // In ELF, each section can be compressed by zlib, and if compressed,
84   // section name may be mangled by appending "z" (e.g. ".zdebug_info").
85   // If that's the case, demangle section name so that we can handle a
86   // section as if it weren't compressed.
87   if ((flags & SHF_COMPRESSED) || name.startswith(".zdebug")) {
88     if (!zlib::isAvailable())
89       error(toString(file) + ": contains a compressed section, " +
90             "but zlib is not available");
91     parseCompressedHeader();
92   }
93 }
94 
95 // Drop SHF_GROUP bit unless we are producing a re-linkable object file.
96 // SHF_GROUP is a marker that a section belongs to some comdat group.
97 // That flag doesn't make sense in an executable.
getFlags(uint64_t flags)98 static uint64_t getFlags(uint64_t flags) {
99   flags &= ~(uint64_t)SHF_INFO_LINK;
100   if (!config->relocatable)
101     flags &= ~(uint64_t)SHF_GROUP;
102   return flags;
103 }
104 
105 // GNU assembler 2.24 and LLVM 4.0.0's MC (the newest release as of
106 // March 2017) fail to infer section types for sections starting with
107 // ".init_array." or ".fini_array.". They set SHT_PROGBITS instead of
108 // SHF_INIT_ARRAY. As a result, the following assembler directive
109 // creates ".init_array.100" with SHT_PROGBITS, for example.
110 //
111 //   .section .init_array.100, "aw"
112 //
113 // This function forces SHT_{INIT,FINI}_ARRAY so that we can handle
114 // incorrect inputs as if they were correct from the beginning.
getType(uint64_t type,StringRef name)115 static uint64_t getType(uint64_t type, StringRef name) {
116   if (type == SHT_PROGBITS && name.startswith(".init_array."))
117     return SHT_INIT_ARRAY;
118   if (type == SHT_PROGBITS && name.startswith(".fini_array."))
119     return SHT_FINI_ARRAY;
120   return type;
121 }
122 
123 template <class ELFT>
InputSectionBase(ObjFile<ELFT> & file,const typename ELFT::Shdr & hdr,StringRef name,Kind sectionKind)124 InputSectionBase::InputSectionBase(ObjFile<ELFT> &file,
125                                    const typename ELFT::Shdr &hdr,
126                                    StringRef name, Kind sectionKind)
127     : InputSectionBase(&file, getFlags(hdr.sh_flags),
128                        getType(hdr.sh_type, name), hdr.sh_entsize, hdr.sh_link,
129                        hdr.sh_info, hdr.sh_addralign,
130                        getSectionContents(file, hdr), name, sectionKind) {
131   // We reject object files having insanely large alignments even though
132   // they are allowed by the spec. I think 4GB is a reasonable limitation.
133   // We might want to relax this in the future.
134   if (hdr.sh_addralign > UINT32_MAX)
135     fatal(toString(&file) + ": section sh_addralign is too large");
136 }
137 
getSize() const138 size_t InputSectionBase::getSize() const {
139   if (auto *s = dyn_cast<SyntheticSection>(this))
140     return s->getSize();
141   if (uncompressedSize >= 0)
142     return uncompressedSize;
143   return rawData.size() - bytesDropped;
144 }
145 
uncompress() const146 void InputSectionBase::uncompress() const {
147   size_t size = uncompressedSize;
148   char *uncompressedBuf;
149   {
150     static std::mutex mu;
151     std::lock_guard<std::mutex> lock(mu);
152     uncompressedBuf = bAlloc.Allocate<char>(size);
153   }
154 
155   if (Error e = zlib::uncompress(toStringRef(rawData), uncompressedBuf, size))
156     fatal(toString(this) +
157           ": uncompress failed: " + llvm::toString(std::move(e)));
158   rawData = makeArrayRef((uint8_t *)uncompressedBuf, size);
159   uncompressedSize = -1;
160 }
161 
getOffsetInFile() const162 uint64_t InputSectionBase::getOffsetInFile() const {
163   const uint8_t *fileStart = (const uint8_t *)file->mb.getBufferStart();
164   const uint8_t *secStart = data().begin();
165   return secStart - fileStart;
166 }
167 
getOffset(uint64_t offset) const168 uint64_t SectionBase::getOffset(uint64_t offset) const {
169   switch (kind()) {
170   case Output: {
171     auto *os = cast<OutputSection>(this);
172     // For output sections we treat offset -1 as the end of the section.
173     return offset == uint64_t(-1) ? os->size : offset;
174   }
175   case Regular:
176   case Synthetic:
177     return cast<InputSection>(this)->getOffset(offset);
178   case EHFrame:
179     // The file crtbeginT.o has relocations pointing to the start of an empty
180     // .eh_frame that is known to be the first in the link. It does that to
181     // identify the start of the output .eh_frame.
182     return offset;
183   case Merge:
184     const MergeInputSection *ms = cast<MergeInputSection>(this);
185     if (InputSection *isec = ms->getParent())
186       return isec->getOffset(ms->getParentOffset(offset));
187     return ms->getParentOffset(offset);
188   }
189   llvm_unreachable("invalid section kind");
190 }
191 
getVA(uint64_t offset) const192 uint64_t SectionBase::getVA(uint64_t offset) const {
193   const OutputSection *out = getOutputSection();
194   return (out ? out->addr : 0) + getOffset(offset);
195 }
196 
getOutputSection()197 OutputSection *SectionBase::getOutputSection() {
198   InputSection *sec;
199   if (auto *isec = dyn_cast<InputSection>(this))
200     sec = isec;
201   else if (auto *ms = dyn_cast<MergeInputSection>(this))
202     sec = ms->getParent();
203   else if (auto *eh = dyn_cast<EhInputSection>(this))
204     sec = eh->getParent();
205   else
206     return cast<OutputSection>(this);
207   return sec ? sec->getParent() : nullptr;
208 }
209 
210 // When a section is compressed, `rawData` consists with a header followed
211 // by zlib-compressed data. This function parses a header to initialize
212 // `uncompressedSize` member and remove the header from `rawData`.
parseCompressedHeader()213 void InputSectionBase::parseCompressedHeader() {
214   using Chdr64 = typename ELF64LE::Chdr;
215   using Chdr32 = typename ELF32LE::Chdr;
216 
217   // Old-style header
218   if (name.startswith(".zdebug")) {
219     if (!toStringRef(rawData).startswith("ZLIB")) {
220       error(toString(this) + ": corrupted compressed section header");
221       return;
222     }
223     rawData = rawData.slice(4);
224 
225     if (rawData.size() < 8) {
226       error(toString(this) + ": corrupted compressed section header");
227       return;
228     }
229 
230     uncompressedSize = read64be(rawData.data());
231     rawData = rawData.slice(8);
232 
233     // Restore the original section name.
234     // (e.g. ".zdebug_info" -> ".debug_info")
235     name = saver.save("." + name.substr(2));
236     return;
237   }
238 
239   assert(flags & SHF_COMPRESSED);
240   flags &= ~(uint64_t)SHF_COMPRESSED;
241 
242   // New-style 64-bit header
243   if (config->is64) {
244     if (rawData.size() < sizeof(Chdr64)) {
245       error(toString(this) + ": corrupted compressed section");
246       return;
247     }
248 
249     auto *hdr = reinterpret_cast<const Chdr64 *>(rawData.data());
250     if (hdr->ch_type != ELFCOMPRESS_ZLIB) {
251       error(toString(this) + ": unsupported compression type");
252       return;
253     }
254 
255     uncompressedSize = hdr->ch_size;
256     alignment = std::max<uint32_t>(hdr->ch_addralign, 1);
257     rawData = rawData.slice(sizeof(*hdr));
258     return;
259   }
260 
261   // New-style 32-bit header
262   if (rawData.size() < sizeof(Chdr32)) {
263     error(toString(this) + ": corrupted compressed section");
264     return;
265   }
266 
267   auto *hdr = reinterpret_cast<const Chdr32 *>(rawData.data());
268   if (hdr->ch_type != ELFCOMPRESS_ZLIB) {
269     error(toString(this) + ": unsupported compression type");
270     return;
271   }
272 
273   uncompressedSize = hdr->ch_size;
274   alignment = std::max<uint32_t>(hdr->ch_addralign, 1);
275   rawData = rawData.slice(sizeof(*hdr));
276 }
277 
getLinkOrderDep() const278 InputSection *InputSectionBase::getLinkOrderDep() const {
279   assert(flags & SHF_LINK_ORDER);
280   if (!link)
281     return nullptr;
282   return cast<InputSection>(file->getSections()[link]);
283 }
284 
285 // Find a function symbol that encloses a given location.
286 template <class ELFT>
getEnclosingFunction(uint64_t offset)287 Defined *InputSectionBase::getEnclosingFunction(uint64_t offset) {
288   for (Symbol *b : file->getSymbols())
289     if (Defined *d = dyn_cast<Defined>(b))
290       if (d->section == this && d->type == STT_FUNC && d->value <= offset &&
291           offset < d->value + d->size)
292         return d;
293   return nullptr;
294 }
295 
296 // Returns a source location string. Used to construct an error message.
297 template <class ELFT>
getLocation(uint64_t offset)298 std::string InputSectionBase::getLocation(uint64_t offset) {
299   std::string secAndOffset = (name + "+0x" + utohexstr(offset)).str();
300 
301   // We don't have file for synthetic sections.
302   if (getFile<ELFT>() == nullptr)
303     return (config->outputFile + ":(" + secAndOffset + ")")
304         .str();
305 
306   // First check if we can get desired values from debugging information.
307   if (Optional<DILineInfo> info = getFile<ELFT>()->getDILineInfo(this, offset))
308     return info->FileName + ":" + std::to_string(info->Line) + ":(" +
309            secAndOffset + ")";
310 
311   // File->sourceFile contains STT_FILE symbol that contains a
312   // source file name. If it's missing, we use an object file name.
313   std::string srcFile = std::string(getFile<ELFT>()->sourceFile);
314   if (srcFile.empty())
315     srcFile = toString(file);
316 
317   if (Defined *d = getEnclosingFunction<ELFT>(offset))
318     return srcFile + ":(function " + toString(*d) + ": " + secAndOffset + ")";
319 
320   // If there's no symbol, print out the offset in the section.
321   return (srcFile + ":(" + secAndOffset + ")");
322 }
323 
324 // This function is intended to be used for constructing an error message.
325 // The returned message looks like this:
326 //
327 //   foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
328 //
329 //  Returns an empty string if there's no way to get line info.
getSrcMsg(const Symbol & sym,uint64_t offset)330 std::string InputSectionBase::getSrcMsg(const Symbol &sym, uint64_t offset) {
331   return file->getSrcMsg(sym, *this, offset);
332 }
333 
334 // Returns a filename string along with an optional section name. This
335 // function is intended to be used for constructing an error
336 // message. The returned message looks like this:
337 //
338 //   path/to/foo.o:(function bar)
339 //
340 // or
341 //
342 //   path/to/foo.o:(function bar) in archive path/to/bar.a
getObjMsg(uint64_t off)343 std::string InputSectionBase::getObjMsg(uint64_t off) {
344   std::string filename = std::string(file->getName());
345 
346   std::string archive;
347   if (!file->archiveName.empty())
348     archive = " in archive " + file->archiveName;
349 
350   // Find a symbol that encloses a given location.
351   for (Symbol *b : file->getSymbols())
352     if (auto *d = dyn_cast<Defined>(b))
353       if (d->section == this && d->value <= off && off < d->value + d->size)
354         return filename + ":(" + toString(*d) + ")" + archive;
355 
356   // If there's no symbol, print out the offset in the section.
357   return (filename + ":(" + name + "+0x" + utohexstr(off) + ")" + archive)
358       .str();
359 }
360 
361 InputSection InputSection::discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), "");
362 
InputSection(InputFile * f,uint64_t flags,uint32_t type,uint32_t alignment,ArrayRef<uint8_t> data,StringRef name,Kind k)363 InputSection::InputSection(InputFile *f, uint64_t flags, uint32_t type,
364                            uint32_t alignment, ArrayRef<uint8_t> data,
365                            StringRef name, Kind k)
366     : InputSectionBase(f, flags, type,
367                        /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, alignment, data,
368                        name, k) {}
369 
370 template <class ELFT>
InputSection(ObjFile<ELFT> & f,const typename ELFT::Shdr & header,StringRef name)371 InputSection::InputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
372                            StringRef name)
373     : InputSectionBase(f, header, name, InputSectionBase::Regular) {}
374 
classof(const SectionBase * s)375 bool InputSection::classof(const SectionBase *s) {
376   return s->kind() == SectionBase::Regular ||
377          s->kind() == SectionBase::Synthetic;
378 }
379 
getParent() const380 OutputSection *InputSection::getParent() const {
381   return cast_or_null<OutputSection>(parent);
382 }
383 
384 // Copy SHT_GROUP section contents. Used only for the -r option.
copyShtGroup(uint8_t * buf)385 template <class ELFT> void InputSection::copyShtGroup(uint8_t *buf) {
386   // ELFT::Word is the 32-bit integral type in the target endianness.
387   using u32 = typename ELFT::Word;
388   ArrayRef<u32> from = getDataAs<u32>();
389   auto *to = reinterpret_cast<u32 *>(buf);
390 
391   // The first entry is not a section number but a flag.
392   *to++ = from[0];
393 
394   // Adjust section numbers because section numbers in an input object files are
395   // different in the output. We also need to handle combined or discarded
396   // members.
397   ArrayRef<InputSectionBase *> sections = file->getSections();
398   std::unordered_set<uint32_t> seen;
399   for (uint32_t idx : from.slice(1)) {
400     OutputSection *osec = sections[idx]->getOutputSection();
401     if (osec && seen.insert(osec->sectionIndex).second)
402       *to++ = osec->sectionIndex;
403   }
404 }
405 
getRelocatedSection() const406 InputSectionBase *InputSection::getRelocatedSection() const {
407   if (!file || (type != SHT_RELA && type != SHT_REL))
408     return nullptr;
409   ArrayRef<InputSectionBase *> sections = file->getSections();
410   return sections[info];
411 }
412 
413 // This is used for -r and --emit-relocs. We can't use memcpy to copy
414 // relocations because we need to update symbol table offset and section index
415 // for each relocation. So we copy relocations one by one.
416 template <class ELFT, class RelTy>
copyRelocations(uint8_t * buf,ArrayRef<RelTy> rels)417 void InputSection::copyRelocations(uint8_t *buf, ArrayRef<RelTy> rels) {
418   InputSectionBase *sec = getRelocatedSection();
419 
420   for (const RelTy &rel : rels) {
421     RelType type = rel.getType(config->isMips64EL);
422     const ObjFile<ELFT> *file = getFile<ELFT>();
423     Symbol &sym = file->getRelocTargetSym(rel);
424 
425     auto *p = reinterpret_cast<typename ELFT::Rela *>(buf);
426     buf += sizeof(RelTy);
427 
428     if (RelTy::IsRela)
429       p->r_addend = getAddend<ELFT>(rel);
430 
431     // Output section VA is zero for -r, so r_offset is an offset within the
432     // section, but for --emit-relocs it is a virtual address.
433     p->r_offset = sec->getVA(rel.r_offset);
434     p->setSymbolAndType(in.symTab->getSymbolIndex(&sym), type,
435                         config->isMips64EL);
436 
437     if (sym.type == STT_SECTION) {
438       // We combine multiple section symbols into only one per
439       // section. This means we have to update the addend. That is
440       // trivial for Elf_Rela, but for Elf_Rel we have to write to the
441       // section data. We do that by adding to the Relocation vector.
442 
443       // .eh_frame is horribly special and can reference discarded sections. To
444       // avoid having to parse and recreate .eh_frame, we just replace any
445       // relocation in it pointing to discarded sections with R_*_NONE, which
446       // hopefully creates a frame that is ignored at runtime. Also, don't warn
447       // on .gcc_except_table and debug sections.
448       //
449       // See the comment in maybeReportUndefined for PPC32 .got2 and PPC64 .toc
450       auto *d = dyn_cast<Defined>(&sym);
451       if (!d) {
452         if (!isDebugSection(*sec) && sec->name != ".eh_frame" &&
453             sec->name != ".gcc_except_table" && sec->name != ".got2" &&
454             sec->name != ".toc") {
455           uint32_t secIdx = cast<Undefined>(sym).discardedSecIdx;
456           Elf_Shdr_Impl<ELFT> sec =
457               CHECK(file->getObj().sections(), file)[secIdx];
458           warn("relocation refers to a discarded section: " +
459                CHECK(file->getObj().getSectionName(sec), file) +
460                "\n>>> referenced by " + getObjMsg(p->r_offset));
461         }
462         p->setSymbolAndType(0, 0, false);
463         continue;
464       }
465       SectionBase *section = d->section->repl;
466       if (!section->isLive()) {
467         p->setSymbolAndType(0, 0, false);
468         continue;
469       }
470 
471       int64_t addend = getAddend<ELFT>(rel);
472       const uint8_t *bufLoc = sec->data().begin() + rel.r_offset;
473       if (!RelTy::IsRela)
474         addend = target->getImplicitAddend(bufLoc, type);
475 
476       if (config->emachine == EM_MIPS &&
477           target->getRelExpr(type, sym, bufLoc) == R_MIPS_GOTREL) {
478         // Some MIPS relocations depend on "gp" value. By default,
479         // this value has 0x7ff0 offset from a .got section. But
480         // relocatable files produced by a compiler or a linker
481         // might redefine this default value and we must use it
482         // for a calculation of the relocation result. When we
483         // generate EXE or DSO it's trivial. Generating a relocatable
484         // output is more difficult case because the linker does
485         // not calculate relocations in this mode and loses
486         // individual "gp" values used by each input object file.
487         // As a workaround we add the "gp" value to the relocation
488         // addend and save it back to the file.
489         addend += sec->getFile<ELFT>()->mipsGp0;
490       }
491 
492       if (RelTy::IsRela)
493         p->r_addend = sym.getVA(addend) - section->getOutputSection()->addr;
494       else if (config->relocatable && type != target->noneRel)
495         sec->relocations.push_back({R_ABS, type, rel.r_offset, addend, &sym});
496     } else if (config->emachine == EM_PPC && type == R_PPC_PLTREL24 &&
497                p->r_addend >= 0x8000) {
498       // Similar to R_MIPS_GPREL{16,32}. If the addend of R_PPC_PLTREL24
499       // indicates that r30 is relative to the input section .got2
500       // (r_addend>=0x8000), after linking, r30 should be relative to the output
501       // section .got2 . To compensate for the shift, adjust r_addend by
502       // ppc32Got2OutSecOff.
503       p->r_addend += sec->file->ppc32Got2OutSecOff;
504     }
505   }
506 }
507 
508 // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
509 // references specially. The general rule is that the value of the symbol in
510 // this context is the address of the place P. A further special case is that
511 // branch relocations to an undefined weak reference resolve to the next
512 // instruction.
getARMUndefinedRelativeWeakVA(RelType type,uint32_t a,uint32_t p)513 static uint32_t getARMUndefinedRelativeWeakVA(RelType type, uint32_t a,
514                                               uint32_t p) {
515   switch (type) {
516   // Unresolved branch relocations to weak references resolve to next
517   // instruction, this will be either 2 or 4 bytes on from P.
518   case R_ARM_THM_JUMP11:
519     return p + 2 + a;
520   case R_ARM_CALL:
521   case R_ARM_JUMP24:
522   case R_ARM_PC24:
523   case R_ARM_PLT32:
524   case R_ARM_PREL31:
525   case R_ARM_THM_JUMP19:
526   case R_ARM_THM_JUMP24:
527     return p + 4 + a;
528   case R_ARM_THM_CALL:
529     // We don't want an interworking BLX to ARM
530     return p + 5 + a;
531   // Unresolved non branch pc-relative relocations
532   // R_ARM_TARGET2 which can be resolved relatively is not present as it never
533   // targets a weak-reference.
534   case R_ARM_MOVW_PREL_NC:
535   case R_ARM_MOVT_PREL:
536   case R_ARM_REL32:
537   case R_ARM_THM_ALU_PREL_11_0:
538   case R_ARM_THM_MOVW_PREL_NC:
539   case R_ARM_THM_MOVT_PREL:
540   case R_ARM_THM_PC12:
541     return p + a;
542   // p + a is unrepresentable as negative immediates can't be encoded.
543   case R_ARM_THM_PC8:
544     return p;
545   }
546   llvm_unreachable("ARM pc-relative relocation expected\n");
547 }
548 
549 // The comment above getARMUndefinedRelativeWeakVA applies to this function.
getAArch64UndefinedRelativeWeakVA(uint64_t type,uint64_t a,uint64_t p)550 static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t type, uint64_t a,
551                                                   uint64_t p) {
552   switch (type) {
553   // Unresolved branch relocations to weak references resolve to next
554   // instruction, this is 4 bytes on from P.
555   case R_AARCH64_CALL26:
556   case R_AARCH64_CONDBR19:
557   case R_AARCH64_JUMP26:
558   case R_AARCH64_TSTBR14:
559     return p + 4 + a;
560   // Unresolved non branch pc-relative relocations
561   case R_AARCH64_PREL16:
562   case R_AARCH64_PREL32:
563   case R_AARCH64_PREL64:
564   case R_AARCH64_ADR_PREL_LO21:
565   case R_AARCH64_LD_PREL_LO19:
566   case R_AARCH64_PLT32:
567     return p + a;
568   }
569   llvm_unreachable("AArch64 pc-relative relocation expected\n");
570 }
571 
572 // ARM SBREL relocations are of the form S + A - B where B is the static base
573 // The ARM ABI defines base to be "addressing origin of the output segment
574 // defining the symbol S". We defined the "addressing origin"/static base to be
575 // the base of the PT_LOAD segment containing the Sym.
576 // The procedure call standard only defines a Read Write Position Independent
577 // RWPI variant so in practice we should expect the static base to be the base
578 // of the RW segment.
getARMStaticBase(const Symbol & sym)579 static uint64_t getARMStaticBase(const Symbol &sym) {
580   OutputSection *os = sym.getOutputSection();
581   if (!os || !os->ptLoad || !os->ptLoad->firstSec)
582     fatal("SBREL relocation to " + sym.getName() + " without static base");
583   return os->ptLoad->firstSec->addr;
584 }
585 
586 // For R_RISCV_PC_INDIRECT (R_RISCV_PCREL_LO12_{I,S}), the symbol actually
587 // points the corresponding R_RISCV_PCREL_HI20 relocation, and the target VA
588 // is calculated using PCREL_HI20's symbol.
589 //
590 // This function returns the R_RISCV_PCREL_HI20 relocation from
591 // R_RISCV_PCREL_LO12's symbol and addend.
getRISCVPCRelHi20(const Symbol * sym,uint64_t addend)592 static Relocation *getRISCVPCRelHi20(const Symbol *sym, uint64_t addend) {
593   const Defined *d = cast<Defined>(sym);
594   if (!d->section) {
595     error("R_RISCV_PCREL_LO12 relocation points to an absolute symbol: " +
596           sym->getName());
597     return nullptr;
598   }
599   InputSection *isec = cast<InputSection>(d->section);
600 
601   if (addend != 0)
602     warn("Non-zero addend in R_RISCV_PCREL_LO12 relocation to " +
603          isec->getObjMsg(d->value) + " is ignored");
604 
605   // Relocations are sorted by offset, so we can use std::equal_range to do
606   // binary search.
607   Relocation r;
608   r.offset = d->value;
609   auto range =
610       std::equal_range(isec->relocations.begin(), isec->relocations.end(), r,
611                        [](const Relocation &lhs, const Relocation &rhs) {
612                          return lhs.offset < rhs.offset;
613                        });
614 
615   for (auto it = range.first; it != range.second; ++it)
616     if (it->type == R_RISCV_PCREL_HI20 || it->type == R_RISCV_GOT_HI20 ||
617         it->type == R_RISCV_TLS_GD_HI20 || it->type == R_RISCV_TLS_GOT_HI20)
618       return &*it;
619 
620   error("R_RISCV_PCREL_LO12 relocation points to " + isec->getObjMsg(d->value) +
621         " without an associated R_RISCV_PCREL_HI20 relocation");
622   return nullptr;
623 }
624 
625 // A TLS symbol's virtual address is relative to the TLS segment. Add a
626 // target-specific adjustment to produce a thread-pointer-relative offset.
getTlsTpOffset(const Symbol & s)627 static int64_t getTlsTpOffset(const Symbol &s) {
628   // On targets that support TLSDESC, _TLS_MODULE_BASE_@tpoff = 0.
629   if (&s == ElfSym::tlsModuleBase)
630     return 0;
631 
632   // There are 2 TLS layouts. Among targets we support, x86 uses TLS Variant 2
633   // while most others use Variant 1. At run time TP will be aligned to p_align.
634 
635   // Variant 1. TP will be followed by an optional gap (which is the size of 2
636   // pointers on ARM/AArch64, 0 on other targets), followed by alignment
637   // padding, then the static TLS blocks. The alignment padding is added so that
638   // (TP + gap + padding) is congruent to p_vaddr modulo p_align.
639   //
640   // Variant 2. Static TLS blocks, followed by alignment padding are placed
641   // before TP. The alignment padding is added so that (TP - padding -
642   // p_memsz) is congruent to p_vaddr modulo p_align.
643   PhdrEntry *tls = Out::tlsPhdr;
644   switch (config->emachine) {
645     // Variant 1.
646   case EM_ARM:
647   case EM_AARCH64:
648     return s.getVA(0) + config->wordsize * 2 +
649            ((tls->p_vaddr - config->wordsize * 2) & (tls->p_align - 1));
650   case EM_MIPS:
651   case EM_PPC:
652   case EM_PPC64:
653     // Adjusted Variant 1. TP is placed with a displacement of 0x7000, which is
654     // to allow a signed 16-bit offset to reach 0x1000 of TCB/thread-library
655     // data and 0xf000 of the program's TLS segment.
656     return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1)) - 0x7000;
657   case EM_RISCV:
658     return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1));
659 
660     // Variant 2.
661   case EM_HEXAGON:
662   case EM_SPARCV9:
663   case EM_386:
664   case EM_X86_64:
665     return s.getVA(0) - tls->p_memsz -
666            ((-tls->p_vaddr - tls->p_memsz) & (tls->p_align - 1));
667   default:
668     llvm_unreachable("unhandled Config->EMachine");
669   }
670 }
671 
getRelocTargetVA(const InputFile * file,RelType type,int64_t a,uint64_t p,const Symbol & sym,RelExpr expr)672 uint64_t InputSectionBase::getRelocTargetVA(const InputFile *file, RelType type,
673                                             int64_t a, uint64_t p,
674                                             const Symbol &sym, RelExpr expr) {
675   switch (expr) {
676   case R_ABS:
677   case R_DTPREL:
678   case R_RELAX_TLS_LD_TO_LE_ABS:
679   case R_RELAX_GOT_PC_NOPIC:
680   case R_RISCV_ADD:
681     return sym.getVA(a);
682   case R_ADDEND:
683     return a;
684   case R_ARM_SBREL:
685     return sym.getVA(a) - getARMStaticBase(sym);
686   case R_GOT:
687   case R_RELAX_TLS_GD_TO_IE_ABS:
688     return sym.getGotVA() + a;
689   case R_GOTONLY_PC:
690     return in.got->getVA() + a - p;
691   case R_GOTPLTONLY_PC:
692     return in.gotPlt->getVA() + a - p;
693   case R_GOTREL:
694   case R_PPC64_RELAX_TOC:
695     return sym.getVA(a) - in.got->getVA();
696   case R_GOTPLTREL:
697     return sym.getVA(a) - in.gotPlt->getVA();
698   case R_GOTPLT:
699   case R_RELAX_TLS_GD_TO_IE_GOTPLT:
700     return sym.getGotVA() + a - in.gotPlt->getVA();
701   case R_TLSLD_GOT_OFF:
702   case R_GOT_OFF:
703   case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
704     return sym.getGotOffset() + a;
705   case R_AARCH64_GOT_PAGE_PC:
706   case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
707     return getAArch64Page(sym.getGotVA() + a) - getAArch64Page(p);
708   case R_GOT_PC:
709   case R_RELAX_TLS_GD_TO_IE:
710     return sym.getGotVA() + a - p;
711   case R_MIPS_GOTREL:
712     return sym.getVA(a) - in.mipsGot->getGp(file);
713   case R_MIPS_GOT_GP:
714     return in.mipsGot->getGp(file) + a;
715   case R_MIPS_GOT_GP_PC: {
716     // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
717     // is _gp_disp symbol. In that case we should use the following
718     // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
719     // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
720     // microMIPS variants of these relocations use slightly different
721     // expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi()
722     // to correctly handle less-significant bit of the microMIPS symbol.
723     uint64_t v = in.mipsGot->getGp(file) + a - p;
724     if (type == R_MIPS_LO16 || type == R_MICROMIPS_LO16)
725       v += 4;
726     if (type == R_MICROMIPS_LO16 || type == R_MICROMIPS_HI16)
727       v -= 1;
728     return v;
729   }
730   case R_MIPS_GOT_LOCAL_PAGE:
731     // If relocation against MIPS local symbol requires GOT entry, this entry
732     // should be initialized by 'page address'. This address is high 16-bits
733     // of sum the symbol's value and the addend.
734     return in.mipsGot->getVA() + in.mipsGot->getPageEntryOffset(file, sym, a) -
735            in.mipsGot->getGp(file);
736   case R_MIPS_GOT_OFF:
737   case R_MIPS_GOT_OFF32:
738     // In case of MIPS if a GOT relocation has non-zero addend this addend
739     // should be applied to the GOT entry content not to the GOT entry offset.
740     // That is why we use separate expression type.
741     return in.mipsGot->getVA() + in.mipsGot->getSymEntryOffset(file, sym, a) -
742            in.mipsGot->getGp(file);
743   case R_MIPS_TLSGD:
744     return in.mipsGot->getVA() + in.mipsGot->getGlobalDynOffset(file, sym) -
745            in.mipsGot->getGp(file);
746   case R_MIPS_TLSLD:
747     return in.mipsGot->getVA() + in.mipsGot->getTlsIndexOffset(file) -
748            in.mipsGot->getGp(file);
749   case R_AARCH64_PAGE_PC: {
750     uint64_t val = sym.isUndefWeak() ? p + a : sym.getVA(a);
751     return getAArch64Page(val) - getAArch64Page(p);
752   }
753   case R_RISCV_PC_INDIRECT: {
754     if (const Relocation *hiRel = getRISCVPCRelHi20(&sym, a))
755       return getRelocTargetVA(file, hiRel->type, hiRel->addend, sym.getVA(),
756                               *hiRel->sym, hiRel->expr);
757     return 0;
758   }
759   case R_PC:
760   case R_ARM_PCA: {
761     uint64_t dest;
762     if (expr == R_ARM_PCA)
763       // Some PC relative ARM (Thumb) relocations align down the place.
764       p = p & 0xfffffffc;
765     if (sym.isUndefWeak()) {
766       // On ARM and AArch64 a branch to an undefined weak resolves to the
767       // next instruction, otherwise the place.
768       if (config->emachine == EM_ARM)
769         dest = getARMUndefinedRelativeWeakVA(type, a, p);
770       else if (config->emachine == EM_AARCH64)
771         dest = getAArch64UndefinedRelativeWeakVA(type, a, p);
772       else if (config->emachine == EM_PPC)
773         dest = p;
774       else
775         dest = sym.getVA(a);
776     } else {
777       dest = sym.getVA(a);
778     }
779     return dest - p;
780   }
781   case R_PLT:
782     return sym.getPltVA() + a;
783   case R_PLT_PC:
784   case R_PPC64_CALL_PLT:
785     return sym.getPltVA() + a - p;
786   case R_PPC32_PLTREL:
787     // R_PPC_PLTREL24 uses the addend (usually 0 or 0x8000) to indicate r30
788     // stores _GLOBAL_OFFSET_TABLE_ or .got2+0x8000. The addend is ignored for
789     // target VA computation.
790     return sym.getPltVA() - p;
791   case R_PPC64_CALL: {
792     uint64_t symVA = sym.getVA(a);
793     // If we have an undefined weak symbol, we might get here with a symbol
794     // address of zero. That could overflow, but the code must be unreachable,
795     // so don't bother doing anything at all.
796     if (!symVA)
797       return 0;
798 
799     // PPC64 V2 ABI describes two entry points to a function. The global entry
800     // point is used for calls where the caller and callee (may) have different
801     // TOC base pointers and r2 needs to be modified to hold the TOC base for
802     // the callee. For local calls the caller and callee share the same
803     // TOC base and so the TOC pointer initialization code should be skipped by
804     // branching to the local entry point.
805     return symVA - p + getPPC64GlobalEntryToLocalEntryOffset(sym.stOther);
806   }
807   case R_PPC64_TOCBASE:
808     return getPPC64TocBase() + a;
809   case R_RELAX_GOT_PC:
810   case R_PPC64_RELAX_GOT_PC:
811     return sym.getVA(a) - p;
812   case R_RELAX_TLS_GD_TO_LE:
813   case R_RELAX_TLS_IE_TO_LE:
814   case R_RELAX_TLS_LD_TO_LE:
815   case R_TLS:
816     // It is not very clear what to return if the symbol is undefined. With
817     // --noinhibit-exec, even a non-weak undefined reference may reach here.
818     // Just return A, which matches R_ABS, and the behavior of some dynamic
819     // loaders.
820     if (sym.isUndefined() || sym.isLazy())
821       return a;
822     return getTlsTpOffset(sym) + a;
823   case R_RELAX_TLS_GD_TO_LE_NEG:
824   case R_NEG_TLS:
825     if (sym.isUndefined())
826       return a;
827     return -getTlsTpOffset(sym) + a;
828   case R_SIZE:
829     return sym.getSize() + a;
830   case R_TLSDESC:
831     return in.got->getGlobalDynAddr(sym) + a;
832   case R_TLSDESC_PC:
833     return in.got->getGlobalDynAddr(sym) + a - p;
834   case R_AARCH64_TLSDESC_PAGE:
835     return getAArch64Page(in.got->getGlobalDynAddr(sym) + a) -
836            getAArch64Page(p);
837   case R_TLSGD_GOT:
838     return in.got->getGlobalDynOffset(sym) + a;
839   case R_TLSGD_GOTPLT:
840     return in.got->getVA() + in.got->getGlobalDynOffset(sym) + a - in.gotPlt->getVA();
841   case R_TLSGD_PC:
842     return in.got->getGlobalDynAddr(sym) + a - p;
843   case R_TLSLD_GOTPLT:
844     return in.got->getVA() + in.got->getTlsIndexOff() + a - in.gotPlt->getVA();
845   case R_TLSLD_GOT:
846     return in.got->getTlsIndexOff() + a;
847   case R_TLSLD_PC:
848     return in.got->getTlsIndexVA() + a - p;
849   default:
850     llvm_unreachable("invalid expression");
851   }
852 }
853 
854 // This function applies relocations to sections without SHF_ALLOC bit.
855 // Such sections are never mapped to memory at runtime. Debug sections are
856 // an example. Relocations in non-alloc sections are much easier to
857 // handle than in allocated sections because it will never need complex
858 // treatment such as GOT or PLT (because at runtime no one refers them).
859 // So, we handle relocations for non-alloc sections directly in this
860 // function as a performance optimization.
861 template <class ELFT, class RelTy>
relocateNonAlloc(uint8_t * buf,ArrayRef<RelTy> rels)862 void InputSection::relocateNonAlloc(uint8_t *buf, ArrayRef<RelTy> rels) {
863   const unsigned bits = sizeof(typename ELFT::uint) * 8;
864   const bool isDebug = isDebugSection(*this);
865   const bool isDebugLocOrRanges =
866       isDebug && (name == ".debug_loc" || name == ".debug_ranges");
867   const bool isDebugLine = isDebug && name == ".debug_line";
868   Optional<uint64_t> tombstone;
869   for (const auto &patAndValue : llvm::reverse(config->deadRelocInNonAlloc))
870     if (patAndValue.first.match(this->name)) {
871       tombstone = patAndValue.second;
872       break;
873     }
874 
875   for (const RelTy &rel : rels) {
876     RelType type = rel.getType(config->isMips64EL);
877 
878     // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations
879     // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed
880     // in 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we
881     // need to keep this bug-compatible code for a while.
882     if (config->emachine == EM_386 && type == R_386_GOTPC)
883       continue;
884 
885     uint64_t offset = rel.r_offset;
886     uint8_t *bufLoc = buf + offset;
887     int64_t addend = getAddend<ELFT>(rel);
888     if (!RelTy::IsRela)
889       addend += target->getImplicitAddend(bufLoc, type);
890 
891     Symbol &sym = getFile<ELFT>()->getRelocTargetSym(rel);
892     RelExpr expr = target->getRelExpr(type, sym, bufLoc);
893     if (expr == R_NONE)
894       continue;
895 
896     if (expr == R_SIZE) {
897       target->relocateNoSym(bufLoc, type,
898                             SignExtend64<bits>(sym.getSize() + addend));
899       continue;
900     }
901 
902     if (expr != R_ABS && expr != R_DTPREL && expr != R_RISCV_ADD) {
903       std::string msg = getLocation<ELFT>(offset) +
904                         ": has non-ABS relocation " + toString(type) +
905                         " against symbol '" + toString(sym) + "'";
906       if (expr != R_PC && expr != R_ARM_PCA) {
907         error(msg);
908         return;
909       }
910 
911       // If the control reaches here, we found a PC-relative relocation in a
912       // non-ALLOC section. Since non-ALLOC section is not loaded into memory
913       // at runtime, the notion of PC-relative doesn't make sense here. So,
914       // this is a usage error. However, GNU linkers historically accept such
915       // relocations without any errors and relocate them as if they were at
916       // address 0. For bug-compatibilty, we accept them with warnings. We
917       // know Steel Bank Common Lisp as of 2018 have this bug.
918       warn(msg);
919       target->relocateNoSym(
920           bufLoc, type,
921           SignExtend64<bits>(sym.getVA(addend - offset - outSecOff)));
922       continue;
923     }
924 
925     if (tombstone ||
926         (isDebug && (type == target->symbolicRel || expr == R_DTPREL))) {
927       // Resolve relocations in .debug_* referencing (discarded symbols or ICF
928       // folded section symbols) to a tombstone value. Resolving to addend is
929       // unsatisfactory because the result address range may collide with a
930       // valid range of low address, or leave multiple CUs claiming ownership of
931       // the same range of code, which may confuse consumers.
932       //
933       // To address the problems, we use -1 as a tombstone value for most
934       // .debug_* sections. We have to ignore the addend because we don't want
935       // to resolve an address attribute (which may have a non-zero addend) to
936       // -1+addend (wrap around to a low address).
937       //
938       // R_DTPREL type relocations represent an offset into the dynamic thread
939       // vector. The computed value is st_value plus a non-negative offset.
940       // Negative values are invalid, so -1 can be used as the tombstone value.
941       //
942       // If the referenced symbol is discarded (made Undefined), or the
943       // section defining the referenced symbol is garbage collected,
944       // sym.getOutputSection() is nullptr. `ds->section->repl != ds->section`
945       // catches the ICF folded case. However, resolving a relocation in
946       // .debug_line to -1 would stop debugger users from setting breakpoints on
947       // the folded-in function, so exclude .debug_line.
948       //
949       // For pre-DWARF-v5 .debug_loc and .debug_ranges, -1 is a reserved value
950       // (base address selection entry), use 1 (which is used by GNU ld for
951       // .debug_ranges).
952       //
953       // TODO To reduce disruption, we use 0 instead of -1 as the tombstone
954       // value. Enable -1 in a future release.
955       auto *ds = dyn_cast<Defined>(&sym);
956       if (!sym.getOutputSection() ||
957           (ds && ds->section->repl != ds->section && !isDebugLine)) {
958         // If -z dead-reloc-in-nonalloc= is specified, respect it.
959         const uint64_t value = tombstone ? SignExtend64<bits>(*tombstone)
960                                          : (isDebugLocOrRanges ? 1 : 0);
961         target->relocateNoSym(bufLoc, type, value);
962         continue;
963       }
964     }
965     target->relocateNoSym(bufLoc, type, SignExtend64<bits>(sym.getVA(addend)));
966   }
967 }
968 
969 // This is used when '-r' is given.
970 // For REL targets, InputSection::copyRelocations() may store artificial
971 // relocations aimed to update addends. They are handled in relocateAlloc()
972 // for allocatable sections, and this function does the same for
973 // non-allocatable sections, such as sections with debug information.
relocateNonAllocForRelocatable(InputSection * sec,uint8_t * buf)974 static void relocateNonAllocForRelocatable(InputSection *sec, uint8_t *buf) {
975   const unsigned bits = config->is64 ? 64 : 32;
976 
977   for (const Relocation &rel : sec->relocations) {
978     // InputSection::copyRelocations() adds only R_ABS relocations.
979     assert(rel.expr == R_ABS);
980     uint8_t *bufLoc = buf + rel.offset;
981     uint64_t targetVA = SignExtend64(rel.sym->getVA(rel.addend), bits);
982     target->relocate(bufLoc, rel, targetVA);
983   }
984 }
985 
986 template <class ELFT>
relocate(uint8_t * buf,uint8_t * bufEnd)987 void InputSectionBase::relocate(uint8_t *buf, uint8_t *bufEnd) {
988   if (flags & SHF_EXECINSTR)
989     adjustSplitStackFunctionPrologues<ELFT>(buf, bufEnd);
990 
991   if (flags & SHF_ALLOC) {
992     relocateAlloc(buf, bufEnd);
993     return;
994   }
995 
996   auto *sec = cast<InputSection>(this);
997   if (config->relocatable)
998     relocateNonAllocForRelocatable(sec, buf);
999   else if (sec->areRelocsRela)
1000     sec->relocateNonAlloc<ELFT>(buf, sec->template relas<ELFT>());
1001   else
1002     sec->relocateNonAlloc<ELFT>(buf, sec->template rels<ELFT>());
1003 }
1004 
relocateAlloc(uint8_t * buf,uint8_t * bufEnd)1005 void InputSectionBase::relocateAlloc(uint8_t *buf, uint8_t *bufEnd) {
1006   assert(flags & SHF_ALLOC);
1007   const unsigned bits = config->wordsize * 8;
1008   uint64_t lastPPCRelaxedRelocOff = UINT64_C(-1);
1009 
1010   for (const Relocation &rel : relocations) {
1011     if (rel.expr == R_NONE)
1012       continue;
1013     uint64_t offset = rel.offset;
1014     uint8_t *bufLoc = buf + offset;
1015     RelType type = rel.type;
1016 
1017     uint64_t addrLoc = getOutputSection()->addr + offset;
1018     if (auto *sec = dyn_cast<InputSection>(this))
1019       addrLoc += sec->outSecOff;
1020     RelExpr expr = rel.expr;
1021     uint64_t targetVA = SignExtend64(
1022         getRelocTargetVA(file, type, rel.addend, addrLoc, *rel.sym, expr),
1023         bits);
1024 
1025     switch (expr) {
1026     case R_RELAX_GOT_PC:
1027     case R_RELAX_GOT_PC_NOPIC:
1028       target->relaxGot(bufLoc, rel, targetVA);
1029       break;
1030     case R_PPC64_RELAX_GOT_PC: {
1031       // The R_PPC64_PCREL_OPT relocation must appear immediately after
1032       // R_PPC64_GOT_PCREL34 in the relocations table at the same offset.
1033       // We can only relax R_PPC64_PCREL_OPT if we have also relaxed
1034       // the associated R_PPC64_GOT_PCREL34 since only the latter has an
1035       // associated symbol. So save the offset when relaxing R_PPC64_GOT_PCREL34
1036       // and only relax the other if the saved offset matches.
1037       if (type == R_PPC64_GOT_PCREL34)
1038         lastPPCRelaxedRelocOff = offset;
1039       if (type == R_PPC64_PCREL_OPT && offset != lastPPCRelaxedRelocOff)
1040         break;
1041       target->relaxGot(bufLoc, rel, targetVA);
1042       break;
1043     }
1044     case R_PPC64_RELAX_TOC:
1045       // rel.sym refers to the STT_SECTION symbol associated to the .toc input
1046       // section. If an R_PPC64_TOC16_LO (.toc + addend) references the TOC
1047       // entry, there may be R_PPC64_TOC16_HA not paired with
1048       // R_PPC64_TOC16_LO_DS. Don't relax. This loses some relaxation
1049       // opportunities but is safe.
1050       if (ppc64noTocRelax.count({rel.sym, rel.addend}) ||
1051           !tryRelaxPPC64TocIndirection(rel, bufLoc))
1052         target->relocate(bufLoc, rel, targetVA);
1053       break;
1054     case R_RELAX_TLS_IE_TO_LE:
1055       target->relaxTlsIeToLe(bufLoc, rel, targetVA);
1056       break;
1057     case R_RELAX_TLS_LD_TO_LE:
1058     case R_RELAX_TLS_LD_TO_LE_ABS:
1059       target->relaxTlsLdToLe(bufLoc, rel, targetVA);
1060       break;
1061     case R_RELAX_TLS_GD_TO_LE:
1062     case R_RELAX_TLS_GD_TO_LE_NEG:
1063       target->relaxTlsGdToLe(bufLoc, rel, targetVA);
1064       break;
1065     case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
1066     case R_RELAX_TLS_GD_TO_IE:
1067     case R_RELAX_TLS_GD_TO_IE_ABS:
1068     case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
1069     case R_RELAX_TLS_GD_TO_IE_GOTPLT:
1070       target->relaxTlsGdToIe(bufLoc, rel, targetVA);
1071       break;
1072     case R_PPC64_CALL:
1073       // If this is a call to __tls_get_addr, it may be part of a TLS
1074       // sequence that has been relaxed and turned into a nop. In this
1075       // case, we don't want to handle it as a call.
1076       if (read32(bufLoc) == 0x60000000) // nop
1077         break;
1078 
1079       // Patch a nop (0x60000000) to a ld.
1080       if (rel.sym->needsTocRestore) {
1081         // gcc/gfortran 5.4, 6.3 and earlier versions do not add nop for
1082         // recursive calls even if the function is preemptible. This is not
1083         // wrong in the common case where the function is not preempted at
1084         // runtime. Just ignore.
1085         if ((bufLoc + 8 > bufEnd || read32(bufLoc + 4) != 0x60000000) &&
1086             rel.sym->file != file) {
1087           // Use substr(6) to remove the "__plt_" prefix.
1088           errorOrWarn(getErrorLocation(bufLoc) + "call to " +
1089                       lld::toString(*rel.sym).substr(6) +
1090                       " lacks nop, can't restore toc");
1091           break;
1092         }
1093         write32(bufLoc + 4, 0xe8410018); // ld %r2, 24(%r1)
1094       }
1095       target->relocate(bufLoc, rel, targetVA);
1096       break;
1097     default:
1098       target->relocate(bufLoc, rel, targetVA);
1099       break;
1100     }
1101   }
1102 
1103   // Apply jumpInstrMods.  jumpInstrMods are created when the opcode of
1104   // a jmp insn must be modified to shrink the jmp insn or to flip the jmp
1105   // insn.  This is primarily used to relax and optimize jumps created with
1106   // basic block sections.
1107   if (isa<InputSection>(this)) {
1108     for (const JumpInstrMod &jumpMod : jumpInstrMods) {
1109       uint64_t offset = jumpMod.offset;
1110       uint8_t *bufLoc = buf + offset;
1111       target->applyJumpInstrMod(bufLoc, jumpMod.original, jumpMod.size);
1112     }
1113   }
1114 }
1115 
1116 // For each function-defining prologue, find any calls to __morestack,
1117 // and replace them with calls to __morestack_non_split.
switchMorestackCallsToMorestackNonSplit(DenseSet<Defined * > & prologues,std::vector<Relocation * > & morestackCalls)1118 static void switchMorestackCallsToMorestackNonSplit(
1119     DenseSet<Defined *> &prologues, std::vector<Relocation *> &morestackCalls) {
1120 
1121   // If the target adjusted a function's prologue, all calls to
1122   // __morestack inside that function should be switched to
1123   // __morestack_non_split.
1124   Symbol *moreStackNonSplit = symtab->find("__morestack_non_split");
1125   if (!moreStackNonSplit) {
1126     error("Mixing split-stack objects requires a definition of "
1127           "__morestack_non_split");
1128     return;
1129   }
1130 
1131   // Sort both collections to compare addresses efficiently.
1132   llvm::sort(morestackCalls, [](const Relocation *l, const Relocation *r) {
1133     return l->offset < r->offset;
1134   });
1135   std::vector<Defined *> functions(prologues.begin(), prologues.end());
1136   llvm::sort(functions, [](const Defined *l, const Defined *r) {
1137     return l->value < r->value;
1138   });
1139 
1140   auto it = morestackCalls.begin();
1141   for (Defined *f : functions) {
1142     // Find the first call to __morestack within the function.
1143     while (it != morestackCalls.end() && (*it)->offset < f->value)
1144       ++it;
1145     // Adjust all calls inside the function.
1146     while (it != morestackCalls.end() && (*it)->offset < f->value + f->size) {
1147       (*it)->sym = moreStackNonSplit;
1148       ++it;
1149     }
1150   }
1151 }
1152 
enclosingPrologueAttempted(uint64_t offset,const DenseSet<Defined * > & prologues)1153 static bool enclosingPrologueAttempted(uint64_t offset,
1154                                        const DenseSet<Defined *> &prologues) {
1155   for (Defined *f : prologues)
1156     if (f->value <= offset && offset < f->value + f->size)
1157       return true;
1158   return false;
1159 }
1160 
1161 // If a function compiled for split stack calls a function not
1162 // compiled for split stack, then the caller needs its prologue
1163 // adjusted to ensure that the called function will have enough stack
1164 // available. Find those functions, and adjust their prologues.
1165 template <class ELFT>
adjustSplitStackFunctionPrologues(uint8_t * buf,uint8_t * end)1166 void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *buf,
1167                                                          uint8_t *end) {
1168   if (!getFile<ELFT>()->splitStack)
1169     return;
1170   DenseSet<Defined *> prologues;
1171   std::vector<Relocation *> morestackCalls;
1172 
1173   for (Relocation &rel : relocations) {
1174     // Local symbols can't possibly be cross-calls, and should have been
1175     // resolved long before this line.
1176     if (rel.sym->isLocal())
1177       continue;
1178 
1179     // Ignore calls into the split-stack api.
1180     if (rel.sym->getName().startswith("__morestack")) {
1181       if (rel.sym->getName().equals("__morestack"))
1182         morestackCalls.push_back(&rel);
1183       continue;
1184     }
1185 
1186     // A relocation to non-function isn't relevant. Sometimes
1187     // __morestack is not marked as a function, so this check comes
1188     // after the name check.
1189     if (rel.sym->type != STT_FUNC)
1190       continue;
1191 
1192     // If the callee's-file was compiled with split stack, nothing to do.  In
1193     // this context, a "Defined" symbol is one "defined by the binary currently
1194     // being produced". So an "undefined" symbol might be provided by a shared
1195     // library. It is not possible to tell how such symbols were compiled, so be
1196     // conservative.
1197     if (Defined *d = dyn_cast<Defined>(rel.sym))
1198       if (InputSection *isec = cast_or_null<InputSection>(d->section))
1199         if (!isec || !isec->getFile<ELFT>() || isec->getFile<ELFT>()->splitStack)
1200           continue;
1201 
1202     if (enclosingPrologueAttempted(rel.offset, prologues))
1203       continue;
1204 
1205     if (Defined *f = getEnclosingFunction<ELFT>(rel.offset)) {
1206       prologues.insert(f);
1207       if (target->adjustPrologueForCrossSplitStack(buf + f->value, end,
1208                                                    f->stOther))
1209         continue;
1210       if (!getFile<ELFT>()->someNoSplitStack)
1211         error(lld::toString(this) + ": " + f->getName() +
1212               " (with -fsplit-stack) calls " + rel.sym->getName() +
1213               " (without -fsplit-stack), but couldn't adjust its prologue");
1214     }
1215   }
1216 
1217   if (target->needsMoreStackNonSplit)
1218     switchMorestackCallsToMorestackNonSplit(prologues, morestackCalls);
1219 }
1220 
writeTo(uint8_t * buf)1221 template <class ELFT> void InputSection::writeTo(uint8_t *buf) {
1222   if (type == SHT_NOBITS)
1223     return;
1224 
1225   if (auto *s = dyn_cast<SyntheticSection>(this)) {
1226     s->writeTo(buf + outSecOff);
1227     return;
1228   }
1229 
1230   // If -r or --emit-relocs is given, then an InputSection
1231   // may be a relocation section.
1232   if (type == SHT_RELA) {
1233     copyRelocations<ELFT>(buf + outSecOff, getDataAs<typename ELFT::Rela>());
1234     return;
1235   }
1236   if (type == SHT_REL) {
1237     copyRelocations<ELFT>(buf + outSecOff, getDataAs<typename ELFT::Rel>());
1238     return;
1239   }
1240 
1241   // If -r is given, we may have a SHT_GROUP section.
1242   if (type == SHT_GROUP) {
1243     copyShtGroup<ELFT>(buf + outSecOff);
1244     return;
1245   }
1246 
1247   // If this is a compressed section, uncompress section contents directly
1248   // to the buffer.
1249   if (uncompressedSize >= 0) {
1250     size_t size = uncompressedSize;
1251     if (Error e = zlib::uncompress(toStringRef(rawData),
1252                                    (char *)(buf + outSecOff), size))
1253       fatal(toString(this) +
1254             ": uncompress failed: " + llvm::toString(std::move(e)));
1255     uint8_t *bufEnd = buf + outSecOff + size;
1256     relocate<ELFT>(buf + outSecOff, bufEnd);
1257     return;
1258   }
1259 
1260   // Copy section contents from source object file to output file
1261   // and then apply relocations.
1262   memcpy(buf + outSecOff, data().data(), data().size());
1263   uint8_t *bufEnd = buf + outSecOff + data().size();
1264   relocate<ELFT>(buf + outSecOff, bufEnd);
1265 }
1266 
replace(InputSection * other)1267 void InputSection::replace(InputSection *other) {
1268   alignment = std::max(alignment, other->alignment);
1269 
1270   // When a section is replaced with another section that was allocated to
1271   // another partition, the replacement section (and its associated sections)
1272   // need to be placed in the main partition so that both partitions will be
1273   // able to access it.
1274   if (partition != other->partition) {
1275     partition = 1;
1276     for (InputSection *isec : dependentSections)
1277       isec->partition = 1;
1278   }
1279 
1280   other->repl = repl;
1281   other->markDead();
1282 }
1283 
1284 template <class ELFT>
EhInputSection(ObjFile<ELFT> & f,const typename ELFT::Shdr & header,StringRef name)1285 EhInputSection::EhInputSection(ObjFile<ELFT> &f,
1286                                const typename ELFT::Shdr &header,
1287                                StringRef name)
1288     : InputSectionBase(f, header, name, InputSectionBase::EHFrame) {}
1289 
getParent() const1290 SyntheticSection *EhInputSection::getParent() const {
1291   return cast_or_null<SyntheticSection>(parent);
1292 }
1293 
1294 // Returns the index of the first relocation that points to a region between
1295 // Begin and Begin+Size.
1296 template <class IntTy, class RelTy>
getReloc(IntTy begin,IntTy size,const ArrayRef<RelTy> & rels,unsigned & relocI)1297 static unsigned getReloc(IntTy begin, IntTy size, const ArrayRef<RelTy> &rels,
1298                          unsigned &relocI) {
1299   // Start search from RelocI for fast access. That works because the
1300   // relocations are sorted in .eh_frame.
1301   for (unsigned n = rels.size(); relocI < n; ++relocI) {
1302     const RelTy &rel = rels[relocI];
1303     if (rel.r_offset < begin)
1304       continue;
1305 
1306     if (rel.r_offset < begin + size)
1307       return relocI;
1308     return -1;
1309   }
1310   return -1;
1311 }
1312 
1313 // .eh_frame is a sequence of CIE or FDE records.
1314 // This function splits an input section into records and returns them.
split()1315 template <class ELFT> void EhInputSection::split() {
1316   if (areRelocsRela)
1317     split<ELFT>(relas<ELFT>());
1318   else
1319     split<ELFT>(rels<ELFT>());
1320 }
1321 
1322 template <class ELFT, class RelTy>
split(ArrayRef<RelTy> rels)1323 void EhInputSection::split(ArrayRef<RelTy> rels) {
1324   unsigned relI = 0;
1325   for (size_t off = 0, end = data().size(); off != end;) {
1326     size_t size = readEhRecordSize(this, off);
1327     pieces.emplace_back(off, this, size, getReloc(off, size, rels, relI));
1328     // The empty record is the end marker.
1329     if (size == 4)
1330       break;
1331     off += size;
1332   }
1333 }
1334 
findNull(StringRef s,size_t entSize)1335 static size_t findNull(StringRef s, size_t entSize) {
1336   // Optimize the common case.
1337   if (entSize == 1)
1338     return s.find(0);
1339 
1340   for (unsigned i = 0, n = s.size(); i != n; i += entSize) {
1341     const char *b = s.begin() + i;
1342     if (std::all_of(b, b + entSize, [](char c) { return c == 0; }))
1343       return i;
1344   }
1345   return StringRef::npos;
1346 }
1347 
getParent() const1348 SyntheticSection *MergeInputSection::getParent() const {
1349   return cast_or_null<SyntheticSection>(parent);
1350 }
1351 
1352 // Split SHF_STRINGS section. Such section is a sequence of
1353 // null-terminated strings.
splitStrings(ArrayRef<uint8_t> data,size_t entSize)1354 void MergeInputSection::splitStrings(ArrayRef<uint8_t> data, size_t entSize) {
1355   size_t off = 0;
1356   bool isAlloc = flags & SHF_ALLOC;
1357   StringRef s = toStringRef(data);
1358 
1359   while (!s.empty()) {
1360     size_t end = findNull(s, entSize);
1361     if (end == StringRef::npos)
1362       fatal(toString(this) + ": string is not null terminated");
1363     size_t size = end + entSize;
1364 
1365     pieces.emplace_back(off, xxHash64(s.substr(0, size)), !isAlloc);
1366     s = s.substr(size);
1367     off += size;
1368   }
1369 }
1370 
1371 // Split non-SHF_STRINGS section. Such section is a sequence of
1372 // fixed size records.
splitNonStrings(ArrayRef<uint8_t> data,size_t entSize)1373 void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> data,
1374                                         size_t entSize) {
1375   size_t size = data.size();
1376   assert((size % entSize) == 0);
1377   bool isAlloc = flags & SHF_ALLOC;
1378 
1379   for (size_t i = 0; i != size; i += entSize)
1380     pieces.emplace_back(i, xxHash64(data.slice(i, entSize)), !isAlloc);
1381 }
1382 
1383 template <class ELFT>
MergeInputSection(ObjFile<ELFT> & f,const typename ELFT::Shdr & header,StringRef name)1384 MergeInputSection::MergeInputSection(ObjFile<ELFT> &f,
1385                                      const typename ELFT::Shdr &header,
1386                                      StringRef name)
1387     : InputSectionBase(f, header, name, InputSectionBase::Merge) {}
1388 
MergeInputSection(uint64_t flags,uint32_t type,uint64_t entsize,ArrayRef<uint8_t> data,StringRef name)1389 MergeInputSection::MergeInputSection(uint64_t flags, uint32_t type,
1390                                      uint64_t entsize, ArrayRef<uint8_t> data,
1391                                      StringRef name)
1392     : InputSectionBase(nullptr, flags, type, entsize, /*Link*/ 0, /*Info*/ 0,
1393                        /*Alignment*/ entsize, data, name, SectionBase::Merge) {}
1394 
1395 // This function is called after we obtain a complete list of input sections
1396 // that need to be linked. This is responsible to split section contents
1397 // into small chunks for further processing.
1398 //
1399 // Note that this function is called from parallelForEach. This must be
1400 // thread-safe (i.e. no memory allocation from the pools).
splitIntoPieces()1401 void MergeInputSection::splitIntoPieces() {
1402   assert(pieces.empty());
1403 
1404   if (flags & SHF_STRINGS)
1405     splitStrings(data(), entsize);
1406   else
1407     splitNonStrings(data(), entsize);
1408 }
1409 
getSectionPiece(uint64_t offset)1410 SectionPiece *MergeInputSection::getSectionPiece(uint64_t offset) {
1411   if (this->data().size() <= offset)
1412     fatal(toString(this) + ": offset is outside the section");
1413 
1414   // If Offset is not at beginning of a section piece, it is not in the map.
1415   // In that case we need to  do a binary search of the original section piece vector.
1416   auto it = partition_point(
1417       pieces, [=](SectionPiece p) { return p.inputOff <= offset; });
1418   return &it[-1];
1419 }
1420 
1421 // Returns the offset in an output section for a given input offset.
1422 // Because contents of a mergeable section is not contiguous in output,
1423 // it is not just an addition to a base output offset.
getParentOffset(uint64_t offset) const1424 uint64_t MergeInputSection::getParentOffset(uint64_t offset) const {
1425   // If Offset is not at beginning of a section piece, it is not in the map.
1426   // In that case we need to search from the original section piece vector.
1427   const SectionPiece &piece =
1428       *(const_cast<MergeInputSection *>(this)->getSectionPiece (offset));
1429   uint64_t addend = offset - piece.inputOff;
1430   return piece.outputOff + addend;
1431 }
1432 
1433 template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
1434                                     StringRef);
1435 template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
1436                                     StringRef);
1437 template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
1438                                     StringRef);
1439 template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
1440                                     StringRef);
1441 
1442 template std::string InputSectionBase::getLocation<ELF32LE>(uint64_t);
1443 template std::string InputSectionBase::getLocation<ELF32BE>(uint64_t);
1444 template std::string InputSectionBase::getLocation<ELF64LE>(uint64_t);
1445 template std::string InputSectionBase::getLocation<ELF64BE>(uint64_t);
1446 
1447 template void InputSection::writeTo<ELF32LE>(uint8_t *);
1448 template void InputSection::writeTo<ELF32BE>(uint8_t *);
1449 template void InputSection::writeTo<ELF64LE>(uint8_t *);
1450 template void InputSection::writeTo<ELF64BE>(uint8_t *);
1451 
1452 template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
1453                                               const ELF32LE::Shdr &, StringRef);
1454 template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
1455                                               const ELF32BE::Shdr &, StringRef);
1456 template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
1457                                               const ELF64LE::Shdr &, StringRef);
1458 template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
1459                                               const ELF64BE::Shdr &, StringRef);
1460 
1461 template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
1462                                         const ELF32LE::Shdr &, StringRef);
1463 template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
1464                                         const ELF32BE::Shdr &, StringRef);
1465 template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
1466                                         const ELF64LE::Shdr &, StringRef);
1467 template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
1468                                         const ELF64BE::Shdr &, StringRef);
1469 
1470 template void EhInputSection::split<ELF32LE>();
1471 template void EhInputSection::split<ELF32BE>();
1472 template void EhInputSection::split<ELF64LE>();
1473 template void EhInputSection::split<ELF64BE>();
1474