19d06ab6dSRafael Espindola //===- InputSection.cpp ---------------------------------------------------===//
29d06ab6dSRafael Espindola //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
69d06ab6dSRafael Espindola //
79d06ab6dSRafael Espindola //===----------------------------------------------------------------------===//
89d06ab6dSRafael Espindola
99d06ab6dSRafael Espindola #include "InputSection.h"
10551dfd88SRafael Espindola #include "Config.h"
119d06ab6dSRafael Espindola #include "InputFiles.h"
129d06ab6dSRafael Espindola #include "OutputSections.h"
13c3a44b2fSEugene Leviant #include "Relocations.h"
144fd84c18SSterling Augustine #include "SymbolTable.h"
15d26b52fdSRafael Espindola #include "Symbols.h"
1641ca327bSEugene Leviant #include "SyntheticSections.h"
1701205f79SRafael Espindola #include "Target.h"
1883d59e05SAlexandre Ganea #include "lld/Common/CommonLinkerContext.h"
1938a28416SRui Ueyama #include "llvm/Support/Compiler.h"
20602fbee9SGeorge Rimar #include "llvm/Support/Compression.h"
21860fbf09SSimon Atanasyan #include "llvm/Support/Endian.h"
2246557f94SRui Ueyama #include "llvm/Support/xxhash.h"
234fd84c18SSterling Augustine #include <algorithm>
242555952bSRui Ueyama #include <mutex>
254fd84c18SSterling Augustine #include <vector>
26860fbf09SSimon Atanasyan
279d06ab6dSRafael Espindola using namespace llvm;
289d06ab6dSRafael Espindola using namespace llvm::ELF;
299d06ab6dSRafael Espindola using namespace llvm::object;
3005384080SRui Ueyama using namespace llvm::support;
31860fbf09SSimon Atanasyan using namespace llvm::support::endian;
32b8760203SRui Ueyama using namespace llvm::sys;
3307837b8fSFangrui Song using namespace lld;
3407837b8fSFangrui Song using namespace lld::elf;
359d06ab6dSRafael Espindola
36ba948c5aSFangrui Song SmallVector<InputSectionBase *, 0> elf::inputSections;
3707837b8fSFangrui Song DenseSet<std::pair<const Symbol *, uint64_t>> elf::ppc64noTocRelax;
3807837b8fSFangrui Song
393fc0f7e5SRui Ueyama // Returns a string to construct an error message.
toString(const InputSectionBase * sec)4007837b8fSFangrui Song std::string lld::toString(const InputSectionBase *sec) {
413837f427SRui Ueyama return (toString(sec->file) + ":(" + sec->name + ")").str();
423fc0f7e5SRui Ueyama }
433fc0f7e5SRui Ueyama
449d06ab6dSRafael Espindola template <class ELFT>
getSectionContents(ObjFile<ELFT> & file,const typename ELFT::Shdr & hdr)453837f427SRui Ueyama static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &file,
463837f427SRui Ueyama const typename ELFT::Shdr &hdr) {
473837f427SRui Ueyama if (hdr.sh_type == SHT_NOBITS)
483837f427SRui Ueyama return makeArrayRef<uint8_t>(nullptr, hdr.sh_size);
494845531fSGeorgii Rymar return check(file.getObj().getSectionContents(hdr));
50c7e1e034SRafael Espindola }
51c7e1e034SRafael Espindola
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)523837f427SRui Ueyama InputSectionBase::InputSectionBase(InputFile *file, uint64_t flags,
533837f427SRui Ueyama uint32_t type, uint64_t entsize,
543837f427SRui Ueyama uint32_t link, uint32_t info,
553837f427SRui Ueyama uint32_t alignment, ArrayRef<uint8_t> data,
563837f427SRui Ueyama StringRef name, Kind sectionKind)
573837f427SRui Ueyama : SectionBase(sectionKind, name, flags, entsize, alignment, type, info,
583837f427SRui Ueyama link),
593837f427SRui Ueyama file(file), rawData(data) {
605c73c49cSRafael Espindola // In order to reduce memory allocation, we assume that mergeable
615c73c49cSRafael Espindola // sections are smaller than 4 GiB, which is not an unreasonable
625c73c49cSRafael Espindola // assumption as of 2017.
633837f427SRui Ueyama if (sectionKind == SectionBase::Merge && rawData.size() > UINT32_MAX)
645c73c49cSRafael Espindola error(toString(this) + ": section too large");
655c73c49cSRafael Espindola
665ac58917SRui Ueyama // The ELF spec states that a value of 0 means the section has
675976a3f5SNico Weber // no alignment constraints.
683837f427SRui Ueyama uint32_t v = std::max<uint32_t>(alignment, 1);
693837f427SRui Ueyama if (!isPowerOf2_64(v))
70cc19dc75SGeorge Rimar fatal(toString(this) + ": sh_addralign is not a power of 2");
713837f427SRui Ueyama this->alignment = v;
72e28c1464SRui Ueyama
73e09f77d3SFangrui Song // If SHF_COMPRESSED is set, parse the header. The legacy .zdebug format is no
74e09f77d3SFangrui Song // longer supported.
75dd74d311SFangrui Song if (flags & SHF_COMPRESSED)
7617a39aecSFangrui Song invokeELFT(parseCompressedHeader);
77e28c1464SRui Ueyama }
78c159c967SRafael Espindola
791c837b5fSRui Ueyama // Drop SHF_GROUP bit unless we are producing a re-linkable object file.
801c837b5fSRui Ueyama // SHF_GROUP is a marker that a section belongs to some comdat group.
811c837b5fSRui Ueyama // That flag doesn't make sense in an executable.
getFlags(uint64_t flags)823837f427SRui Ueyama static uint64_t getFlags(uint64_t flags) {
833837f427SRui Ueyama flags &= ~(uint64_t)SHF_INFO_LINK;
843837f427SRui Ueyama if (!config->relocatable)
853837f427SRui Ueyama flags &= ~(uint64_t)SHF_GROUP;
863837f427SRui Ueyama return flags;
871c837b5fSRui Ueyama }
881c837b5fSRui Ueyama
890e090522SRafael Espindola template <class ELFT>
InputSectionBase(ObjFile<ELFT> & file,const typename ELFT::Shdr & hdr,StringRef name,Kind sectionKind)903837f427SRui Ueyama InputSectionBase::InputSectionBase(ObjFile<ELFT> &file,
913837f427SRui Ueyama const typename ELFT::Shdr &hdr,
923837f427SRui Ueyama StringRef name, Kind sectionKind)
9343753f8fSFangrui Song : InputSectionBase(&file, getFlags(hdr.sh_flags), hdr.sh_type,
9443753f8fSFangrui Song hdr.sh_entsize, hdr.sh_link, hdr.sh_info,
9543753f8fSFangrui Song hdr.sh_addralign, getSectionContents(file, hdr), name,
9643753f8fSFangrui Song sectionKind) {
97fcd208fdSRafael Espindola // We reject object files having insanely large alignments even though
98fcd208fdSRafael Espindola // they are allowed by the spec. I think 4GB is a reasonable limitation.
99fcd208fdSRafael Espindola // We might want to relax this in the future.
1003837f427SRui Ueyama if (hdr.sh_addralign > UINT32_MAX)
1013837f427SRui Ueyama fatal(toString(&file) + ": section sh_addralign is too large");
102c4681203SEugene Leviant }
1030e090522SRafael Espindola
getSize() const10476b6bd35SRafael Espindola size_t InputSectionBase::getSize() const {
1053837f427SRui Ueyama if (auto *s = dyn_cast<SyntheticSection>(this))
1063837f427SRui Ueyama return s->getSize();
1073837f427SRui Ueyama if (uncompressedSize >= 0)
1083837f427SRui Ueyama return uncompressedSize;
10994317878SSriraman Tallam return rawData.size() - bytesDropped;
110e28c1464SRui Ueyama }
11141ca327bSEugene Leviant
uncompress() const112e28c1464SRui Ueyama void InputSectionBase::uncompress() const {
1133837f427SRui Ueyama size_t size = uncompressedSize;
114*e690137dSFangrui Song uint8_t *uncompressedBuf;
115e2b8c40aSPeter Collingbourne {
1163837f427SRui Ueyama static std::mutex mu;
1173837f427SRui Ueyama std::lock_guard<std::mutex> lock(mu);
118*e690137dSFangrui Song uncompressedBuf = bAlloc().Allocate<uint8_t>(size);
119e2b8c40aSPeter Collingbourne }
120e28c1464SRui Ueyama
121*e690137dSFangrui Song if (Error e = compression::zlib::uncompress(rawData, uncompressedBuf, size))
122e28c1464SRui Ueyama fatal(toString(this) +
1233837f427SRui Ueyama ": uncompress failed: " + llvm::toString(std::move(e)));
124*e690137dSFangrui Song rawData = makeArrayRef(uncompressedBuf, size);
1253837f427SRui Ueyama uncompressedSize = -1;
1261a541123SRafael Espindola }
1271a541123SRafael Espindola
relsOrRelas() const128ecc93ed2SFangrui Song template <class ELFT> RelsOrRelas<ELFT> InputSectionBase::relsOrRelas() const {
129ecc93ed2SFangrui Song if (relSecIdx == 0)
130ecc93ed2SFangrui Song return {};
131ecc93ed2SFangrui Song RelsOrRelas<ELFT> ret;
132b5a0f0f3SFangrui Song typename ELFT::Shdr shdr =
133b5a0f0f3SFangrui Song cast<ELFFileBase>(file)->getELFShdrs<ELFT>()[relSecIdx];
134ecc93ed2SFangrui Song if (shdr.sh_type == SHT_REL) {
135ecc93ed2SFangrui Song ret.rels = makeArrayRef(reinterpret_cast<const typename ELFT::Rel *>(
136b5a0f0f3SFangrui Song file->mb.getBufferStart() + shdr.sh_offset),
137ecc93ed2SFangrui Song shdr.sh_size / sizeof(typename ELFT::Rel));
138ecc93ed2SFangrui Song } else {
139ecc93ed2SFangrui Song assert(shdr.sh_type == SHT_RELA);
140ecc93ed2SFangrui Song ret.relas = makeArrayRef(reinterpret_cast<const typename ELFT::Rela *>(
141b5a0f0f3SFangrui Song file->mb.getBufferStart() + shdr.sh_offset),
142ecc93ed2SFangrui Song shdr.sh_size / sizeof(typename ELFT::Rela));
143ecc93ed2SFangrui Song }
144ecc93ed2SFangrui Song return ret;
145ecc93ed2SFangrui Song }
146ecc93ed2SFangrui Song
getOffset(uint64_t offset) const1473837f427SRui Ueyama uint64_t SectionBase::getOffset(uint64_t offset) const {
14816853bb0SRafael Espindola switch (kind()) {
1495616adf6SRafael Espindola case Output: {
1503837f427SRui Ueyama auto *os = cast<OutputSection>(this);
1515616adf6SRafael Espindola // For output sections we treat offset -1 as the end of the section.
1523837f427SRui Ueyama return offset == uint64_t(-1) ? os->size : offset;
1535616adf6SRafael Espindola }
154db9bf4dbSRafael Espindola case Regular:
155aded4093SRafael Espindola case Synthetic:
15685e50c10SFangrui Song return cast<InputSection>(this)->outSecOff + offset;
15746453119SFangrui Song case EHFrame: {
15846453119SFangrui Song // Two code paths may reach here. First, clang_rt.crtbegin.o and GCC
15946453119SFangrui Song // crtbeginT.o may reference the start of an empty .eh_frame to identify the
16046453119SFangrui Song // start of the output .eh_frame. Just return offset.
16146453119SFangrui Song //
16246453119SFangrui Song // Second, InputSection::copyRelocations on .eh_frame. Some pieces may be
16346453119SFangrui Song // discarded due to GC/ICF. We should compute the output section offset.
16446453119SFangrui Song const EhInputSection *es = cast<EhInputSection>(this);
16546453119SFangrui Song if (!es->rawData.empty())
16646453119SFangrui Song if (InputSection *isec = es->getParent())
16746453119SFangrui Song return isec->outSecOff + es->getParentOffset(offset);
16848e251b1SFangrui Song return offset;
16946453119SFangrui Song }
170db9bf4dbSRafael Espindola case Merge:
1713837f427SRui Ueyama const MergeInputSection *ms = cast<MergeInputSection>(this);
1723837f427SRui Ueyama if (InputSection *isec = ms->getParent())
17385e50c10SFangrui Song return isec->outSecOff + ms->getParentOffset(offset);
1743837f427SRui Ueyama return ms->getParentOffset(offset);
175db9bf4dbSRafael Espindola }
176777f9630SGeorge Rimar llvm_unreachable("invalid section kind");
177db9bf4dbSRafael Espindola }
178db9bf4dbSRafael Espindola
getVA(uint64_t offset) const1793837f427SRui Ueyama uint64_t SectionBase::getVA(uint64_t offset) const {
1803837f427SRui Ueyama const OutputSection *out = getOutputSection();
1813837f427SRui Ueyama return (out ? out->addr : 0) + getOffset(offset);
1824f058a2cSRafael Espindola }
1834f058a2cSRafael Espindola
getOutputSection()1845616adf6SRafael Espindola OutputSection *SectionBase::getOutputSection() {
1853837f427SRui Ueyama InputSection *sec;
1863837f427SRui Ueyama if (auto *isec = dyn_cast<InputSection>(this))
1873837f427SRui Ueyama sec = isec;
1883837f427SRui Ueyama else if (auto *ms = dyn_cast<MergeInputSection>(this))
1893837f427SRui Ueyama sec = ms->getParent();
1903837f427SRui Ueyama else if (auto *eh = dyn_cast<EhInputSection>(this))
1913837f427SRui Ueyama sec = eh->getParent();
192db5e56f7SRafael Espindola else
1935616adf6SRafael Espindola return cast<OutputSection>(this);
1943837f427SRui Ueyama return sec ? sec->getParent() : nullptr;
1959e9754b5SRafael Espindola }
1969e9754b5SRafael Espindola
19747cfe8f3SFangrui Song // When a section is compressed, `rawData` consists with a header followed
198e28c1464SRui Ueyama // by zlib-compressed data. This function parses a header to initialize
19947cfe8f3SFangrui Song // `uncompressedSize` member and remove the header from `rawData`.
parseCompressedHeader()200c6ebc651SSimon Atanasyan template <typename ELFT> void InputSectionBase::parseCompressedHeader() {
2013837f427SRui Ueyama flags &= ~(uint64_t)SHF_COMPRESSED;
2023cd48fb1SRui Ueyama
203c6ebc651SSimon Atanasyan // New-style header
204c6ebc651SSimon Atanasyan if (rawData.size() < sizeof(typename ELFT::Chdr)) {
205e28c1464SRui Ueyama error(toString(this) + ": corrupted compressed section");
206e28c1464SRui Ueyama return;
2073cd48fb1SRui Ueyama }
208e28c1464SRui Ueyama
209c6ebc651SSimon Atanasyan auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(rawData.data());
210dd74d311SFangrui Song if (hdr->ch_type == ELFCOMPRESS_ZLIB) {
211dd74d311SFangrui Song if (!compression::zlib::isAvailable())
212dd74d311SFangrui Song error(toString(this) + " is compressed with ELFCOMPRESS_ZLIB, but lld is "
213dd74d311SFangrui Song "not built with zlib support");
214dd74d311SFangrui Song } else {
215dd74d311SFangrui Song error(toString(this) + ": unsupported compression type (" +
216dd74d311SFangrui Song Twine(hdr->ch_type) + ")");
217e28c1464SRui Ueyama return;
218e28c1464SRui Ueyama }
219e28c1464SRui Ueyama
2203837f427SRui Ueyama uncompressedSize = hdr->ch_size;
2213837f427SRui Ueyama alignment = std::max<uint32_t>(hdr->ch_addralign, 1);
2223837f427SRui Ueyama rawData = rawData.slice(sizeof(*hdr));
223602fbee9SGeorge Rimar }
224602fbee9SGeorge Rimar
getLinkOrderDep() const225b47c6e5cSRafael Espindola InputSection *InputSectionBase::getLinkOrderDep() const {
2263837f427SRui Ueyama assert(flags & SHF_LINK_ORDER);
227b216c80cSFangrui Song if (!link)
228b216c80cSFangrui Song return nullptr;
2293837f427SRui Ueyama return cast<InputSection>(file->getSections()[link]);
2300a259f3bSPeter Smith }
2310a259f3bSPeter Smith
2324fd84c18SSterling Augustine // Find a function symbol that encloses a given location.
getEnclosingFunction(uint64_t offset)2333837f427SRui Ueyama Defined *InputSectionBase::getEnclosingFunction(uint64_t offset) {
2343837f427SRui Ueyama for (Symbol *b : file->getSymbols())
2353837f427SRui Ueyama if (Defined *d = dyn_cast<Defined>(b))
2363837f427SRui Ueyama if (d->section == this && d->type == STT_FUNC && d->value <= offset &&
2373837f427SRui Ueyama offset < d->value + d->size)
2383837f427SRui Ueyama return d;
2394fd84c18SSterling Augustine return nullptr;
2404fd84c18SSterling Augustine }
2414fd84c18SSterling Augustine
2422b1e3241SFangrui Song // Returns an object file location string. Used to construct an error message.
getLocation(uint64_t offset)2433837f427SRui Ueyama std::string InputSectionBase::getLocation(uint64_t offset) {
2442b1e3241SFangrui Song std::string secAndOffset =
2452b1e3241SFangrui Song (name + "+0x" + Twine::utohexstr(offset) + ")").str();
2463ca494b2SSean Fertile
24729685479SEugene Leviant // We don't have file for synthetic sections.
2485f404a74SFangrui Song if (file == nullptr)
2492b1e3241SFangrui Song return (config->outputFile + ":(" + secAndOffset).str();
25029685479SEugene Leviant
2515f404a74SFangrui Song std::string filename = toString(file);
252469144ffSFangrui Song if (Defined *d = getEnclosingFunction(offset))
2535f404a74SFangrui Song return filename + ":(function " + toString(*d) + ": " + secAndOffset;
254da06bfb7SRui Ueyama
2555f404a74SFangrui Song return filename + ":(" + secAndOffset;
256da06bfb7SRui Ueyama }
257da06bfb7SRui Ueyama
25882f0c42dSGeorge Rimar // This function is intended to be used for constructing an error message.
25982f0c42dSGeorge Rimar // The returned message looks like this:
260b8760203SRui Ueyama //
261b8760203SRui Ueyama // foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
262b8760203SRui Ueyama //
263b8760203SRui Ueyama // Returns an empty string if there's no way to get line info.
getSrcMsg(const Symbol & sym,uint64_t offset)2643837f427SRui Ueyama std::string InputSectionBase::getSrcMsg(const Symbol &sym, uint64_t offset) {
2653837f427SRui Ueyama return file->getSrcMsg(sym, *this, offset);
266b8760203SRui Ueyama }
267b8760203SRui Ueyama
268b8760203SRui Ueyama // Returns a filename string along with an optional section name. This
269b8760203SRui Ueyama // function is intended to be used for constructing an error
270b8760203SRui Ueyama // message. The returned message looks like this:
271b8760203SRui Ueyama //
272b8760203SRui Ueyama // path/to/foo.o:(function bar)
273b8760203SRui Ueyama //
274b8760203SRui Ueyama // or
275b8760203SRui Ueyama //
276b8760203SRui Ueyama // path/to/foo.o:(function bar) in archive path/to/bar.a
getObjMsg(uint64_t off)2773837f427SRui Ueyama std::string InputSectionBase::getObjMsg(uint64_t off) {
278adcd0268SBenjamin Kramer std::string filename = std::string(file->getName());
279b8760203SRui Ueyama
2803837f427SRui Ueyama std::string archive;
2813837f427SRui Ueyama if (!file->archiveName.empty())
2821ff1d50dSFangrui Song archive = (" in archive " + file->archiveName).str();
283b8760203SRui Ueyama
284a815424cSFangrui Song // Find a symbol that encloses a given location. getObjMsg may be called
285a815424cSFangrui Song // before ObjFile::initializeLocalSymbols where local symbols are initialized.
2863837f427SRui Ueyama for (Symbol *b : file->getSymbols())
287a815424cSFangrui Song if (auto *d = dyn_cast_or_null<Defined>(b))
2883837f427SRui Ueyama if (d->section == this && d->value <= off && off < d->value + d->size)
2893837f427SRui Ueyama return filename + ":(" + toString(*d) + ")" + archive;
290b8760203SRui Ueyama
291b8760203SRui Ueyama // If there's no symbol, print out the offset in the section.
2923837f427SRui Ueyama return (filename + ":(" + name + "+0x" + utohexstr(off) + ")" + archive)
293b8760203SRui Ueyama .str();
294b8760203SRui Ueyama }
295b8760203SRui Ueyama
2963837f427SRui Ueyama InputSection InputSection::discarded(nullptr, 0, 0, 0, ArrayRef<uint8_t>(), "");
297774ea7d0SRafael Espindola
InputSection(InputFile * f,uint64_t flags,uint32_t type,uint32_t alignment,ArrayRef<uint8_t> data,StringRef name,Kind k)2983837f427SRui Ueyama InputSection::InputSection(InputFile *f, uint64_t flags, uint32_t type,
2993837f427SRui Ueyama uint32_t alignment, ArrayRef<uint8_t> data,
3003837f427SRui Ueyama StringRef name, Kind k)
3013837f427SRui Ueyama : InputSectionBase(f, flags, type,
3023837f427SRui Ueyama /*Entsize*/ 0, /*Link*/ 0, /*Info*/ 0, alignment, data,
3033837f427SRui Ueyama name, k) {}
3040e090522SRafael Espindola
3050e090522SRafael Espindola template <class ELFT>
InputSection(ObjFile<ELFT> & f,const typename ELFT::Shdr & header,StringRef name)3063837f427SRui Ueyama InputSection::InputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
3073837f427SRui Ueyama StringRef name)
3083837f427SRui Ueyama : InputSectionBase(f, header, name, InputSectionBase::Regular) {}
309c159c967SRafael Espindola
310f08b38cbSRui Ueyama // Copy SHT_GROUP section contents. Used only for the -r option.
copyShtGroup(uint8_t * buf)3113837f427SRui Ueyama template <class ELFT> void InputSection::copyShtGroup(uint8_t *buf) {
312f08b38cbSRui Ueyama // ELFT::Word is the 32-bit integral type in the target endianness.
31368b9f45fSRui Ueyama using u32 = typename ELFT::Word;
3143837f427SRui Ueyama ArrayRef<u32> from = getDataAs<u32>();
3153837f427SRui Ueyama auto *to = reinterpret_cast<u32 *>(buf);
3163b189d16SGeorge Rimar
317f08b38cbSRui Ueyama // The first entry is not a section number but a flag.
3183837f427SRui Ueyama *to++ = from[0];
3193b189d16SGeorge Rimar
32086ab98b0SFangrui Song // Adjust section numbers because section numbers in an input object files are
32186ab98b0SFangrui Song // different in the output. We also need to handle combined or discarded
32286ab98b0SFangrui Song // members.
3233837f427SRui Ueyama ArrayRef<InputSectionBase *> sections = file->getSections();
3245a2020d0SFangrui Song DenseSet<uint32_t> seen;
32586ab98b0SFangrui Song for (uint32_t idx : from.slice(1)) {
32686ab98b0SFangrui Song OutputSection *osec = sections[idx]->getOutputSection();
32786ab98b0SFangrui Song if (osec && seen.insert(osec->sectionIndex).second)
32886ab98b0SFangrui Song *to++ = osec->sectionIndex;
32986ab98b0SFangrui Song }
3303b189d16SGeorge Rimar }
3313b189d16SGeorge Rimar
getRelocatedSection() const33211dc7fcaSPeter Collingbourne InputSectionBase *InputSection::getRelocatedSection() const {
3333837f427SRui Ueyama if (!file || (type != SHT_RELA && type != SHT_REL))
334f065390fSRafael Espindola return nullptr;
3353837f427SRui Ueyama ArrayRef<InputSectionBase *> sections = file->getSections();
3363837f427SRui Ueyama return sections[info];
33758941ee1SGeorge Rimar }
33858941ee1SGeorge Rimar
33982bd8be6SGeorge Rimar // This is used for -r and --emit-relocs. We can't use memcpy to copy
34082bd8be6SGeorge Rimar // relocations because we need to update symbol table offset and section index
34182bd8be6SGeorge Rimar // for each relocation. So we copy relocations one by one.
342774ea7d0SRafael Espindola template <class ELFT, class RelTy>
copyRelocations(uint8_t * buf,ArrayRef<RelTy> rels)3433837f427SRui Ueyama void InputSection::copyRelocations(uint8_t *buf, ArrayRef<RelTy> rels) {
344745420d3SFangrui Song const TargetInfo &target = *elf::target;
3453837f427SRui Ueyama InputSectionBase *sec = getRelocatedSection();
346ae1ba619SFangrui Song (void)sec->data(); // uncompress if needed
347c04a91aaSRui Ueyama
3483837f427SRui Ueyama for (const RelTy &rel : rels) {
3493837f427SRui Ueyama RelType type = rel.getType(config->isMips64EL);
3503837f427SRui Ueyama const ObjFile<ELFT> *file = getFile<ELFT>();
3513837f427SRui Ueyama Symbol &sym = file->getRelocTargetSym(rel);
35258941ee1SGeorge Rimar
3533837f427SRui Ueyama auto *p = reinterpret_cast<typename ELFT::Rela *>(buf);
3543837f427SRui Ueyama buf += sizeof(RelTy);
35558941ee1SGeorge Rimar
35643604663SSimon Atanasyan if (RelTy::IsRela)
3573837f427SRui Ueyama p->r_addend = getAddend<ELFT>(rel);
35882bd8be6SGeorge Rimar
359d50c8598SRafael Espindola // Output section VA is zero for -r, so r_offset is an offset within the
3607ae3d335SKazuaki Ishizaki // section, but for --emit-relocs it is a virtual address.
3613837f427SRui Ueyama p->r_offset = sec->getVA(rel.r_offset);
3623837f427SRui Ueyama p->setSymbolAndType(in.symTab->getSymbolIndex(&sym), type,
3633837f427SRui Ueyama config->isMips64EL);
364d50c8598SRafael Espindola
3653837f427SRui Ueyama if (sym.type == STT_SECTION) {
36608d6a3f1SRafael Espindola // We combine multiple section symbols into only one per
36708d6a3f1SRafael Espindola // section. This means we have to update the addend. That is
36808d6a3f1SRafael Espindola // trivial for Elf_Rela, but for Elf_Rel we have to write to the
36908d6a3f1SRafael Espindola // section data. We do that by adding to the Relocation vector.
37060b02509SRafael Espindola
37160b02509SRafael Espindola // .eh_frame is horribly special and can reference discarded sections. To
37260b02509SRafael Espindola // avoid having to parse and recreate .eh_frame, we just replace any
37360b02509SRafael Espindola // relocation in it pointing to discarded sections with R_*_NONE, which
374ba51fd56SFangrui Song // hopefully creates a frame that is ignored at runtime. Also, don't warn
375ba51fd56SFangrui Song // on .gcc_except_table and debug sections.
376ba51fd56SFangrui Song //
377315f8a55SFangrui Song // See the comment in maybeReportUndefined for PPC32 .got2 and PPC64 .toc
3783837f427SRui Ueyama auto *d = dyn_cast<Defined>(&sym);
3793837f427SRui Ueyama if (!d) {
3806c732461SFangrui Song if (!isDebugSection(*sec) && sec->name != ".eh_frame" &&
381315f8a55SFangrui Song sec->name != ".gcc_except_table" && sec->name != ".got2" &&
382315f8a55SFangrui Song sec->name != ".toc") {
3833837f427SRui Ueyama uint32_t secIdx = cast<Undefined>(sym).discardedSecIdx;
384b5a0f0f3SFangrui Song Elf_Shdr_Impl<ELFT> sec = file->template getELFShdrs<ELFT>()[secIdx];
385ba51fd56SFangrui Song warn("relocation refers to a discarded section: " +
3864845531fSGeorgii Rymar CHECK(file->getObj().getSectionName(sec), file) +
3873837f427SRui Ueyama "\n>>> referenced by " + getObjMsg(p->r_offset));
388ba51fd56SFangrui Song }
3893837f427SRui Ueyama p->setSymbolAndType(0, 0, false);
390568ee2c0SRafael Espindola continue;
391568ee2c0SRafael Espindola }
392e1b6b5beSFangrui Song SectionBase *section = d->section;
3933837f427SRui Ueyama if (!section->isLive()) {
3943837f427SRui Ueyama p->setSymbolAndType(0, 0, false);
39560b02509SRafael Espindola continue;
39660b02509SRafael Espindola }
39760b02509SRafael Espindola
3983837f427SRui Ueyama int64_t addend = getAddend<ELFT>(rel);
399ae1ba619SFangrui Song const uint8_t *bufLoc = sec->rawData.begin() + rel.r_offset;
40005600506SSimon Atanasyan if (!RelTy::IsRela)
401745420d3SFangrui Song addend = target.getImplicitAddend(bufLoc, type);
40205600506SSimon Atanasyan
403da1973a2SFangrui Song if (config->emachine == EM_MIPS &&
404745420d3SFangrui Song target.getRelExpr(type, sym, bufLoc) == R_MIPS_GOTREL) {
40505600506SSimon Atanasyan // Some MIPS relocations depend on "gp" value. By default,
40605600506SSimon Atanasyan // this value has 0x7ff0 offset from a .got section. But
4075976a3f5SNico Weber // relocatable files produced by a compiler or a linker
40805600506SSimon Atanasyan // might redefine this default value and we must use it
40905600506SSimon Atanasyan // for a calculation of the relocation result. When we
41005600506SSimon Atanasyan // generate EXE or DSO it's trivial. Generating a relocatable
41105600506SSimon Atanasyan // output is more difficult case because the linker does
41205600506SSimon Atanasyan // not calculate relocations in this mode and loses
41305600506SSimon Atanasyan // individual "gp" values used by each input object file.
41405600506SSimon Atanasyan // As a workaround we add the "gp" value to the relocation
41505600506SSimon Atanasyan // addend and save it back to the file.
4163837f427SRui Ueyama addend += sec->getFile<ELFT>()->mipsGp0;
41708d6a3f1SRafael Espindola }
41808d6a3f1SRafael Espindola
41905600506SSimon Atanasyan if (RelTy::IsRela)
4203837f427SRui Ueyama p->r_addend = sym.getVA(addend) - section->getOutputSection()->addr;
421745420d3SFangrui Song else if (config->relocatable && type != target.noneRel)
4223837f427SRui Ueyama sec->relocations.push_back({R_ABS, type, rel.r_offset, addend, &sym});
423e11b709bSFangrui Song } else if (config->emachine == EM_PPC && type == R_PPC_PLTREL24 &&
424bf45624bSFangrui Song p->r_addend >= 0x8000 && sec->file->ppc32Got2) {
425e11b709bSFangrui Song // Similar to R_MIPS_GPREL{16,32}. If the addend of R_PPC_PLTREL24
426e11b709bSFangrui Song // indicates that r30 is relative to the input section .got2
427e11b709bSFangrui Song // (r_addend>=0x8000), after linking, r30 should be relative to the output
428e11b709bSFangrui Song // section .got2 . To compensate for the shift, adjust r_addend by
429bf45624bSFangrui Song // ppc32Got->outSecOff.
430bf45624bSFangrui Song p->r_addend += sec->file->ppc32Got2->outSecOff;
43105600506SSimon Atanasyan }
43258941ee1SGeorge Rimar }
43358941ee1SGeorge Rimar }
43458941ee1SGeorge Rimar
4359873c4b5SPeter Smith // The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
4369873c4b5SPeter Smith // references specially. The general rule is that the value of the symbol in
4379873c4b5SPeter Smith // this context is the address of the place P. A further special case is that
4389873c4b5SPeter Smith // branch relocations to an undefined weak reference resolve to the next
4399873c4b5SPeter Smith // instruction.
getARMUndefinedRelativeWeakVA(RelType type,uint32_t a,uint32_t p)4403837f427SRui Ueyama static uint32_t getARMUndefinedRelativeWeakVA(RelType type, uint32_t a,
4413837f427SRui Ueyama uint32_t p) {
4423837f427SRui Ueyama switch (type) {
4439873c4b5SPeter Smith // Unresolved branch relocations to weak references resolve to next
4449873c4b5SPeter Smith // instruction, this will be either 2 or 4 bytes on from P.
445d56b171eSPetr Hosek case R_ARM_THM_JUMP8:
4468339bbd7SPeter Smith case R_ARM_THM_JUMP11:
4473837f427SRui Ueyama return p + 2 + a;
4488339bbd7SPeter Smith case R_ARM_CALL:
4498339bbd7SPeter Smith case R_ARM_JUMP24:
4508339bbd7SPeter Smith case R_ARM_PC24:
4518339bbd7SPeter Smith case R_ARM_PLT32:
4528339bbd7SPeter Smith case R_ARM_PREL31:
4538339bbd7SPeter Smith case R_ARM_THM_JUMP19:
4548339bbd7SPeter Smith case R_ARM_THM_JUMP24:
4553837f427SRui Ueyama return p + 4 + a;
4568339bbd7SPeter Smith case R_ARM_THM_CALL:
4578339bbd7SPeter Smith // We don't want an interworking BLX to ARM
4583837f427SRui Ueyama return p + 5 + a;
4599873c4b5SPeter Smith // Unresolved non branch pc-relative relocations
4609873c4b5SPeter Smith // R_ARM_TARGET2 which can be resolved relatively is not present as it never
4619873c4b5SPeter Smith // targets a weak-reference.
4629873c4b5SPeter Smith case R_ARM_MOVW_PREL_NC:
4639873c4b5SPeter Smith case R_ARM_MOVT_PREL:
4649873c4b5SPeter Smith case R_ARM_REL32:
4656b035b60SPeter Smith case R_ARM_THM_ALU_PREL_11_0:
4669873c4b5SPeter Smith case R_ARM_THM_MOVW_PREL_NC:
4679873c4b5SPeter Smith case R_ARM_THM_MOVT_PREL:
4686b035b60SPeter Smith case R_ARM_THM_PC12:
4693837f427SRui Ueyama return p + a;
4706b035b60SPeter Smith // p + a is unrepresentable as negative immediates can't be encoded.
4716b035b60SPeter Smith case R_ARM_THM_PC8:
4726b035b60SPeter Smith return p;
4738339bbd7SPeter Smith }
4749873c4b5SPeter Smith llvm_unreachable("ARM pc-relative relocation expected\n");
4758339bbd7SPeter Smith }
4768339bbd7SPeter Smith
4779873c4b5SPeter Smith // The comment above getARMUndefinedRelativeWeakVA applies to this function.
getAArch64UndefinedRelativeWeakVA(uint64_t type,uint64_t p)4780995bbdbSFangrui Song static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t type, uint64_t p) {
4793837f427SRui Ueyama switch (type) {
4809873c4b5SPeter Smith // Unresolved branch relocations to weak references resolve to next
4819873c4b5SPeter Smith // instruction, this is 4 bytes on from P.
4828339bbd7SPeter Smith case R_AARCH64_CALL26:
4838339bbd7SPeter Smith case R_AARCH64_CONDBR19:
4848339bbd7SPeter Smith case R_AARCH64_JUMP26:
4858339bbd7SPeter Smith case R_AARCH64_TSTBR14:
4860995bbdbSFangrui Song return p + 4;
4879873c4b5SPeter Smith // Unresolved non branch pc-relative relocations
4889873c4b5SPeter Smith case R_AARCH64_PREL16:
4899873c4b5SPeter Smith case R_AARCH64_PREL32:
4909873c4b5SPeter Smith case R_AARCH64_PREL64:
4919873c4b5SPeter Smith case R_AARCH64_ADR_PREL_LO21:
492f681a8faSDavide Italiano case R_AARCH64_LD_PREL_LO19:
493723b5a17SLeonard Chan case R_AARCH64_PLT32:
4940995bbdbSFangrui Song return p;
4958339bbd7SPeter Smith }
4969873c4b5SPeter Smith llvm_unreachable("AArch64 pc-relative relocation expected\n");
4978339bbd7SPeter Smith }
4988339bbd7SPeter Smith
getRISCVUndefinedRelativeWeakVA(uint64_t type,uint64_t p)499c03b6305SFangrui Song static uint64_t getRISCVUndefinedRelativeWeakVA(uint64_t type, uint64_t p) {
500c03b6305SFangrui Song switch (type) {
501c03b6305SFangrui Song case R_RISCV_BRANCH:
502c03b6305SFangrui Song case R_RISCV_JAL:
503c03b6305SFangrui Song case R_RISCV_CALL:
504c03b6305SFangrui Song case R_RISCV_CALL_PLT:
505c03b6305SFangrui Song case R_RISCV_RVC_BRANCH:
506c03b6305SFangrui Song case R_RISCV_RVC_JUMP:
507c03b6305SFangrui Song return p;
508c03b6305SFangrui Song default:
509c03b6305SFangrui Song return 0;
510c03b6305SFangrui Song }
511c03b6305SFangrui Song }
512c03b6305SFangrui Song
513d54f368eSPeter Smith // ARM SBREL relocations are of the form S + A - B where B is the static base
514d54f368eSPeter Smith // The ARM ABI defines base to be "addressing origin of the output segment
515d54f368eSPeter Smith // defining the symbol S". We defined the "addressing origin"/static base to be
51648882249SRui Ueyama // the base of the PT_LOAD segment containing the Sym.
517d54f368eSPeter Smith // The procedure call standard only defines a Read Write Position Independent
518d54f368eSPeter Smith // RWPI variant so in practice we should expect the static base to be the base
519d54f368eSPeter Smith // of the RW segment.
getARMStaticBase(const Symbol & sym)5203837f427SRui Ueyama static uint64_t getARMStaticBase(const Symbol &sym) {
5213837f427SRui Ueyama OutputSection *os = sym.getOutputSection();
5223837f427SRui Ueyama if (!os || !os->ptLoad || !os->ptLoad->firstSec)
5233837f427SRui Ueyama fatal("SBREL relocation to " + sym.getName() + " without static base");
5243837f427SRui Ueyama return os->ptLoad->firstSec->addr;
525d54f368eSPeter Smith }
526d54f368eSPeter Smith
5275cd9c6bcSRui Ueyama // For R_RISCV_PC_INDIRECT (R_RISCV_PCREL_LO12_{I,S}), the symbol actually
5285cd9c6bcSRui Ueyama // points the corresponding R_RISCV_PCREL_HI20 relocation, and the target VA
5295cd9c6bcSRui Ueyama // is calculated using PCREL_HI20's symbol.
5305cd9c6bcSRui Ueyama //
5315cd9c6bcSRui Ueyama // This function returns the R_RISCV_PCREL_HI20 relocation from
5325cd9c6bcSRui Ueyama // R_RISCV_PCREL_LO12's symbol and addend.
getRISCVPCRelHi20(const Symbol * sym,uint64_t addend)5333837f427SRui Ueyama static Relocation *getRISCVPCRelHi20(const Symbol *sym, uint64_t addend) {
5343837f427SRui Ueyama const Defined *d = cast<Defined>(sym);
5353837f427SRui Ueyama if (!d->section) {
53616ca490fSFangrui Song errorOrWarn("R_RISCV_PCREL_LO12 relocation points to an absolute symbol: " +
5373837f427SRui Ueyama sym->getName());
5384e225deaSFangrui Song return nullptr;
5394e225deaSFangrui Song }
5403837f427SRui Ueyama InputSection *isec = cast<InputSection>(d->section);
5415cd9c6bcSRui Ueyama
5423837f427SRui Ueyama if (addend != 0)
5438b2f3323SFangrui Song warn("non-zero addend in R_RISCV_PCREL_LO12 relocation to " +
5443837f427SRui Ueyama isec->getObjMsg(d->value) + " is ignored");
5455cd9c6bcSRui Ueyama
5465cd9c6bcSRui Ueyama // Relocations are sorted by offset, so we can use std::equal_range to do
5475cd9c6bcSRui Ueyama // binary search.
5483837f427SRui Ueyama Relocation r;
5493837f427SRui Ueyama r.offset = d->value;
5503837f427SRui Ueyama auto range =
5513837f427SRui Ueyama std::equal_range(isec->relocations.begin(), isec->relocations.end(), r,
5523837f427SRui Ueyama [](const Relocation &lhs, const Relocation &rhs) {
5533837f427SRui Ueyama return lhs.offset < rhs.offset;
554980fb790SRui Ueyama });
555980fb790SRui Ueyama
5563837f427SRui Ueyama for (auto it = range.first; it != range.second; ++it)
5573837f427SRui Ueyama if (it->type == R_RISCV_PCREL_HI20 || it->type == R_RISCV_GOT_HI20 ||
5583837f427SRui Ueyama it->type == R_RISCV_TLS_GD_HI20 || it->type == R_RISCV_TLS_GOT_HI20)
5593837f427SRui Ueyama return &*it;
5605cd9c6bcSRui Ueyama
56116ca490fSFangrui Song errorOrWarn("R_RISCV_PCREL_LO12 relocation points to " +
56216ca490fSFangrui Song isec->getObjMsg(d->value) +
5635cd9c6bcSRui Ueyama " without an associated R_RISCV_PCREL_HI20 relocation");
5645cd9c6bcSRui Ueyama return nullptr;
5655cd9c6bcSRui Ueyama }
5665cd9c6bcSRui Ueyama
567e7cb0225SRyan Prichard // A TLS symbol's virtual address is relative to the TLS segment. Add a
568e7cb0225SRyan Prichard // target-specific adjustment to produce a thread-pointer-relative offset.
getTlsTpOffset(const Symbol & s)5693837f427SRui Ueyama static int64_t getTlsTpOffset(const Symbol &s) {
5700526c0cdSFangrui Song // On targets that support TLSDESC, _TLS_MODULE_BASE_@tpoff = 0.
5713837f427SRui Ueyama if (&s == ElfSym::tlsModuleBase)
5720526c0cdSFangrui Song return 0;
5730526c0cdSFangrui Song
57401c7f4b6SFangrui Song // There are 2 TLS layouts. Among targets we support, x86 uses TLS Variant 2
57501c7f4b6SFangrui Song // while most others use Variant 1. At run time TP will be aligned to p_align.
57601c7f4b6SFangrui Song
57701c7f4b6SFangrui Song // Variant 1. TP will be followed by an optional gap (which is the size of 2
57801c7f4b6SFangrui Song // pointers on ARM/AArch64, 0 on other targets), followed by alignment
57901c7f4b6SFangrui Song // padding, then the static TLS blocks. The alignment padding is added so that
58001c7f4b6SFangrui Song // (TP + gap + padding) is congruent to p_vaddr modulo p_align.
58101c7f4b6SFangrui Song //
58201c7f4b6SFangrui Song // Variant 2. Static TLS blocks, followed by alignment padding are placed
58301c7f4b6SFangrui Song // before TP. The alignment padding is added so that (TP - padding -
58401c7f4b6SFangrui Song // p_memsz) is congruent to p_vaddr modulo p_align.
585bd8cfe65SFangrui Song PhdrEntry *tls = Out::tlsPhdr;
5863837f427SRui Ueyama switch (config->emachine) {
58701c7f4b6SFangrui Song // Variant 1.
588e7cb0225SRyan Prichard case EM_ARM:
589e7cb0225SRyan Prichard case EM_AARCH64:
59001c7f4b6SFangrui Song return s.getVA(0) + config->wordsize * 2 +
59101c7f4b6SFangrui Song ((tls->p_vaddr - config->wordsize * 2) & (tls->p_align - 1));
5925adbfddaSSimon Atanasyan case EM_MIPS:
5937ccfdad7SFangrui Song case EM_PPC:
594e7cb0225SRyan Prichard case EM_PPC64:
59501c7f4b6SFangrui Song // Adjusted Variant 1. TP is placed with a displacement of 0x7000, which is
59601c7f4b6SFangrui Song // to allow a signed 16-bit offset to reach 0x1000 of TCB/thread-library
59701c7f4b6SFangrui Song // data and 0xf000 of the program's TLS segment.
59801c7f4b6SFangrui Song return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1)) - 0x7000;
599ddc57afaSFangrui Song case EM_RISCV:
60001c7f4b6SFangrui Song return s.getVA(0) + (tls->p_vaddr & (tls->p_align - 1));
60101c7f4b6SFangrui Song
60201c7f4b6SFangrui Song // Variant 2.
60381ffe897SSid Manning case EM_HEXAGON:
604aff950e9SLemonBoy case EM_SPARCV9:
60501c7f4b6SFangrui Song case EM_386:
60601c7f4b6SFangrui Song case EM_X86_64:
60701c7f4b6SFangrui Song return s.getVA(0) - tls->p_memsz -
60801c7f4b6SFangrui Song ((-tls->p_vaddr - tls->p_memsz) & (tls->p_align - 1));
609e7cb0225SRyan Prichard default:
610e7cb0225SRyan Prichard llvm_unreachable("unhandled Config->EMachine");
611e7cb0225SRyan Prichard }
612e7cb0225SRyan Prichard }
613e7cb0225SRyan Prichard
getRelocTargetVA(const InputFile * file,RelType type,int64_t a,uint64_t p,const Symbol & sym,RelExpr expr)61494317878SSriraman Tallam uint64_t InputSectionBase::getRelocTargetVA(const InputFile *file, RelType type,
61594317878SSriraman Tallam int64_t a, uint64_t p,
61694317878SSriraman Tallam const Symbol &sym, RelExpr expr) {
6173837f427SRui Ueyama switch (expr) {
618ff524bf7SRui Ueyama case R_ABS:
619d986e41fSFangrui Song case R_DTPREL:
62075c348a0SZaara Syeda case R_RELAX_TLS_LD_TO_LE_ABS:
621ff524bf7SRui Ueyama case R_RELAX_GOT_PC_NOPIC:
6224ce0a519SFangrui Song case R_RISCV_ADD:
6233837f427SRui Ueyama return sym.getVA(a);
624cfb60933SAlexander Richardson case R_ADDEND:
6253837f427SRui Ueyama return a;
6266611d58fSFangrui Song case R_RELAX_HINT:
6276611d58fSFangrui Song return 0;
628d54f368eSPeter Smith case R_ARM_SBREL:
6293837f427SRui Ueyama return sym.getVA(a) - getARMStaticBase(sym);
63022ef956aSRafael Espindola case R_GOT:
631ff524bf7SRui Ueyama case R_RELAX_TLS_GD_TO_IE_ABS:
6323837f427SRui Ueyama return sym.getGotVA() + a;
6333f5d634cSRafael Espindola case R_GOTONLY_PC:
6343837f427SRui Ueyama return in.got->getVA() + a - p;
635210949a2SFangrui Song case R_GOTPLTONLY_PC:
6363837f427SRui Ueyama return in.gotPlt->getVA() + a - p;
637ff524bf7SRui Ueyama case R_GOTREL:
638912251e8SFangrui Song case R_PPC64_RELAX_TOC:
6393837f427SRui Ueyama return sym.getVA(a) - in.got->getVA();
640210949a2SFangrui Song case R_GOTPLTREL:
6413837f427SRui Ueyama return sym.getVA(a) - in.gotPlt->getVA();
642210949a2SFangrui Song case R_GOTPLT:
643e1f3191aSFangrui Song case R_RELAX_TLS_GD_TO_IE_GOTPLT:
6443837f427SRui Ueyama return sym.getGotVA() + a - in.gotPlt->getVA();
645de54f584SZaara Syeda case R_TLSLD_GOT_OFF:
64658cd5db4SRafael Espindola case R_GOT_OFF:
647f60cb34cSSean Fertile case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
6483837f427SRui Ueyama return sym.getGotOffset() + a;
6498ef9babbSGeorge Rimar case R_AARCH64_GOT_PAGE_PC:
6508ef9babbSGeorge Rimar case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
6513837f427SRui Ueyama return getAArch64Page(sym.getGotVA() + a) - getAArch64Page(p);
652988cc0a0SAdhemerval Zanella case R_AARCH64_GOT_PAGE:
653988cc0a0SAdhemerval Zanella return sym.getGotVA() + a - getAArch64Page(in.got->getVA());
654ff524bf7SRui Ueyama case R_GOT_PC:
655ff524bf7SRui Ueyama case R_RELAX_TLS_GD_TO_IE:
6563837f427SRui Ueyama return sym.getGotVA() + a - p;
657ff524bf7SRui Ueyama case R_MIPS_GOTREL:
6583837f427SRui Ueyama return sym.getVA(a) - in.mipsGot->getGp(file);
659ff524bf7SRui Ueyama case R_MIPS_GOT_GP:
6603837f427SRui Ueyama return in.mipsGot->getGp(file) + a;
661ff524bf7SRui Ueyama case R_MIPS_GOT_GP_PC: {
662ff524bf7SRui Ueyama // R_MIPS_LO16 expression has R_MIPS_GOT_GP_PC type iif the target
663ff524bf7SRui Ueyama // is _gp_disp symbol. In that case we should use the following
664ff524bf7SRui Ueyama // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
665ff524bf7SRui Ueyama // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
666509834d7SSimon Atanasyan // microMIPS variants of these relocations use slightly different
667509834d7SSimon Atanasyan // expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi()
6687c5fcb35SKazuaki Ishizaki // to correctly handle less-significant bit of the microMIPS symbol.
6693837f427SRui Ueyama uint64_t v = in.mipsGot->getGp(file) + a - p;
6703837f427SRui Ueyama if (type == R_MIPS_LO16 || type == R_MICROMIPS_LO16)
6713837f427SRui Ueyama v += 4;
6723837f427SRui Ueyama if (type == R_MICROMIPS_LO16 || type == R_MICROMIPS_HI16)
6733837f427SRui Ueyama v -= 1;
6743837f427SRui Ueyama return v;
675ff524bf7SRui Ueyama }
6764e3a15c9SSimon Atanasyan case R_MIPS_GOT_LOCAL_PAGE:
677604aee13SSimon Atanasyan // If relocation against MIPS local symbol requires GOT entry, this entry
678604aee13SSimon Atanasyan // should be initialized by 'page address'. This address is high 16-bits
679abc9a129SRafael Espindola // of sum the symbol's value and the addend.
6803837f427SRui Ueyama return in.mipsGot->getVA() + in.mipsGot->getPageEntryOffset(file, sym, a) -
6813837f427SRui Ueyama in.mipsGot->getGp(file);
6824132511cSSimon Atanasyan case R_MIPS_GOT_OFF:
683bed04bf1SSimon Atanasyan case R_MIPS_GOT_OFF32:
6844132511cSSimon Atanasyan // In case of MIPS if a GOT relocation has non-zero addend this addend
6854132511cSSimon Atanasyan // should be applied to the GOT entry content not to the GOT entry offset.
6864132511cSSimon Atanasyan // That is why we use separate expression type.
6873837f427SRui Ueyama return in.mipsGot->getVA() + in.mipsGot->getSymEntryOffset(file, sym, a) -
6883837f427SRui Ueyama in.mipsGot->getGp(file);
689002e2447SSimon Atanasyan case R_MIPS_TLSGD:
6903837f427SRui Ueyama return in.mipsGot->getVA() + in.mipsGot->getGlobalDynOffset(file, sym) -
6913837f427SRui Ueyama in.mipsGot->getGp(file);
692002e2447SSimon Atanasyan case R_MIPS_TLSLD:
6933837f427SRui Ueyama return in.mipsGot->getVA() + in.mipsGot->getTlsIndexOffset(file) -
6943837f427SRui Ueyama in.mipsGot->getGp(file);
6958329028bSGeorge Rimar case R_AARCH64_PAGE_PC: {
6963837f427SRui Ueyama uint64_t val = sym.isUndefWeak() ? p + a : sym.getVA(a);
6973837f427SRui Ueyama return getAArch64Page(val) - getAArch64Page(p);
698ad51cee8SPeter Smith }
6995cd9c6bcSRui Ueyama case R_RISCV_PC_INDIRECT: {
7003837f427SRui Ueyama if (const Relocation *hiRel = getRISCVPCRelHi20(&sym, a))
7013837f427SRui Ueyama return getRelocTargetVA(file, hiRel->type, hiRel->addend, sym.getVA(),
7023837f427SRui Ueyama *hiRel->sym, hiRel->expr);
7030fc5dcd1SGeorge Rimar return 0;
7045cd9c6bcSRui Ueyama }
7056b035b60SPeter Smith case R_PC:
7066b035b60SPeter Smith case R_ARM_PCA: {
7073837f427SRui Ueyama uint64_t dest;
7086b035b60SPeter Smith if (expr == R_ARM_PCA)
7096b035b60SPeter Smith // Some PC relative ARM (Thumb) relocations align down the place.
7106b035b60SPeter Smith p = p & 0xfffffffc;
71102eab528SFangrui Song if (sym.isUndefined()) {
712c03b6305SFangrui Song // On ARM and AArch64 a branch to an undefined weak resolves to the next
713c03b6305SFangrui Song // instruction, otherwise the place. On RISCV, resolve an undefined weak
714c03b6305SFangrui Song // to the same instruction to cause an infinite loop (making the user
715c03b6305SFangrui Song // aware of the issue) while ensuring no overflow.
71602eab528SFangrui Song // Note: if the symbol is hidden, its binding has been converted to local,
71702eab528SFangrui Song // so we just check isUndefined() here.
7183837f427SRui Ueyama if (config->emachine == EM_ARM)
7193837f427SRui Ueyama dest = getARMUndefinedRelativeWeakVA(type, a, p);
7203837f427SRui Ueyama else if (config->emachine == EM_AARCH64)
7210995bbdbSFangrui Song dest = getAArch64UndefinedRelativeWeakVA(type, p) + a;
7223837f427SRui Ueyama else if (config->emachine == EM_PPC)
7233837f427SRui Ueyama dest = p;
724c03b6305SFangrui Song else if (config->emachine == EM_RISCV)
725c03b6305SFangrui Song dest = getRISCVUndefinedRelativeWeakVA(type, p) + a;
726f846ce25SRafael Espindola else
7273837f427SRui Ueyama dest = sym.getVA(a);
728f846ce25SRafael Espindola } else {
7293837f427SRui Ueyama dest = sym.getVA(a);
730ff524bf7SRui Ueyama }
7313837f427SRui Ueyama return dest - p;
732f846ce25SRafael Espindola }
733ff524bf7SRui Ueyama case R_PLT:
7343837f427SRui Ueyama return sym.getPltVA() + a;
735ff524bf7SRui Ueyama case R_PLT_PC:
7368522d579SFangrui Song case R_PPC64_CALL_PLT:
7373837f427SRui Ueyama return sym.getPltVA() + a - p;
738ca8105b7SFangrui Song case R_PLT_GOTPLT:
739ca8105b7SFangrui Song return sym.getPltVA() + a - in.gotPlt->getVA();
74082442adfSFangrui Song case R_PPC32_PLTREL:
74182442adfSFangrui Song // R_PPC_PLTREL24 uses the addend (usually 0 or 0x8000) to indicate r30
74282442adfSFangrui Song // stores _GLOBAL_OFFSET_TABLE_ or .got2+0x8000. The addend is ignored for
7435976a3f5SNico Weber // target VA computation.
7443837f427SRui Ueyama return sym.getPltVA() - p;
7458522d579SFangrui Song case R_PPC64_CALL: {
7463837f427SRui Ueyama uint64_t symVA = sym.getVA(a);
74722ef956aSRafael Espindola // If we have an undefined weak symbol, we might get here with a symbol
74822ef956aSRafael Espindola // address of zero. That could overflow, but the code must be unreachable,
74922ef956aSRafael Espindola // so don't bother doing anything at all.
7503837f427SRui Ueyama if (!symVA)
75122ef956aSRafael Espindola return 0;
75282dd99e0SZaara Syeda
75382dd99e0SZaara Syeda // PPC64 V2 ABI describes two entry points to a function. The global entry
754e0e586b9SSean Fertile // point is used for calls where the caller and callee (may) have different
755e0e586b9SSean Fertile // TOC base pointers and r2 needs to be modified to hold the TOC base for
756e0e586b9SSean Fertile // the callee. For local calls the caller and callee share the same
757e0e586b9SSean Fertile // TOC base and so the TOC pointer initialization code should be skipped by
758e0e586b9SSean Fertile // branching to the local entry point.
7593837f427SRui Ueyama return symVA - p + getPPC64GlobalEntryToLocalEntryOffset(sym.stOther);
76022ef956aSRafael Espindola }
7618522d579SFangrui Song case R_PPC64_TOCBASE:
7623837f427SRui Ueyama return getPPC64TocBase() + a;
7635c33b91bSGeorge Rimar case R_RELAX_GOT_PC:
764cddb0dbcSNemanja Ivanovic case R_PPC64_RELAX_GOT_PC:
7653837f427SRui Ueyama return sym.getVA(a) - p;
766ff524bf7SRui Ueyama case R_RELAX_TLS_GD_TO_LE:
767ff524bf7SRui Ueyama case R_RELAX_TLS_IE_TO_LE:
768ff524bf7SRui Ueyama case R_RELAX_TLS_LD_TO_LE:
76922c1bd57SFangrui Song case R_TPREL:
77021095724SFangrui Song // It is not very clear what to return if the symbol is undefined. With
77121095724SFangrui Song // --noinhibit-exec, even a non-weak undefined reference may reach here.
77221095724SFangrui Song // Just return A, which matches R_ABS, and the behavior of some dynamic
77321095724SFangrui Song // loaders.
7746fcc19afSFangrui Song if (sym.isUndefined())
7753837f427SRui Ueyama return a;
7763837f427SRui Ueyama return getTlsTpOffset(sym) + a;
777ff524bf7SRui Ueyama case R_RELAX_TLS_GD_TO_LE_NEG:
77822c1bd57SFangrui Song case R_TPREL_NEG:
7793837f427SRui Ueyama if (sym.isUndefined())
7803837f427SRui Ueyama return a;
7813837f427SRui Ueyama return -getTlsTpOffset(sym) + a;
782ff524bf7SRui Ueyama case R_SIZE:
7833837f427SRui Ueyama return sym.getSize() + a;
784ff524bf7SRui Ueyama case R_TLSDESC:
7857f1955dcSFangrui Song return in.got->getTlsDescAddr(sym) + a;
78671932241SFangrui Song case R_TLSDESC_PC:
7877f1955dcSFangrui Song return in.got->getTlsDescAddr(sym) + a - p;
788e39c138fSFangrui Song case R_TLSDESC_GOTPLT:
7897f1955dcSFangrui Song return in.got->getTlsDescAddr(sym) + a - in.gotPlt->getVA();
7908329028bSGeorge Rimar case R_AARCH64_TLSDESC_PAGE:
7917f1955dcSFangrui Song return getAArch64Page(in.got->getTlsDescAddr(sym) + a) - getAArch64Page(p);
792ef0f7496SSean Fertile case R_TLSGD_GOT:
7933837f427SRui Ueyama return in.got->getGlobalDynOffset(sym) + a;
794210949a2SFangrui Song case R_TLSGD_GOTPLT:
795b2a3d31eSFangrui Song return in.got->getGlobalDynAddr(sym) + a - in.gotPlt->getVA();
796ff524bf7SRui Ueyama case R_TLSGD_PC:
7973837f427SRui Ueyama return in.got->getGlobalDynAddr(sym) + a - p;
798210949a2SFangrui Song case R_TLSLD_GOTPLT:
7993837f427SRui Ueyama return in.got->getVA() + in.got->getTlsIndexOff() + a - in.gotPlt->getVA();
8001a8343fcSSean Fertile case R_TLSLD_GOT:
8013837f427SRui Ueyama return in.got->getTlsIndexOff() + a;
802ff524bf7SRui Ueyama case R_TLSLD_PC:
8033837f427SRui Ueyama return in.got->getTlsIndexVA() + a - p;
80447ec1e07SGeorge Rimar default:
80547ec1e07SGeorge Rimar llvm_unreachable("invalid expression");
80622ef956aSRafael Espindola }
807604aee13SSimon Atanasyan }
808604aee13SSimon Atanasyan
8092b6fb803SRui Ueyama // This function applies relocations to sections without SHF_ALLOC bit.
8102b6fb803SRui Ueyama // Such sections are never mapped to memory at runtime. Debug sections are
8112b6fb803SRui Ueyama // an example. Relocations in non-alloc sections are much easier to
8122b6fb803SRui Ueyama // handle than in allocated sections because it will never need complex
81307255f81SNico Weber // treatment such as GOT or PLT (because at runtime no one refers them).
8142b6fb803SRui Ueyama // So, we handle relocations for non-alloc sections directly in this
8152b6fb803SRui Ueyama // function as a performance optimization.
816774ea7d0SRafael Espindola template <class ELFT, class RelTy>
relocateNonAlloc(uint8_t * buf,ArrayRef<RelTy> rels)8173837f427SRui Ueyama void InputSection::relocateNonAlloc(uint8_t *buf, ArrayRef<RelTy> rels) {
8183837f427SRui Ueyama const unsigned bits = sizeof(typename ELFT::uint) * 8;
819745420d3SFangrui Song const TargetInfo &target = *elf::target;
820e618ccbfSFangrui Song const bool isDebug = isDebugSection(*this);
821e618ccbfSFangrui Song const bool isDebugLocOrRanges =
822e618ccbfSFangrui Song isDebug && (name == ".debug_loc" || name == ".debug_ranges");
823e6ad78feSFangrui Song const bool isDebugLine = isDebug && name == ".debug_line";
8244ce56b81SFangrui Song Optional<uint64_t> tombstone;
8254ce56b81SFangrui Song for (const auto &patAndValue : llvm::reverse(config->deadRelocInNonAlloc))
8264ce56b81SFangrui Song if (patAndValue.first.match(this->name)) {
8274ce56b81SFangrui Song tombstone = patAndValue.second;
8284ce56b81SFangrui Song break;
8294ce56b81SFangrui Song }
830ce135ff6SRui Ueyama
8313837f427SRui Ueyama for (const RelTy &rel : rels) {
8323837f427SRui Ueyama RelType type = rel.getType(config->isMips64EL);
83365b620beSRui Ueyama
83465b620beSRui Ueyama // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations
83565b620beSRui Ueyama // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed
83665b620beSRui Ueyama // in 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we
83765b620beSRui Ueyama // need to keep this bug-compatible code for a while.
8383837f427SRui Ueyama if (config->emachine == EM_386 && type == R_386_GOTPC)
83965b620beSRui Ueyama continue;
84065b620beSRui Ueyama
841e973c137SFangrui Song uint64_t offset = rel.r_offset;
8423837f427SRui Ueyama uint8_t *bufLoc = buf + offset;
8433837f427SRui Ueyama int64_t addend = getAddend<ELFT>(rel);
844890ce0c1SRui Ueyama if (!RelTy::IsRela)
845745420d3SFangrui Song addend += target.getImplicitAddend(bufLoc, type);
8462b6fb803SRui Ueyama
8473837f427SRui Ueyama Symbol &sym = getFile<ELFT>()->getRelocTargetSym(rel);
848745420d3SFangrui Song RelExpr expr = target.getRelExpr(type, sym, bufLoc);
8493837f427SRui Ueyama if (expr == R_NONE)
850b27bb59aSPetr Hosek continue;
85190dacc25SGeorge Rimar
8524ce56b81SFangrui Song if (tombstone ||
853745420d3SFangrui Song (isDebug && (type == target.symbolicRel || expr == R_DTPREL))) {
854e618ccbfSFangrui Song // Resolve relocations in .debug_* referencing (discarded symbols or ICF
855e618ccbfSFangrui Song // folded section symbols) to a tombstone value. Resolving to addend is
856e618ccbfSFangrui Song // unsatisfactory because the result address range may collide with a
857e618ccbfSFangrui Song // valid range of low address, or leave multiple CUs claiming ownership of
858e618ccbfSFangrui Song // the same range of code, which may confuse consumers.
859e618ccbfSFangrui Song //
860e618ccbfSFangrui Song // To address the problems, we use -1 as a tombstone value for most
861e618ccbfSFangrui Song // .debug_* sections. We have to ignore the addend because we don't want
862e618ccbfSFangrui Song // to resolve an address attribute (which may have a non-zero addend) to
863e618ccbfSFangrui Song // -1+addend (wrap around to a low address).
864e618ccbfSFangrui Song //
8656fa1343bSFangrui Song // R_DTPREL type relocations represent an offset into the dynamic thread
8666fa1343bSFangrui Song // vector. The computed value is st_value plus a non-negative offset.
8676fa1343bSFangrui Song // Negative values are invalid, so -1 can be used as the tombstone value.
8686fa1343bSFangrui Song //
869e618ccbfSFangrui Song // If the referenced symbol is discarded (made Undefined), or the
870e618ccbfSFangrui Song // section defining the referenced symbol is garbage collected,
871e1b6b5beSFangrui Song // sym.getOutputSection() is nullptr. `ds->folded` catches the ICF folded
872e1b6b5beSFangrui Song // case. However, resolving a relocation in .debug_line to -1 would stop
873e1b6b5beSFangrui Song // debugger users from setting breakpoints on the folded-in function, so
874e1b6b5beSFangrui Song // exclude .debug_line.
875e618ccbfSFangrui Song //
876e618ccbfSFangrui Song // For pre-DWARF-v5 .debug_loc and .debug_ranges, -1 is a reserved value
877004be403SFangrui Song // (base address selection entry), use 1 (which is used by GNU ld for
878004be403SFangrui Song // .debug_ranges).
879004be403SFangrui Song //
880004be403SFangrui Song // TODO To reduce disruption, we use 0 instead of -1 as the tombstone
881004be403SFangrui Song // value. Enable -1 in a future release.
882e618ccbfSFangrui Song auto *ds = dyn_cast<Defined>(&sym);
883e1b6b5beSFangrui Song if (!sym.getOutputSection() || (ds && ds->folded && !isDebugLine)) {
8844ce56b81SFangrui Song // If -z dead-reloc-in-nonalloc= is specified, respect it.
885004be403SFangrui Song const uint64_t value = tombstone ? SignExtend64<bits>(*tombstone)
886004be403SFangrui Song : (isDebugLocOrRanges ? 1 : 0);
887745420d3SFangrui Song target.relocateNoSym(bufLoc, type, value);
888e618ccbfSFangrui Song continue;
889e618ccbfSFangrui Song }
890e618ccbfSFangrui Song }
891e00ac48dSIgor Kudrin
892e00ac48dSIgor Kudrin // For a relocatable link, only tombstone values are applied.
893e00ac48dSIgor Kudrin if (config->relocatable)
894e00ac48dSIgor Kudrin continue;
895e00ac48dSIgor Kudrin
896e00ac48dSIgor Kudrin if (expr == R_SIZE) {
897e00ac48dSIgor Kudrin target.relocateNoSym(bufLoc, type,
898e00ac48dSIgor Kudrin SignExtend64<bits>(sym.getSize() + addend));
899e00ac48dSIgor Kudrin continue;
900e00ac48dSIgor Kudrin }
901e00ac48dSIgor Kudrin
902e00ac48dSIgor Kudrin // R_ABS/R_DTPREL and some other relocations can be used from non-SHF_ALLOC
903e00ac48dSIgor Kudrin // sections.
904e00ac48dSIgor Kudrin if (expr == R_ABS || expr == R_DTPREL || expr == R_GOTPLTREL ||
905e00ac48dSIgor Kudrin expr == R_RISCV_ADD) {
906745420d3SFangrui Song target.relocateNoSym(bufLoc, type, SignExtend64<bits>(sym.getVA(addend)));
907e00ac48dSIgor Kudrin continue;
908e00ac48dSIgor Kudrin }
909e00ac48dSIgor Kudrin
9105f404a74SFangrui Song std::string msg = getLocation(offset) + ": has non-ABS relocation " +
911e00ac48dSIgor Kudrin toString(type) + " against symbol '" + toString(sym) +
912e00ac48dSIgor Kudrin "'";
913e00ac48dSIgor Kudrin if (expr != R_PC && expr != R_ARM_PCA) {
914e00ac48dSIgor Kudrin error(msg);
915e00ac48dSIgor Kudrin return;
916e00ac48dSIgor Kudrin }
917e00ac48dSIgor Kudrin
918e00ac48dSIgor Kudrin // If the control reaches here, we found a PC-relative relocation in a
919e00ac48dSIgor Kudrin // non-ALLOC section. Since non-ALLOC section is not loaded into memory
920e00ac48dSIgor Kudrin // at runtime, the notion of PC-relative doesn't make sense here. So,
921e00ac48dSIgor Kudrin // this is a usage error. However, GNU linkers historically accept such
922e00ac48dSIgor Kudrin // relocations without any errors and relocate them as if they were at
923e00ac48dSIgor Kudrin // address 0. For bug-compatibilty, we accept them with warnings. We
924e00ac48dSIgor Kudrin // know Steel Bank Common Lisp as of 2018 have this bug.
925e00ac48dSIgor Kudrin warn(msg);
926e00ac48dSIgor Kudrin target.relocateNoSym(
927e00ac48dSIgor Kudrin bufLoc, type,
928e00ac48dSIgor Kudrin SignExtend64<bits>(sym.getVA(addend - offset - outSecOff)));
9292b6fb803SRui Ueyama }
9302b6fb803SRui Ueyama }
9312b6fb803SRui Ueyama
9324f48b3efSIgor Kudrin // This is used when '-r' is given.
9334f48b3efSIgor Kudrin // For REL targets, InputSection::copyRelocations() may store artificial
9344f48b3efSIgor Kudrin // relocations aimed to update addends. They are handled in relocateAlloc()
9354f48b3efSIgor Kudrin // for allocatable sections, and this function does the same for
9364f48b3efSIgor Kudrin // non-allocatable sections, such as sections with debug information.
relocateNonAllocForRelocatable(InputSection * sec,uint8_t * buf)9373837f427SRui Ueyama static void relocateNonAllocForRelocatable(InputSection *sec, uint8_t *buf) {
9383837f427SRui Ueyama const unsigned bits = config->is64 ? 64 : 32;
9394f48b3efSIgor Kudrin
9403837f427SRui Ueyama for (const Relocation &rel : sec->relocations) {
9414f48b3efSIgor Kudrin // InputSection::copyRelocations() adds only R_ABS relocations.
9423837f427SRui Ueyama assert(rel.expr == R_ABS);
943e973c137SFangrui Song uint8_t *bufLoc = buf + rel.offset;
9443837f427SRui Ueyama uint64_t targetVA = SignExtend64(rel.sym->getVA(rel.addend), bits);
945deb5819dSFangrui Song target->relocate(bufLoc, rel, targetVA);
9464f48b3efSIgor Kudrin }
9474f48b3efSIgor Kudrin }
9484f48b3efSIgor Kudrin
94969082f05SRafael Espindola template <class ELFT>
relocate(uint8_t * buf,uint8_t * bufEnd)9503837f427SRui Ueyama void InputSectionBase::relocate(uint8_t *buf, uint8_t *bufEnd) {
9514cfff19bSFangrui Song if ((flags & SHF_EXECINSTR) && LLVM_UNLIKELY(getFile<ELFT>()->splitStack))
9523837f427SRui Ueyama adjustSplitStackFunctionPrologues<ELFT>(buf, bufEnd);
9534fd84c18SSterling Augustine
9543837f427SRui Ueyama if (flags & SHF_ALLOC) {
9553837f427SRui Ueyama relocateAlloc(buf, bufEnd);
956e41f9e06SRui Ueyama return;
957a6465bbbSRafael Espindola }
958a6465bbbSRafael Espindola
9593837f427SRui Ueyama auto *sec = cast<InputSection>(this);
960e00ac48dSIgor Kudrin if (config->relocatable)
9613837f427SRui Ueyama relocateNonAllocForRelocatable(sec, buf);
962e00ac48dSIgor Kudrin // For a relocatable link, also call relocateNonAlloc() to rewrite applicable
963e00ac48dSIgor Kudrin // locations with tombstone values.
964ecc93ed2SFangrui Song const RelsOrRelas<ELFT> rels = sec->template relsOrRelas<ELFT>();
965ecc93ed2SFangrui Song if (rels.areRelocsRel())
966ecc93ed2SFangrui Song sec->relocateNonAlloc<ELFT>(buf, rels.rels);
9672b6fb803SRui Ueyama else
968ecc93ed2SFangrui Song sec->relocateNonAlloc<ELFT>(buf, rels.relas);
969ecc93ed2SFangrui Song }
9702b6fb803SRui Ueyama
relocateAlloc(uint8_t * buf,uint8_t * bufEnd)9713837f427SRui Ueyama void InputSectionBase::relocateAlloc(uint8_t *buf, uint8_t *bufEnd) {
9723837f427SRui Ueyama assert(flags & SHF_ALLOC);
9733837f427SRui Ueyama const unsigned bits = config->wordsize * 8;
974745420d3SFangrui Song const TargetInfo &target = *elf::target;
975cddb0dbcSNemanja Ivanovic uint64_t lastPPCRelaxedRelocOff = UINT64_C(-1);
9768acc3b4aSAlexander Shaposhnikov AArch64Relaxer aarch64relaxer(relocations);
9778acc3b4aSAlexander Shaposhnikov for (size_t i = 0, size = relocations.size(); i != size; ++i) {
9788acc3b4aSAlexander Shaposhnikov const Relocation &rel = relocations[i];
97994317878SSriraman Tallam if (rel.expr == R_NONE)
98094317878SSriraman Tallam continue;
9813837f427SRui Ueyama uint64_t offset = rel.offset;
9823837f427SRui Ueyama uint8_t *bufLoc = buf + offset;
98322ef956aSRafael Espindola
9848acc3b4aSAlexander Shaposhnikov uint64_t secAddr = getOutputSection()->addr;
985e973c137SFangrui Song if (auto *sec = dyn_cast<InputSection>(this))
9868acc3b4aSAlexander Shaposhnikov secAddr += sec->outSecOff;
9878acc3b4aSAlexander Shaposhnikov const uint64_t addrLoc = secAddr + offset;
988d29766bbSFangrui Song const uint64_t targetVA =
989d29766bbSFangrui Song SignExtend64(getRelocTargetVA(file, rel.type, rel.addend, addrLoc,
9908acc3b4aSAlexander Shaposhnikov *rel.sym, rel.expr),
9918acc3b4aSAlexander Shaposhnikov bits);
992d29766bbSFangrui Song switch (rel.expr) {
9936611d58fSFangrui Song case R_RELAX_HINT:
9946611d58fSFangrui Song continue;
9955c33b91bSGeorge Rimar case R_RELAX_GOT_PC:
996f10c8290SGeorge Rimar case R_RELAX_GOT_PC_NOPIC:
997745420d3SFangrui Song target.relaxGot(bufLoc, rel, targetVA);
998912251e8SFangrui Song break;
9998acc3b4aSAlexander Shaposhnikov case R_AARCH64_GOT_PAGE_PC:
10008acc3b4aSAlexander Shaposhnikov if (i + 1 < size && aarch64relaxer.tryRelaxAdrpLdr(
10018acc3b4aSAlexander Shaposhnikov rel, relocations[i + 1], secAddr, buf)) {
10028acc3b4aSAlexander Shaposhnikov ++i;
10038acc3b4aSAlexander Shaposhnikov continue;
10048acc3b4aSAlexander Shaposhnikov }
10058acc3b4aSAlexander Shaposhnikov target.relocate(bufLoc, rel, targetVA);
10068acc3b4aSAlexander Shaposhnikov break;
10074450a2a2SAlexander Shaposhnikov case R_AARCH64_PAGE_PC:
10084450a2a2SAlexander Shaposhnikov if (i + 1 < size && aarch64relaxer.tryRelaxAdrpAdd(
10094450a2a2SAlexander Shaposhnikov rel, relocations[i + 1], secAddr, buf)) {
10104450a2a2SAlexander Shaposhnikov ++i;
10114450a2a2SAlexander Shaposhnikov continue;
10124450a2a2SAlexander Shaposhnikov }
10134450a2a2SAlexander Shaposhnikov target.relocate(bufLoc, rel, targetVA);
10144450a2a2SAlexander Shaposhnikov break;
1015cddb0dbcSNemanja Ivanovic case R_PPC64_RELAX_GOT_PC: {
1016cddb0dbcSNemanja Ivanovic // The R_PPC64_PCREL_OPT relocation must appear immediately after
1017cddb0dbcSNemanja Ivanovic // R_PPC64_GOT_PCREL34 in the relocations table at the same offset.
1018cddb0dbcSNemanja Ivanovic // We can only relax R_PPC64_PCREL_OPT if we have also relaxed
1019cddb0dbcSNemanja Ivanovic // the associated R_PPC64_GOT_PCREL34 since only the latter has an
1020cddb0dbcSNemanja Ivanovic // associated symbol. So save the offset when relaxing R_PPC64_GOT_PCREL34
1021cddb0dbcSNemanja Ivanovic // and only relax the other if the saved offset matches.
1022d29766bbSFangrui Song if (rel.type == R_PPC64_GOT_PCREL34)
1023cddb0dbcSNemanja Ivanovic lastPPCRelaxedRelocOff = offset;
1024d29766bbSFangrui Song if (rel.type == R_PPC64_PCREL_OPT && offset != lastPPCRelaxedRelocOff)
1025cddb0dbcSNemanja Ivanovic break;
1026745420d3SFangrui Song target.relaxGot(bufLoc, rel, targetVA);
1027cddb0dbcSNemanja Ivanovic break;
1028cddb0dbcSNemanja Ivanovic }
1029f9106e85SSean Fertile case R_PPC64_RELAX_TOC:
1030b257d3c8SFangrui Song // rel.sym refers to the STT_SECTION symbol associated to the .toc input
1031b257d3c8SFangrui Song // section. If an R_PPC64_TOC16_LO (.toc + addend) references the TOC
1032b257d3c8SFangrui Song // entry, there may be R_PPC64_TOC16_HA not paired with
1033b257d3c8SFangrui Song // R_PPC64_TOC16_LO_DS. Don't relax. This loses some relaxation
1034b257d3c8SFangrui Song // opportunities but is safe.
1035b257d3c8SFangrui Song if (ppc64noTocRelax.count({rel.sym, rel.addend}) ||
1036b257d3c8SFangrui Song !tryRelaxPPC64TocIndirection(rel, bufLoc))
1037745420d3SFangrui Song target.relocate(bufLoc, rel, targetVA);
10385c33b91bSGeorge Rimar break;
103950223310SRafael Espindola case R_RELAX_TLS_IE_TO_LE:
1040745420d3SFangrui Song target.relaxTlsIeToLe(bufLoc, rel, targetVA);
104150223310SRafael Espindola break;
104250223310SRafael Espindola case R_RELAX_TLS_LD_TO_LE:
104375c348a0SZaara Syeda case R_RELAX_TLS_LD_TO_LE_ABS:
1044745420d3SFangrui Song target.relaxTlsLdToLe(bufLoc, rel, targetVA);
104550223310SRafael Espindola break;
104650223310SRafael Espindola case R_RELAX_TLS_GD_TO_LE:
104769f5402bSRafael Espindola case R_RELAX_TLS_GD_TO_LE_NEG:
1048745420d3SFangrui Song target.relaxTlsGdToLe(bufLoc, rel, targetVA);
104950223310SRafael Espindola break;
10508ef9babbSGeorge Rimar case R_AARCH64_RELAX_TLS_GD_TO_IE_PAGE_PC:
105150223310SRafael Espindola case R_RELAX_TLS_GD_TO_IE:
1052e1979aedSRafael Espindola case R_RELAX_TLS_GD_TO_IE_ABS:
1053f60cb34cSSean Fertile case R_RELAX_TLS_GD_TO_IE_GOT_OFF:
1054e1f3191aSFangrui Song case R_RELAX_TLS_GD_TO_IE_GOTPLT:
1055745420d3SFangrui Song target.relaxTlsGdToIe(bufLoc, rel, targetVA);
105650223310SRafael Espindola break;
10578522d579SFangrui Song case R_PPC64_CALL:
1058f60cb34cSSean Fertile // If this is a call to __tls_get_addr, it may be part of a TLS
1059f60cb34cSSean Fertile // sequence that has been relaxed and turned into a nop. In this
1060f60cb34cSSean Fertile // case, we don't want to handle it as a call.
10613837f427SRui Ueyama if (read32(bufLoc) == 0x60000000) // nop
1062f60cb34cSSean Fertile break;
1063f60cb34cSSean Fertile
106429da3e35SRafael Espindola // Patch a nop (0x60000000) to a ld.
10653837f427SRui Ueyama if (rel.sym->needsTocRestore) {
1066bb87364fSFangrui Song // gcc/gfortran 5.4, 6.3 and earlier versions do not add nop for
1067bb87364fSFangrui Song // recursive calls even if the function is preemptible. This is not
1068bb87364fSFangrui Song // wrong in the common case where the function is not preempted at
1069bb87364fSFangrui Song // runtime. Just ignore.
1070bb87364fSFangrui Song if ((bufLoc + 8 > bufEnd || read32(bufLoc + 4) != 0x60000000) &&
1071bb87364fSFangrui Song rel.sym->file != file) {
1072bb87364fSFangrui Song // Use substr(6) to remove the "__plt_" prefix.
1073bb87364fSFangrui Song errorOrWarn(getErrorLocation(bufLoc) + "call to " +
1074bb87364fSFangrui Song lld::toString(*rel.sym).substr(6) +
1075bb87364fSFangrui Song " lacks nop, can't restore toc");
1076d134d2e5SRui Ueyama break;
107725b488b0SZaara Syeda }
10783837f427SRui Ueyama write32(bufLoc + 4, 0xe8410018); // ld %r2, 24(%r1)
1079d2e887d2SSean Fertile }
1080745420d3SFangrui Song target.relocate(bufLoc, rel, targetVA);
1081d134d2e5SRui Ueyama break;
108250223310SRafael Espindola default:
1083745420d3SFangrui Song target.relocate(bufLoc, rel, targetVA);
108450223310SRafael Espindola break;
108550223310SRafael Espindola }
10869d06ab6dSRafael Espindola }
108794317878SSriraman Tallam
108894317878SSriraman Tallam // Apply jumpInstrMods. jumpInstrMods are created when the opcode of
108994317878SSriraman Tallam // a jmp insn must be modified to shrink the jmp insn or to flip the jmp
109094317878SSriraman Tallam // insn. This is primarily used to relax and optimize jumps created with
109194317878SSriraman Tallam // basic block sections.
1092e90c8c04SFangrui Song if (jumpInstrMod) {
1093e90c8c04SFangrui Song target.applyJumpInstrMod(buf + jumpInstrMod->offset, jumpInstrMod->original,
1094e90c8c04SFangrui Song jumpInstrMod->size);
109594317878SSriraman Tallam }
10969d06ab6dSRafael Espindola }
10979d06ab6dSRafael Espindola
10984fd84c18SSterling Augustine // For each function-defining prologue, find any calls to __morestack,
10994fd84c18SSterling Augustine // and replace them with calls to __morestack_non_split.
switchMorestackCallsToMorestackNonSplit(DenseSet<Defined * > & prologues,SmallVector<Relocation *,0> & morestackCalls)11004fd84c18SSterling Augustine static void switchMorestackCallsToMorestackNonSplit(
1101d97749faSFangrui Song DenseSet<Defined *> &prologues,
1102d97749faSFangrui Song SmallVector<Relocation *, 0> &morestackCalls) {
11034fd84c18SSterling Augustine
11044fd84c18SSterling Augustine // If the target adjusted a function's prologue, all calls to
11054fd84c18SSterling Augustine // __morestack inside that function should be switched to
11064fd84c18SSterling Augustine // __morestack_non_split.
11073837f427SRui Ueyama Symbol *moreStackNonSplit = symtab->find("__morestack_non_split");
11083837f427SRui Ueyama if (!moreStackNonSplit) {
11098b2f3323SFangrui Song error("mixing split-stack objects requires a definition of "
11100f6d3181SJordan Rupprecht "__morestack_non_split");
11110f6d3181SJordan Rupprecht return;
11120f6d3181SJordan Rupprecht }
11134fd84c18SSterling Augustine
11144fd84c18SSterling Augustine // Sort both collections to compare addresses efficiently.
11153837f427SRui Ueyama llvm::sort(morestackCalls, [](const Relocation *l, const Relocation *r) {
11163837f427SRui Ueyama return l->offset < r->offset;
11174fd84c18SSterling Augustine });
11183837f427SRui Ueyama std::vector<Defined *> functions(prologues.begin(), prologues.end());
11193837f427SRui Ueyama llvm::sort(functions, [](const Defined *l, const Defined *r) {
11203837f427SRui Ueyama return l->value < r->value;
1121dbaeec68SFangrui Song });
11224fd84c18SSterling Augustine
11233837f427SRui Ueyama auto it = morestackCalls.begin();
11243837f427SRui Ueyama for (Defined *f : functions) {
11254fd84c18SSterling Augustine // Find the first call to __morestack within the function.
11263837f427SRui Ueyama while (it != morestackCalls.end() && (*it)->offset < f->value)
11273837f427SRui Ueyama ++it;
11284fd84c18SSterling Augustine // Adjust all calls inside the function.
11293837f427SRui Ueyama while (it != morestackCalls.end() && (*it)->offset < f->value + f->size) {
11303837f427SRui Ueyama (*it)->sym = moreStackNonSplit;
11313837f427SRui Ueyama ++it;
11324fd84c18SSterling Augustine }
11334fd84c18SSterling Augustine }
11344fd84c18SSterling Augustine }
11354fd84c18SSterling Augustine
enclosingPrologueAttempted(uint64_t offset,const DenseSet<Defined * > & prologues)11363837f427SRui Ueyama static bool enclosingPrologueAttempted(uint64_t offset,
11373837f427SRui Ueyama const DenseSet<Defined *> &prologues) {
11383837f427SRui Ueyama for (Defined *f : prologues)
11393837f427SRui Ueyama if (f->value <= offset && offset < f->value + f->size)
11404fd84c18SSterling Augustine return true;
11414fd84c18SSterling Augustine return false;
11424fd84c18SSterling Augustine }
11434fd84c18SSterling Augustine
11444fd84c18SSterling Augustine // If a function compiled for split stack calls a function not
11454fd84c18SSterling Augustine // compiled for split stack, then the caller needs its prologue
11464fd84c18SSterling Augustine // adjusted to ensure that the called function will have enough stack
11474fd84c18SSterling Augustine // available. Find those functions, and adjust their prologues.
11484fd84c18SSterling Augustine template <class ELFT>
adjustSplitStackFunctionPrologues(uint8_t * buf,uint8_t * end)11493837f427SRui Ueyama void InputSectionBase::adjustSplitStackFunctionPrologues(uint8_t *buf,
11503837f427SRui Ueyama uint8_t *end) {
11513837f427SRui Ueyama DenseSet<Defined *> prologues;
1152d97749faSFangrui Song SmallVector<Relocation *, 0> morestackCalls;
11534fd84c18SSterling Augustine
11543837f427SRui Ueyama for (Relocation &rel : relocations) {
11554fd84c18SSterling Augustine // Ignore calls into the split-stack api.
11563837f427SRui Ueyama if (rel.sym->getName().startswith("__morestack")) {
11573837f427SRui Ueyama if (rel.sym->getName().equals("__morestack"))
11583837f427SRui Ueyama morestackCalls.push_back(&rel);
11594fd84c18SSterling Augustine continue;
11604fd84c18SSterling Augustine }
11614fd84c18SSterling Augustine
11624fd84c18SSterling Augustine // A relocation to non-function isn't relevant. Sometimes
11634fd84c18SSterling Augustine // __morestack is not marked as a function, so this check comes
11644fd84c18SSterling Augustine // after the name check.
11653837f427SRui Ueyama if (rel.sym->type != STT_FUNC)
11664fd84c18SSterling Augustine continue;
11674fd84c18SSterling Augustine
116848b46974SSterling Augustine // If the callee's-file was compiled with split stack, nothing to do. In
116948b46974SSterling Augustine // this context, a "Defined" symbol is one "defined by the binary currently
117048b46974SSterling Augustine // being produced". So an "undefined" symbol might be provided by a shared
117148b46974SSterling Augustine // library. It is not possible to tell how such symbols were compiled, so be
117248b46974SSterling Augustine // conservative.
11733837f427SRui Ueyama if (Defined *d = dyn_cast<Defined>(rel.sym))
11743837f427SRui Ueyama if (InputSection *isec = cast_or_null<InputSection>(d->section))
11753837f427SRui Ueyama if (!isec || !isec->getFile<ELFT>() || isec->getFile<ELFT>()->splitStack)
11760f6d3181SJordan Rupprecht continue;
11770f6d3181SJordan Rupprecht
11783837f427SRui Ueyama if (enclosingPrologueAttempted(rel.offset, prologues))
11794fd84c18SSterling Augustine continue;
11804fd84c18SSterling Augustine
1181469144ffSFangrui Song if (Defined *f = getEnclosingFunction(rel.offset)) {
11823837f427SRui Ueyama prologues.insert(f);
1183e973c137SFangrui Song if (target->adjustPrologueForCrossSplitStack(buf + f->value, end,
1184e973c137SFangrui Song f->stOther))
11854fd84c18SSterling Augustine continue;
11863837f427SRui Ueyama if (!getFile<ELFT>()->someNoSplitStack)
118707837b8fSFangrui Song error(lld::toString(this) + ": " + f->getName() +
11883837f427SRui Ueyama " (with -fsplit-stack) calls " + rel.sym->getName() +
11890f6d3181SJordan Rupprecht " (without -fsplit-stack), but couldn't adjust its prologue");
11904fd84c18SSterling Augustine }
11910f6d3181SJordan Rupprecht }
11924b5ec7fbSSean Fertile
11933837f427SRui Ueyama if (target->needsMoreStackNonSplit)
11943837f427SRui Ueyama switchMorestackCallsToMorestackNonSplit(prologues, morestackCalls);
11954fd84c18SSterling Augustine }
11964fd84c18SSterling Augustine
writeTo(uint8_t * buf)11973837f427SRui Ueyama template <class ELFT> void InputSection::writeTo(uint8_t *buf) {
1198aa27bab5SFangrui Song if (LLVM_UNLIKELY(type == SHT_NOBITS))
1199aa27bab5SFangrui Song return;
120082bd8be6SGeorge Rimar // If -r or --emit-relocs is given, then an InputSection
120182bd8be6SGeorge Rimar // may be a relocation section.
1202aa27bab5SFangrui Song if (LLVM_UNLIKELY(type == SHT_RELA)) {
1203bf7f3dd7SFangrui Song copyRelocations<ELFT>(buf, getDataAs<typename ELFT::Rela>());
120458941ee1SGeorge Rimar return;
120558941ee1SGeorge Rimar }
1206aa27bab5SFangrui Song if (LLVM_UNLIKELY(type == SHT_REL)) {
1207bf7f3dd7SFangrui Song copyRelocations<ELFT>(buf, getDataAs<typename ELFT::Rel>());
120858941ee1SGeorge Rimar return;
120958941ee1SGeorge Rimar }
121058941ee1SGeorge Rimar
1211f08b38cbSRui Ueyama // If -r is given, we may have a SHT_GROUP section.
1212aa27bab5SFangrui Song if (LLVM_UNLIKELY(type == SHT_GROUP)) {
1213bf7f3dd7SFangrui Song copyShtGroup<ELFT>(buf);
12143b189d16SGeorge Rimar return;
12153b189d16SGeorge Rimar }
12163b189d16SGeorge Rimar
1217e28c1464SRui Ueyama // If this is a compressed section, uncompress section contents directly
1218e28c1464SRui Ueyama // to the buffer.
12193837f427SRui Ueyama if (uncompressedSize >= 0) {
12203837f427SRui Ueyama size_t size = uncompressedSize;
1221*e690137dSFangrui Song if (Error e = compression::zlib::uncompress(rawData, buf, size))
1222e28c1464SRui Ueyama fatal(toString(this) +
12233837f427SRui Ueyama ": uncompress failed: " + llvm::toString(std::move(e)));
1224bf7f3dd7SFangrui Song uint8_t *bufEnd = buf + size;
1225bf7f3dd7SFangrui Song relocate<ELFT>(buf, bufEnd);
1226e28c1464SRui Ueyama return;
1227e28c1464SRui Ueyama }
1228e28c1464SRui Ueyama
12290faa53aaSRui Ueyama // Copy section contents from source object file to output file
12300faa53aaSRui Ueyama // and then apply relocations.
123114b7785cSFangrui Song memcpy(buf, rawData.data(), rawData.size());
123214b7785cSFangrui Song relocate<ELFT>(buf, buf + rawData.size());
12339d06ab6dSRafael Espindola }
12349d06ab6dSRafael Espindola
replace(InputSection * other)12353837f427SRui Ueyama void InputSection::replace(InputSection *other) {
12363837f427SRui Ueyama alignment = std::max(alignment, other->alignment);
1237ba2816beSPeter Collingbourne
1238ba2816beSPeter Collingbourne // When a section is replaced with another section that was allocated to
1239ba2816beSPeter Collingbourne // another partition, the replacement section (and its associated sections)
1240ba2816beSPeter Collingbourne // need to be placed in the main partition so that both partitions will be
1241ba2816beSPeter Collingbourne // able to access it.
12423837f427SRui Ueyama if (partition != other->partition) {
12433837f427SRui Ueyama partition = 1;
12443837f427SRui Ueyama for (InputSection *isec : dependentSections)
12453837f427SRui Ueyama isec->partition = 1;
1246ba2816beSPeter Collingbourne }
1247ba2816beSPeter Collingbourne
12483837f427SRui Ueyama other->repl = repl;
12493837f427SRui Ueyama other->markDead();
12500b289529SRui Ueyama }
12510b289529SRui Ueyama
12520b289529SRui Ueyama template <class ELFT>
EhInputSection(ObjFile<ELFT> & f,const typename ELFT::Shdr & header,StringRef name)12533837f427SRui Ueyama EhInputSection::EhInputSection(ObjFile<ELFT> &f,
12543837f427SRui Ueyama const typename ELFT::Shdr &header,
12553837f427SRui Ueyama StringRef name)
12563837f427SRui Ueyama : InputSectionBase(f, header, name, InputSectionBase::EHFrame) {}
12570c6a4f19SRafael Espindola
getParent() const1258db5e56f7SRafael Espindola SyntheticSection *EhInputSection::getParent() const {
12593837f427SRui Ueyama return cast_or_null<SyntheticSection>(parent);
1260db5e56f7SRafael Espindola }
1261db5e56f7SRafael Espindola
12622deeb609SRafael Espindola // Returns the index of the first relocation that points to a region between
12632deeb609SRafael Espindola // Begin and Begin+Size.
12642deeb609SRafael Espindola template <class IntTy, class RelTy>
getReloc(IntTy begin,IntTy size,const ArrayRef<RelTy> & rels,unsigned & relocI)12653837f427SRui Ueyama static unsigned getReloc(IntTy begin, IntTy size, const ArrayRef<RelTy> &rels,
12663837f427SRui Ueyama unsigned &relocI) {
12672deeb609SRafael Espindola // Start search from RelocI for fast access. That works because the
12682deeb609SRafael Espindola // relocations are sorted in .eh_frame.
12693837f427SRui Ueyama for (unsigned n = rels.size(); relocI < n; ++relocI) {
12703837f427SRui Ueyama const RelTy &rel = rels[relocI];
12713837f427SRui Ueyama if (rel.r_offset < begin)
12722deeb609SRafael Espindola continue;
12732deeb609SRafael Espindola
12743837f427SRui Ueyama if (rel.r_offset < begin + size)
12753837f427SRui Ueyama return relocI;
12762deeb609SRafael Espindola return -1;
12772deeb609SRafael Espindola }
12782deeb609SRafael Espindola return -1;
12792deeb609SRafael Espindola }
12802deeb609SRafael Espindola
128188abd9b3SRui Ueyama // .eh_frame is a sequence of CIE or FDE records.
128288abd9b3SRui Ueyama // This function splits an input section into records and returns them.
split()12835c02b741SRafael Espindola template <class ELFT> void EhInputSection::split() {
1284ecc93ed2SFangrui Song const RelsOrRelas<ELFT> rels = relsOrRelas<ELFT>();
1285eafd3458SFangrui Song // getReloc expects the relocations to be sorted by r_offset. See the comment
1286eafd3458SFangrui Song // in scanRelocs.
1287eafd3458SFangrui Song if (rels.areRelocsRel()) {
1288eafd3458SFangrui Song SmallVector<typename ELFT::Rel, 0> storage;
1289eafd3458SFangrui Song split<ELFT>(sortRels(rels.rels, storage));
1290eafd3458SFangrui Song } else {
1291eafd3458SFangrui Song SmallVector<typename ELFT::Rela, 0> storage;
1292eafd3458SFangrui Song split<ELFT>(sortRels(rels.relas, storage));
1293eafd3458SFangrui Song }
12942deeb609SRafael Espindola }
12952deeb609SRafael Espindola
12965c02b741SRafael Espindola template <class ELFT, class RelTy>
split(ArrayRef<RelTy> rels)12973837f427SRui Ueyama void EhInputSection::split(ArrayRef<RelTy> rels) {
1298eafd3458SFangrui Song ArrayRef<uint8_t> d = rawData;
1299eafd3458SFangrui Song const char *msg = nullptr;
13003837f427SRui Ueyama unsigned relI = 0;
1301eafd3458SFangrui Song while (!d.empty()) {
1302eafd3458SFangrui Song if (d.size() < 4) {
1303eafd3458SFangrui Song msg = "CIE/FDE too small";
1304eafd3458SFangrui Song break;
130588abd9b3SRui Ueyama }
1306eafd3458SFangrui Song uint64_t size = endian::read32<ELFT::TargetEndianness>(d.data());
1307eafd3458SFangrui Song // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead,
1308eafd3458SFangrui Song // but we do not support that format yet.
1309eafd3458SFangrui Song if (size == UINT32_MAX) {
1310eafd3458SFangrui Song msg = "CIE/FDE too large";
1311eafd3458SFangrui Song break;
1312eafd3458SFangrui Song }
1313eafd3458SFangrui Song size += 4;
1314eafd3458SFangrui Song if (size > d.size()) {
1315eafd3458SFangrui Song msg = "CIE/FDE ends past the end of the section";
1316eafd3458SFangrui Song break;
1317eafd3458SFangrui Song }
1318eafd3458SFangrui Song
1319eafd3458SFangrui Song uint64_t off = d.data() - rawData.data();
1320eafd3458SFangrui Song pieces.emplace_back(off, this, size, getReloc(off, size, rels, relI));
1321eafd3458SFangrui Song d = d.slice(size);
1322eafd3458SFangrui Song }
1323eafd3458SFangrui Song if (msg)
1324eafd3458SFangrui Song errorOrWarn("corrupted .eh_frame: " + Twine(msg) + "\n>>> defined in " +
1325eafd3458SFangrui Song getObjMsg(d.data() - rawData.data()));
132688abd9b3SRui Ueyama }
132788abd9b3SRui Ueyama
132846453119SFangrui Song // Return the offset in an output section for a given input offset.
getParentOffset(uint64_t offset) const132946453119SFangrui Song uint64_t EhInputSection::getParentOffset(uint64_t offset) const {
133046453119SFangrui Song const EhSectionPiece &piece = partition_point(
133146453119SFangrui Song pieces, [=](EhSectionPiece p) { return p.inputOff <= offset; })[-1];
133246453119SFangrui Song if (piece.outputOff == -1) // invalid piece
133346453119SFangrui Song return offset - piece.inputOff;
133446453119SFangrui Song return piece.outputOff + (offset - piece.inputOff);
133546453119SFangrui Song }
133646453119SFangrui Song
findNull(StringRef s,size_t entSize)13373837f427SRui Ueyama static size_t findNull(StringRef s, size_t entSize) {
13383837f427SRui Ueyama for (unsigned i = 0, n = s.size(); i != n; i += entSize) {
13393837f427SRui Ueyama const char *b = s.begin() + i;
13403837f427SRui Ueyama if (std::all_of(b, b + entSize, [](char c) { return c == 0; }))
13413837f427SRui Ueyama return i;
13420b9531c8SRafael Espindola }
1343457273fdSFangrui Song llvm_unreachable("");
13440b9531c8SRafael Espindola }
13450b9531c8SRafael Espindola
getParent() const1346db5e56f7SRafael Espindola SyntheticSection *MergeInputSection::getParent() const {
13473837f427SRui Ueyama return cast_or_null<SyntheticSection>(parent);
1348db5e56f7SRafael Espindola }
1349db5e56f7SRafael Espindola
1350518f1af0SRui Ueyama // Split SHF_STRINGS section. Such section is a sequence of
1351518f1af0SRui Ueyama // null-terminated strings.
splitStrings(StringRef s,size_t entSize)1352457273fdSFangrui Song void MergeInputSection::splitStrings(StringRef s, size_t entSize) {
13534c98d088SFangrui Song const bool live = !(flags & SHF_ALLOC) || !config->gcSections;
1354457273fdSFangrui Song const char *p = s.data(), *end = s.data() + s.size();
1355457273fdSFangrui Song if (!std::all_of(end - entSize, end, [](char c) { return c == 0; }))
13563fc0f7e5SRui Ueyama fatal(toString(this) + ": string is not null terminated");
1357457273fdSFangrui Song if (entSize == 1) {
1358457273fdSFangrui Song // Optimize the common case.
1359457273fdSFangrui Song do {
1360c78c00dcSAndrew Ng size_t size = strlen(p);
1361457273fdSFangrui Song pieces.emplace_back(p - s.begin(), xxHash64(StringRef(p, size)), live);
1362c78c00dcSAndrew Ng p += size + 1;
1363457273fdSFangrui Song } while (p != end);
1364457273fdSFangrui Song } else {
1365457273fdSFangrui Song do {
1366c78c00dcSAndrew Ng size_t size = findNull(StringRef(p, end - p), entSize);
1367457273fdSFangrui Song pieces.emplace_back(p - s.begin(), xxHash64(StringRef(p, size)), live);
1368c78c00dcSAndrew Ng p += size + entSize;
1369457273fdSFangrui Song } while (p != end);
13700b9531c8SRafael Espindola }
13710b9531c8SRafael Espindola }
13720b9531c8SRafael Espindola
1373518f1af0SRui Ueyama // Split non-SHF_STRINGS section. Such section is a sequence of
1374518f1af0SRui Ueyama // fixed size records.
splitNonStrings(ArrayRef<uint8_t> data,size_t entSize)13753837f427SRui Ueyama void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> data,
13763837f427SRui Ueyama size_t entSize) {
13773837f427SRui Ueyama size_t size = data.size();
13783837f427SRui Ueyama assert((size % entSize) == 0);
13794c98d088SFangrui Song const bool live = !(flags & SHF_ALLOC) || !config->gcSections;
138095bf5098SRui Ueyama
1381bc1369faSFangrui Song pieces.resize_for_overwrite(size / entSize);
1382054cdb34SFangrui Song for (size_t i = 0, j = 0; i != size; i += entSize, j++)
1383054cdb34SFangrui Song pieces[j] = {i, (uint32_t)xxHash64(data.slice(i, entSize)), live};
1384518f1af0SRui Ueyama }
1385518f1af0SRui Ueyama
1386518f1af0SRui Ueyama template <class ELFT>
MergeInputSection(ObjFile<ELFT> & f,const typename ELFT::Shdr & header,StringRef name)13873837f427SRui Ueyama MergeInputSection::MergeInputSection(ObjFile<ELFT> &f,
13883837f427SRui Ueyama const typename ELFT::Shdr &header,
13893837f427SRui Ueyama StringRef name)
13903837f427SRui Ueyama : InputSectionBase(f, header, name, InputSectionBase::Merge) {}
13915c73c49cSRafael Espindola
MergeInputSection(uint64_t flags,uint32_t type,uint64_t entsize,ArrayRef<uint8_t> data,StringRef name)13923837f427SRui Ueyama MergeInputSection::MergeInputSection(uint64_t flags, uint32_t type,
13933837f427SRui Ueyama uint64_t entsize, ArrayRef<uint8_t> data,
13943837f427SRui Ueyama StringRef name)
13953837f427SRui Ueyama : InputSectionBase(nullptr, flags, type, entsize, /*Link*/ 0, /*Info*/ 0,
13963837f427SRui Ueyama /*Alignment*/ entsize, data, name, SectionBase::Merge) {}
1397b91bf1a9SRui Ueyama
13982555952bSRui Ueyama // This function is called after we obtain a complete list of input sections
13992555952bSRui Ueyama // that need to be linked. This is responsible to split section contents
14002555952bSRui Ueyama // into small chunks for further processing.
14012555952bSRui Ueyama //
14027dbd1fd7SSam Clegg // Note that this function is called from parallelForEach. This must be
14032555952bSRui Ueyama // thread-safe (i.e. no memory allocation from the pools).
splitIntoPieces()14046119b865SRafael Espindola void MergeInputSection::splitIntoPieces() {
14053837f427SRui Ueyama assert(pieces.empty());
140653a9aff9SRui Ueyama
14073837f427SRui Ueyama if (flags & SHF_STRINGS)
1408457273fdSFangrui Song splitStrings(toStringRef(data()), entsize);
1409518f1af0SRui Ueyama else
14103837f427SRui Ueyama splitNonStrings(data(), entsize);
14110b9531c8SRafael Espindola }
1412c159c967SRafael Espindola
getSectionPiece(uint64_t offset)14138565a87fSFangrui Song SectionPiece &MergeInputSection::getSectionPiece(uint64_t offset) {
14148565a87fSFangrui Song if (rawData.size() <= offset)
1415df6f0ad2SBen Dunbobbin fatal(toString(this) + ": offset is outside the section");
14168565a87fSFangrui Song return partition_point(
14178565a87fSFangrui Song pieces, [=](SectionPiece p) { return p.inputOff <= offset; })[-1];
141895f8d303SRafael Espindola }
141995f8d303SRafael Espindola
14208565a87fSFangrui Song // Return the offset in an output section for a given input offset.
getParentOffset(uint64_t offset) const14213837f427SRui Ueyama uint64_t MergeInputSection::getParentOffset(uint64_t offset) const {
14228565a87fSFangrui Song const SectionPiece &piece = getSectionPiece(offset);
14238565a87fSFangrui Song return piece.outputOff + (offset - piece.inputOff);
1424406b469dSRui Ueyama }
1425f82ed2a2SRafael Espindola
142660403272SRafael Espindola template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
1427709fb2bbSRui Ueyama StringRef);
142860403272SRafael Espindola template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
1429709fb2bbSRui Ueyama StringRef);
143060403272SRafael Espindola template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
1431709fb2bbSRui Ueyama StringRef);
143260403272SRafael Espindola template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
1433709fb2bbSRui Ueyama StringRef);
1434774ea7d0SRafael Espindola
14358d753caaSRui Ueyama template void InputSection::writeTo<ELF32LE>(uint8_t *);
14368d753caaSRui Ueyama template void InputSection::writeTo<ELF32BE>(uint8_t *);
14378d753caaSRui Ueyama template void InputSection::writeTo<ELF64LE>(uint8_t *);
14388d753caaSRui Ueyama template void InputSection::writeTo<ELF64BE>(uint8_t *);
1439c159c967SRafael Espindola
1440ecc93ed2SFangrui Song template RelsOrRelas<ELF32LE> InputSectionBase::relsOrRelas<ELF32LE>() const;
1441ecc93ed2SFangrui Song template RelsOrRelas<ELF32BE> InputSectionBase::relsOrRelas<ELF32BE>() const;
1442ecc93ed2SFangrui Song template RelsOrRelas<ELF64LE> InputSectionBase::relsOrRelas<ELF64LE>() const;
1443ecc93ed2SFangrui Song template RelsOrRelas<ELF64BE> InputSectionBase::relsOrRelas<ELF64BE>() const;
1444ecc93ed2SFangrui Song
144560403272SRafael Espindola template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
144660403272SRafael Espindola const ELF32LE::Shdr &, StringRef);
144760403272SRafael Espindola template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
144860403272SRafael Espindola const ELF32BE::Shdr &, StringRef);
144960403272SRafael Espindola template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
145060403272SRafael Espindola const ELF64LE::Shdr &, StringRef);
145160403272SRafael Espindola template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
145260403272SRafael Espindola const ELF64BE::Shdr &, StringRef);
14535c02b741SRafael Espindola
145460403272SRafael Espindola template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
145560403272SRafael Espindola const ELF32LE::Shdr &, StringRef);
145660403272SRafael Espindola template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
145760403272SRafael Espindola const ELF32BE::Shdr &, StringRef);
145860403272SRafael Espindola template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
145960403272SRafael Espindola const ELF64LE::Shdr &, StringRef);
146060403272SRafael Espindola template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
146160403272SRafael Espindola const ELF64BE::Shdr &, StringRef);
14625c02b741SRafael Espindola
14635c02b741SRafael Espindola template void EhInputSection::split<ELF32LE>();
14645c02b741SRafael Espindola template void EhInputSection::split<ELF32BE>();
14655c02b741SRafael Espindola template void EhInputSection::split<ELF64LE>();
14665c02b741SRafael Espindola template void EhInputSection::split<ELF64BE>();
1467