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 "InputFiles.h"
12#include "OutputSections.h"
13#include "Relocations.h"
14#include "SymbolTable.h"
15#include "Symbols.h"
16#include "SyntheticSections.h"
17#include "Target.h"
18#include "lld/Common/DWARF.h"
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/Compression.h"
21#include "llvm/Support/Endian.h"
22#include "llvm/Support/LEB128.h"
23#include "llvm/Support/xxhash.h"
24#include <algorithm>
25#include <optional>
26#include <vector>
27
28using namespace llvm;
29using namespace llvm::ELF;
30using namespace llvm::object;
31using namespace llvm::support;
32using namespace llvm::support::endian;
33using namespace llvm::sys;
34using namespace lld;
35using namespace lld::elf;
36
37// Returns a string to construct an error message.
38std::string elf::toStr(Ctx &ctx, const InputSectionBase *sec) {
39 return (toStr(ctx, f: sec->file) + ":(" + sec->name + ")").str();
40}
41
42const ELFSyncStream &elf::operator<<(const ELFSyncStream &s,
43 const InputSectionBase *sec) {
44 return s << toStr(ctx&: s.ctx, sec);
45}
46
47template <class ELFT>
48static ArrayRef<uint8_t> getSectionContents(ObjFile<ELFT> &file,
49 const typename ELFT::Shdr &hdr) {
50 if (hdr.sh_type == SHT_NOBITS)
51 return ArrayRef<uint8_t>(nullptr, hdr.sh_size);
52 return check(file.getObj().getSectionContents(hdr));
53}
54
55InputSectionBase::InputSectionBase(InputFile *file, StringRef name,
56 uint32_t type, uint64_t flags, uint32_t link,
57 uint32_t info, uint32_t addralign,
58 uint32_t entsize, ArrayRef<uint8_t> data,
59 Kind sectionKind)
60 : SectionBase(sectionKind, file, name, type, flags, link, info, addralign,
61 entsize),
62 bss(0), decodedCrel(0), keepUnique(0), nopFiller(0),
63 content_(data.data()), size(data.size()) {
64 // In order to reduce memory allocation, we assume that mergeable and
65 // .eh_frame sections are smaller than 4 GiB.
66 if ((sectionKind == SectionBase::Merge ||
67 sectionKind == SectionBase::EHFrame) &&
68 content().size() > UINT32_MAX)
69 ErrAlways(ctx&: getCtx()) << this << ": section too large";
70
71 // The ELF spec states that a value of 0 means the section has
72 // no alignment constraints.
73 uint32_t v = std::max<uint32_t>(a: addralign, b: 1);
74 if (!isPowerOf2_64(Value: v)) {
75 Err(ctx&: getCtx()) << this << ": sh_addralign is not a power of 2";
76 v = 1;
77 }
78 this->addralign = v;
79
80 // If SHF_COMPRESSED is set, parse the header. The legacy .zdebug format is no
81 // longer supported.
82 if (flags & SHF_COMPRESSED) {
83 Ctx &ctx = file->ctx;
84 invokeELFT(parseCompressedHeader, ctx);
85 }
86}
87
88// SHF_INFO_LINK and SHF_GROUP are normally resolved and not copied to the
89// output section. However, for relocatable linking without
90// --force-group-allocation, the SHF_GROUP flag and section groups are retained.
91static uint64_t getFlags(Ctx &ctx, uint64_t flags) {
92 flags &= ~(uint64_t)SHF_INFO_LINK;
93 if (ctx.arg.resolveGroups)
94 flags &= ~(uint64_t)SHF_GROUP;
95 return flags;
96}
97
98template <class ELFT>
99InputSectionBase::InputSectionBase(ObjFile<ELFT> &file,
100 const typename ELFT::Shdr &hdr,
101 StringRef name, Kind sectionKind)
102 : InputSectionBase(&file, name, hdr.sh_type,
103 getFlags(file.ctx, hdr.sh_flags), hdr.sh_link,
104 hdr.sh_info, hdr.sh_addralign, hdr.sh_entsize,
105 getSectionContents(file, hdr), sectionKind) {
106 // We reject object files having insanely large alignments even though
107 // they are allowed by the spec. I think 4GB is a reasonable limitation.
108 // We might want to relax this in the future.
109 if (hdr.sh_addralign > UINT32_MAX) {
110 Err(ctx&: getCtx()) << &file << ": section sh_addralign is too large";
111 addralign = 1;
112 }
113}
114
115size_t InputSectionBase::getSize() const {
116 if (auto *s = dyn_cast<SyntheticSection>(Val: this))
117 return s->getSize();
118 return size - bytesDropped;
119}
120
121template <class ELFT>
122static void decompressAux(Ctx &ctx, const InputSectionBase &sec, uint8_t *out,
123 size_t size) {
124 auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(sec.content_);
125 auto compressed = ArrayRef<uint8_t>(sec.content_, sec.compressedSize)
126 .slice(N: sizeof(typename ELFT::Chdr));
127 if (Error e = hdr->ch_type == ELFCOMPRESS_ZLIB
128 ? compression::zlib::decompress(Input: compressed, Output: out, UncompressedSize&: size)
129 : compression::zstd::decompress(Input: compressed, Output: out, UncompressedSize&: size))
130 Err(ctx) << &sec << ": decompress failed: " << std::move(e);
131}
132
133void InputSectionBase::decompress() const {
134 Ctx &ctx = getCtx();
135 uint8_t *buf = makeThreadLocalN<uint8_t>(n: size);
136 invokeELFT(decompressAux, ctx, *this, buf, size);
137 content_ = buf;
138 compressed = false;
139}
140
141template <class ELFT>
142RelsOrRelas<ELFT> InputSectionBase::relsOrRelas(bool supportsCrel) const {
143 if (relSecIdx == 0)
144 return {};
145 RelsOrRelas<ELFT> ret;
146 auto *f = cast<ObjFile<ELFT>>(file);
147 typename ELFT::Shdr shdr = f->template getELFShdrs<ELFT>()[relSecIdx];
148 if (shdr.sh_type == SHT_CREL) {
149 // Return an iterator if supported by caller.
150 if (supportsCrel) {
151 ret.crels = Relocs<typename ELFT::Crel>(
152 (const uint8_t *)f->mb.getBufferStart() + shdr.sh_offset);
153 return ret;
154 }
155 InputSectionBase *const &relSec = f->getSections()[relSecIdx];
156 // Otherwise, allocate a buffer to hold the decoded RELA relocations. When
157 // called for the first time, relSec is null (without --emit-relocs) or an
158 // InputSection with false decodedCrel.
159 if (!relSec || !cast<InputSection>(Val: relSec)->decodedCrel) {
160 auto *sec = makeThreadLocal<InputSection>(*f, shdr, name);
161 f->cacheDecodedCrel(relSecIdx, sec);
162 sec->type = SHT_RELA;
163 sec->decodedCrel = true;
164
165 RelocsCrel<ELFT::Is64Bits> entries(sec->content_);
166 sec->size = entries.size() * sizeof(typename ELFT::Rela);
167 auto *relas = makeThreadLocalN<typename ELFT::Rela>(entries.size());
168 sec->content_ = reinterpret_cast<uint8_t *>(relas);
169 for (auto [i, r] : llvm::enumerate(entries)) {
170 relas[i].r_offset = r.r_offset;
171 relas[i].setSymbolAndType(r.r_symidx, r.r_type, false);
172 relas[i].r_addend = r.r_addend;
173 }
174 }
175 ret.relas = {ArrayRef(
176 reinterpret_cast<const typename ELFT::Rela *>(relSec->content_),
177 relSec->size / sizeof(typename ELFT::Rela))};
178 return ret;
179 }
180
181 const void *content = f->mb.getBufferStart() + shdr.sh_offset;
182 size_t size = shdr.sh_size;
183 if (shdr.sh_type == SHT_REL) {
184 ret.rels = {ArrayRef(reinterpret_cast<const typename ELFT::Rel *>(content),
185 size / sizeof(typename ELFT::Rel))};
186 } else {
187 assert(shdr.sh_type == SHT_RELA);
188 ret.relas = {
189 ArrayRef(reinterpret_cast<const typename ELFT::Rela *>(content),
190 size / sizeof(typename ELFT::Rela))};
191 }
192 return ret;
193}
194
195Ctx &SectionBase::getCtx() const { return file->ctx; }
196
197uint64_t SectionBase::getOffset(uint64_t offset) const {
198 switch (kind()) {
199 case Output: {
200 auto *os = cast<OutputSection>(Val: this);
201 // For output sections we treat offset -1 as the end of the section.
202 return offset == uint64_t(-1) ? os->size : offset;
203 }
204 case Class:
205 llvm_unreachable("section classes do not have offsets");
206 case Regular:
207 case Synthetic:
208 case Spill:
209 return cast<InputSection>(Val: this)->outSecOff + offset;
210 case EHFrame: {
211 // Two code paths may reach here. First, clang_rt.crtbegin.o and GCC
212 // crtbeginT.o may reference the start of an empty .eh_frame to identify the
213 // start of the output .eh_frame. Just return offset.
214 //
215 // Second, InputSection::copyRelocations on .eh_frame. Some pieces may be
216 // discarded due to GC/ICF. We should compute the output section offset.
217 const EhInputSection *es = cast<EhInputSection>(Val: this);
218 if (!es->content().empty())
219 if (InputSection *isec = es->getParent())
220 return isec->outSecOff + es->getParentOffset(offset);
221 return offset;
222 }
223 case Merge:
224 const MergeInputSection *ms = cast<MergeInputSection>(Val: this);
225 if (InputSection *isec = ms->getParent())
226 return isec->outSecOff + ms->getParentOffset(offset);
227 return ms->getParentOffset(offset);
228 }
229 llvm_unreachable("invalid section kind");
230}
231
232uint64_t SectionBase::getVA(uint64_t offset) const {
233 const OutputSection *out = getOutputSection();
234 return (out ? out->addr : 0) + getOffset(offset);
235}
236
237uint64_t SectionBase::getRelocVA(uint64_t offset) const {
238 if (auto *es = dyn_cast<EhInputSection>(Val: this))
239 return es->getParent()->getVA(offset);
240 return getVA(offset);
241}
242
243OutputSection *SectionBase::getOutputSection() {
244 InputSection *sec;
245 if (auto *isec = dyn_cast<InputSection>(Val: this))
246 sec = isec;
247 else if (auto *ms = dyn_cast<MergeInputSection>(Val: this))
248 sec = ms->getParent();
249 else if (auto *eh = dyn_cast<EhInputSection>(Val: this))
250 sec = eh->getParent();
251 else
252 return cast<OutputSection>(Val: this);
253 return sec ? sec->getParent() : nullptr;
254}
255
256// When a section is compressed, `rawData` consists with a header followed
257// by zlib-compressed data. This function parses a header to initialize
258// `uncompressedSize` member and remove the header from `rawData`.
259template <typename ELFT>
260void InputSectionBase::parseCompressedHeader(Ctx &ctx) {
261 flags &= ~(uint64_t)SHF_COMPRESSED;
262
263 // New-style header
264 if (content().size() < sizeof(typename ELFT::Chdr)) {
265 ErrAlways(ctx) << this << ": corrupted compressed section";
266 return;
267 }
268
269 auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(content().data());
270 if (hdr->ch_type == ELFCOMPRESS_ZLIB) {
271 if (!compression::zlib::isAvailable())
272 ErrAlways(ctx) << this
273 << " is compressed with ELFCOMPRESS_ZLIB, but lld is "
274 "not built with zlib support";
275 } else if (hdr->ch_type == ELFCOMPRESS_ZSTD) {
276 if (!compression::zstd::isAvailable())
277 ErrAlways(ctx) << this
278 << " is compressed with ELFCOMPRESS_ZSTD, but lld is "
279 "not built with zstd support";
280 } else {
281 ErrAlways(ctx) << this << ": unsupported compression type ("
282 << uint32_t(hdr->ch_type) << ")";
283 return;
284 }
285
286 compressed = true;
287 compressedSize = size;
288 size = hdr->ch_size;
289 addralign = std::max<uint32_t>(hdr->ch_addralign, 1);
290}
291
292InputSection *InputSectionBase::getLinkOrderDep() const {
293 assert(flags & SHF_LINK_ORDER);
294 if (!link)
295 return nullptr;
296 return cast<InputSection>(Val: file->getSections()[link]);
297}
298
299// Find a symbol that encloses a given location.
300Defined *InputSectionBase::getEnclosingSymbol(uint64_t offset,
301 uint8_t type) const {
302 if (file->isInternal())
303 return nullptr;
304 for (Symbol *b : file->getSymbols())
305 if (Defined *d = dyn_cast<Defined>(Val: b))
306 if (d->section == this && d->value <= offset &&
307 offset < d->value + d->size && (type == 0 || type == d->type))
308 return d;
309 return nullptr;
310}
311
312// Returns an object file location string. Used to construct an error message.
313std::string InputSectionBase::getLocation(uint64_t offset) const {
314 std::string secAndOffset =
315 (name + "+0x" + Twine::utohexstr(Val: offset) + ")").str();
316
317 std::string filename = toStr(getCtx(), f: file);
318 if (Defined *d = getEnclosingFunction(offset))
319 return filename + ":(function " + toStr(getCtx(), *d) + ": " + secAndOffset;
320
321 return filename + ":(" + secAndOffset;
322}
323
324static void printFileLine(const ELFSyncStream &s, StringRef path,
325 unsigned line) {
326 StringRef filename = path::filename(path);
327 s << filename << ':' << line;
328 if (filename != path)
329 s << " (" << path << ':' << line << ')';
330}
331
332// Print an error message that looks like this:
333//
334// foo.c:42 (/home/alice/possibly/very/long/path/foo.c:42)
335const ELFSyncStream &elf::operator<<(const ELFSyncStream &s,
336 InputSectionBase::SrcMsg &&msg) {
337 auto &sec = msg.sec;
338 if (sec.file->kind() != InputFile::ObjKind)
339 return s;
340 auto &file = cast<ELFFileBase>(Val&: *sec.file);
341
342 // First, look up the DWARF line table.
343 ArrayRef<InputSectionBase *> sections = file.getSections();
344 auto it = llvm::find(Range&: sections, Val: &sec);
345 uint64_t sectionIndex = it != sections.end()
346 ? it - sections.begin()
347 : object::SectionedAddress::UndefSection;
348 DWARFCache *dwarf = file.getDwarf();
349 if (auto info = dwarf->getDILineInfo(offset: msg.offset, sectionIndex))
350 printFileLine(s, path: info->FileName, line: info->Line);
351 else if (auto fileLine = dwarf->getVariableLoc(name: msg.sym.getName()))
352 // If it failed, look up again as a variable.
353 printFileLine(s, path: fileLine->first, line: fileLine->second);
354 else
355 // File.sourceFile contains STT_FILE symbol, and that is a last resort.
356 s << file.sourceFile;
357 return s;
358}
359
360// Returns a filename string along with an optional section name. This
361// function is intended to be used for constructing an error
362// message. The returned message looks like this:
363//
364// path/to/foo.o:(function bar)
365//
366// or
367//
368// path/to/foo.o:(function bar) in archive path/to/bar.a
369const ELFSyncStream &elf::operator<<(const ELFSyncStream &s,
370 InputSectionBase::ObjMsg &&msg) {
371 auto *sec = msg.sec;
372 s << sec->file->getName() << ":(";
373
374 // Find a symbol that encloses a given location. getObjMsg may be called
375 // before ObjFile::initSectionsAndLocalSyms where local symbols are
376 // initialized.
377 if (Defined *d = sec->getEnclosingSymbol(offset: msg.offset))
378 s << d;
379 else
380 s << sec->name << "+0x" << Twine::utohexstr(Val: msg.offset);
381 s << ')';
382 if (!sec->file->archiveName.empty())
383 s << (" in archive " + sec->file->archiveName).str();
384 return s;
385}
386
387PotentialSpillSection::PotentialSpillSection(const InputSectionBase &source,
388 InputSectionDescription &isd)
389 : InputSection(source.file, source.name, source.type, source.flags,
390 source.addralign, source.addralign, {}, SectionBase::Spill),
391 isd(&isd) {}
392
393InputSection InputSection::discarded(nullptr, "", 0, 0, 0, 0,
394 ArrayRef<uint8_t>());
395
396InputSection::InputSection(InputFile *f, StringRef name, uint32_t type,
397 uint64_t flags, uint32_t addralign, uint32_t entsize,
398 ArrayRef<uint8_t> data, Kind k)
399 : InputSectionBase(f, name, type, flags,
400 /*link=*/0, /*info=*/0, addralign, /*entsize=*/entsize,
401 data, k) {
402 assert(f || this == &InputSection::discarded);
403}
404
405template <class ELFT>
406InputSection::InputSection(ObjFile<ELFT> &f, const typename ELFT::Shdr &header,
407 StringRef name)
408 : InputSectionBase(f, header, name, InputSectionBase::Regular) {}
409
410// Copy SHT_GROUP section contents. Used only for the -r option.
411template <class ELFT> void InputSection::copyShtGroup(uint8_t *buf) {
412 // ELFT::Word is the 32-bit integral type in the target endianness.
413 using u32 = typename ELFT::Word;
414 ArrayRef<u32> from = getDataAs<u32>();
415 auto *to = reinterpret_cast<u32 *>(buf);
416
417 // The first entry is not a section number but a flag.
418 *to++ = from[0];
419
420 // Adjust section numbers because section numbers in an input object files are
421 // different in the output. We also need to handle combined or discarded
422 // members.
423 ArrayRef<InputSectionBase *> sections = file->getSections();
424 DenseSet<uint32_t> seen;
425 for (uint32_t idx : from.slice(1)) {
426 OutputSection *osec = sections[idx]->getOutputSection();
427 if (osec && seen.insert(V: osec->sectionIndex).second)
428 *to++ = osec->sectionIndex;
429 }
430}
431
432InputSectionBase *InputSection::getRelocatedSection() const {
433 if (file->isInternal() || !isStaticRelSecType(type))
434 return nullptr;
435 ArrayRef<InputSectionBase *> sections = file->getSections();
436 return sections[info];
437}
438
439template <class ELFT, class RelTy>
440void InputSection::copyRelocations(Ctx &ctx, uint8_t *buf) {
441 bool linkerRelax =
442 ctx.arg.relax && is_contained(Set: {EM_RISCV, EM_LOONGARCH}, Element: ctx.arg.emachine);
443 if (!ctx.arg.relocatable && (linkerRelax || ctx.arg.branchToBranch)) {
444 // On LoongArch and RISC-V, relaxation might change relocations: copy
445 // from internal ones that are updated by relaxation.
446 InputSectionBase *sec = getRelocatedSection();
447 copyRelocations<ELFT, RelTy>(
448 ctx, buf,
449 llvm::make_range(x: sec->relocations.begin(), y: sec->relocations.end()));
450 } else {
451 // Convert the raw relocations in the input section into Relocation objects
452 // suitable to be used by copyRelocations below.
453 struct MapRel {
454 Ctx &ctx;
455 const ObjFile<ELFT> &file;
456 Relocation operator()(const RelTy &rel) const {
457 // RelExpr is not used so set to a dummy value.
458 return Relocation{R_NONE, rel.getType(ctx.arg.isMips64EL), rel.r_offset,
459 getAddend<ELFT>(rel), &file.getRelocTargetSym(rel)};
460 }
461 };
462
463 using RawRels = ArrayRef<RelTy>;
464 using MapRelIter =
465 llvm::mapped_iterator<typename RawRels::iterator, MapRel>;
466 auto mapRel = MapRel{ctx, *getFile<ELFT>()};
467 RawRels rawRels = getDataAs<RelTy>();
468 auto rels = llvm::make_range(MapRelIter(rawRels.begin(), mapRel),
469 MapRelIter(rawRels.end(), mapRel));
470 copyRelocations<ELFT, RelTy>(ctx, buf, rels);
471 }
472}
473
474// This is used for -r and --emit-relocs. We can't use memcpy to copy
475// relocations because we need to update symbol table offset and section index
476// for each relocation. So we copy relocations one by one.
477template <class ELFT, class RelTy, class RelIt>
478void InputSection::copyRelocations(Ctx &ctx, uint8_t *buf,
479 llvm::iterator_range<RelIt> rels) {
480 const TargetInfo &target = *ctx.target;
481 InputSectionBase *sec = getRelocatedSection();
482 (void)sec->contentMaybeDecompress(); // uncompress if needed
483
484 for (const Relocation &rel : rels) {
485 RelType type = rel.type;
486 const ObjFile<ELFT> *file = getFile<ELFT>();
487 Symbol &sym = *rel.sym;
488
489 auto *p = reinterpret_cast<typename ELFT::Rela *>(buf);
490 buf += sizeof(RelTy);
491
492 if (RelTy::HasAddend)
493 p->r_addend = rel.addend;
494
495 // Output section VA is zero for -r, so r_offset is an offset within the
496 // section, but for --emit-relocs it is a virtual address.
497 p->r_offset = sec->getVA(offset: rel.offset);
498 p->setSymbolAndType(ctx.in.symTab->getSymbolIndex(sym), type,
499 ctx.arg.isMips64EL);
500
501 if (sym.type == STT_SECTION) {
502 // We combine multiple section symbols into only one per
503 // section. This means we have to update the addend. That is
504 // trivial for Elf_Rela, but for Elf_Rel we have to write to the
505 // section data. We do that by adding to the Relocation vector.
506
507 // .eh_frame is horribly special and can reference discarded sections. To
508 // avoid having to parse and recreate .eh_frame, we just replace any
509 // relocation in it pointing to discarded sections with R_*_NONE, which
510 // hopefully creates a frame that is ignored at runtime. Also, don't warn
511 // on .gcc_except_table and debug sections.
512 //
513 // See the comment in maybeReportUndefined for PPC32 .got2 and PPC64 .toc
514 auto *d = dyn_cast<Defined>(Val: &sym);
515 if (!d) {
516 if (!isDebugSection(sec: *sec) && sec->name != ".eh_frame" &&
517 sec->name != ".gcc_except_table" && sec->name != ".got2" &&
518 sec->name != ".toc") {
519 uint32_t secIdx = cast<Undefined>(Val&: sym).discardedSecIdx;
520 Elf_Shdr_Impl<ELFT> sec = file->template getELFShdrs<ELFT>()[secIdx];
521 Warn(ctx) << "relocation refers to a discarded section: "
522 << CHECK2(file->getObj().getSectionName(sec), file)
523 << "\n>>> referenced by " << getObjMsg(offset: p->r_offset);
524 }
525 p->setSymbolAndType(0, 0, false);
526 continue;
527 }
528 SectionBase *section = d->section;
529 assert(section->isLive());
530
531 int64_t addend = rel.addend;
532 const uint8_t *bufLoc = sec->content().begin() + rel.offset;
533 if (!RelTy::HasAddend)
534 addend = target.getImplicitAddend(buf: bufLoc, type);
535
536 if (ctx.arg.emachine == EM_MIPS &&
537 target.getRelExpr(type, s: sym, loc: bufLoc) == RE_MIPS_GOTREL) {
538 // Some MIPS relocations depend on "gp" value. By default,
539 // this value has 0x7ff0 offset from a .got section. But
540 // relocatable files produced by a compiler or a linker
541 // might redefine this default value and we must use it
542 // for a calculation of the relocation result. When we
543 // generate EXE or DSO it's trivial. Generating a relocatable
544 // output is more difficult case because the linker does
545 // not calculate relocations in this mode and loses
546 // individual "gp" values used by each input object file.
547 // As a workaround we add the "gp" value to the relocation
548 // addend and save it back to the file.
549 addend += sec->getFile<ELFT>()->mipsGp0;
550 }
551
552 if (RelTy::HasAddend)
553 p->r_addend =
554 sym.getVA(ctx, addend) - section->getOutputSection()->addr;
555 // For SHF_ALLOC sections relocated by REL, append a relocation to
556 // sec->relocations so that relocateAlloc transitively called by
557 // writeSections will update the implicit addend. Non-SHF_ALLOC sections
558 // utilize relocateNonAlloc to process raw relocations and do not need
559 // this sec->relocations change.
560 else if (ctx.arg.relocatable && (sec->flags & SHF_ALLOC) &&
561 type != target.noneRel)
562 sec->addReloc(r: {.expr: R_ABS, .type: type, .offset: rel.offset, .addend: addend, .sym: &sym});
563 } else if (ctx.arg.emachine == EM_PPC && type == R_PPC_PLTREL24 &&
564 p->r_addend >= 0x8000 && sec->file->ppc32Got2) {
565 // Similar to R_MIPS_GPREL{16,32}. If the addend of R_PPC_PLTREL24
566 // indicates that r30 is relative to the input section .got2
567 // (r_addend>=0x8000), after linking, r30 should be relative to the output
568 // section .got2 . To compensate for the shift, adjust r_addend by
569 // ppc32Got->outSecOff.
570 p->r_addend += sec->file->ppc32Got2->outSecOff;
571 }
572 }
573}
574
575// The ARM and AArch64 ABI handle pc-relative relocations to undefined weak
576// references specially. The general rule is that the value of the symbol in
577// this context is the address of the place P. A further special case is that
578// branch relocations to an undefined weak reference resolve to the next
579// instruction.
580static uint32_t getARMUndefinedRelativeWeakVA(RelType type, uint32_t a,
581 uint32_t p) {
582 switch (type) {
583 // Unresolved branch relocations to weak references resolve to next
584 // instruction, this will be either 2 or 4 bytes on from P.
585 case R_ARM_THM_JUMP8:
586 case R_ARM_THM_JUMP11:
587 return p + 2 + a;
588 case R_ARM_CALL:
589 case R_ARM_JUMP24:
590 case R_ARM_PC24:
591 case R_ARM_PLT32:
592 case R_ARM_PREL31:
593 case R_ARM_THM_JUMP19:
594 case R_ARM_THM_JUMP24:
595 return p + 4 + a;
596 case R_ARM_THM_CALL:
597 // We don't want an interworking BLX to ARM
598 return p + 5 + a;
599 // Unresolved non branch pc-relative relocations
600 // R_ARM_TARGET2 which can be resolved relatively is not present as it never
601 // targets a weak-reference.
602 case R_ARM_MOVW_PREL_NC:
603 case R_ARM_MOVT_PREL:
604 case R_ARM_REL32:
605 case R_ARM_THM_ALU_PREL_11_0:
606 case R_ARM_THM_MOVW_PREL_NC:
607 case R_ARM_THM_MOVT_PREL:
608 case R_ARM_THM_PC12:
609 return p + a;
610 // p + a is unrepresentable as negative immediates can't be encoded.
611 case R_ARM_THM_PC8:
612 return p;
613 }
614 llvm_unreachable("ARM pc-relative relocation expected\n");
615}
616
617// The comment above getARMUndefinedRelativeWeakVA applies to this function.
618static uint64_t getAArch64UndefinedRelativeWeakVA(uint64_t type, uint64_t p) {
619 switch (type) {
620 // Unresolved branch relocations to weak references resolve to next
621 // instruction, this is 4 bytes on from P.
622 case R_AARCH64_CALL26:
623 case R_AARCH64_CONDBR19:
624 case R_AARCH64_JUMP26:
625 case R_AARCH64_TSTBR14:
626 return p + 4;
627 // Unresolved non branch pc-relative relocations
628 case R_AARCH64_PREL16:
629 case R_AARCH64_PREL32:
630 case R_AARCH64_PREL64:
631 case R_AARCH64_ADR_PREL_LO21:
632 case R_AARCH64_LD_PREL_LO19:
633 case R_AARCH64_PLT32:
634 return p;
635 }
636 llvm_unreachable("AArch64 pc-relative relocation expected\n");
637}
638
639static uint64_t getRISCVUndefinedRelativeWeakVA(uint64_t type, uint64_t p) {
640 switch (type) {
641 case R_RISCV_BRANCH:
642 case R_RISCV_JAL:
643 case R_RISCV_CALL:
644 case R_RISCV_CALL_PLT:
645 case R_RISCV_RVC_BRANCH:
646 case R_RISCV_RVC_JUMP:
647 case R_RISCV_PLT32:
648 return p;
649 default:
650 return 0;
651 }
652}
653
654// ARM SBREL relocations are of the form S + A - B where B is the static base
655// The ARM ABI defines base to be "addressing origin of the output segment
656// defining the symbol S". We defined the "addressing origin"/static base to be
657// the base of the PT_LOAD segment containing the Sym.
658// The procedure call standard only defines a Read Write Position Independent
659// RWPI variant so in practice we should expect the static base to be the base
660// of the RW segment.
661static uint64_t getARMStaticBase(const Symbol &sym) {
662 OutputSection *os = sym.getOutputSection();
663 if (!os || !os->ptLoad || !os->ptLoad->firstSec) {
664 Err(ctx&: os->ctx) << "SBREL relocation to " << sym.getName()
665 << " without static base";
666 return 0;
667 }
668 return os->ptLoad->firstSec->addr;
669}
670
671struct RISCVPCRel {
672 static constexpr const char *loReloc = "R_RISCV_PCREL_LO12";
673 static constexpr const char *hiReloc = "R_RISCV_PCREL_HI20";
674
675 static bool isHiReloc(uint32_t type) {
676 return is_contained(Set: {R_RISCV_PCREL_HI20, R_RISCV_GOT_HI20,
677 R_RISCV_TLS_GD_HI20, R_RISCV_TLS_GOT_HI20},
678 Element: type);
679 }
680};
681
682struct LoongArchPCAdd {
683 static constexpr const char *loReloc = "R_LARCH_*PCADD_LO12";
684 static constexpr const char *hiReloc = "R_LARCH_*PCADD_HI20";
685
686 static bool isHiReloc(uint32_t type) {
687 return is_contained(Set: {R_LARCH_PCADD_HI20, R_LARCH_GOT_PCADD_HI20,
688 R_LARCH_TLS_IE_PCADD_HI20, R_LARCH_TLS_LD_PCADD_HI20,
689 R_LARCH_TLS_GD_PCADD_HI20,
690 R_LARCH_TLS_DESC_PCADD_HI20},
691 Element: type);
692 }
693};
694
695// For PC-relative indirect relocations (e.g. R_RISCV_PCREL_LO12_* and
696// R_LARCH_*PCADD_LO12), the symbol referenced by the LO12 relocation does not
697// directly represent the final target address. Instead, it points to the
698// corresponding HI20 relocation, and the target VA is computed using the
699// symbol associated with that HI20 relocation.
700//
701// This helper locates and returns the matching HI20 relocation corresponding
702// to a given LO12 relocation.
703template <typename PCRel>
704static Relocation *getPCRelHi20(Ctx &ctx, const InputSectionBase *loSec,
705 const Relocation &loReloc) {
706 int64_t addend = loReloc.addend;
707 Symbol *sym = loReloc.sym;
708
709 const Defined *d = dyn_cast<Defined>(Val: sym);
710 if (!d) {
711 Err(ctx) << loSec->getLocation(offset: loReloc.offset)
712 << " points to undefined symbol";
713 return nullptr;
714 }
715 if (!d->section) {
716 Err(ctx) << loSec->getLocation(offset: loReloc.offset) << ": " << PCRel::loReloc
717 << " relocation points to an absolute symbol: " << sym->getName();
718 return nullptr;
719 }
720 InputSection *hiSec = cast<InputSection>(Val: d->section);
721
722 if (hiSec != loSec) {
723 Err(ctx) << loSec->getLocation(offset: loReloc.offset) << ": " << PCRel::loReloc
724 << " relocation points to a symbol '" << sym->getName()
725 << "' in a different section '" << hiSec->name << "'";
726 return nullptr;
727 }
728
729 if (addend != 0)
730 Warn(ctx) << loSec->getLocation(offset: loReloc.offset) << ": non-zero addend in "
731 << PCRel::loReloc << " relocation to "
732 << hiSec->getObjMsg(offset: d->value) << " is ignored";
733
734 // Relocations are sorted by offset, so we can use std::equal_range to do
735 // binary search.
736 Relocation hiReloc;
737 hiReloc.offset = d->value + addend;
738 auto range =
739 std::equal_range(hiSec->relocs().begin(), hiSec->relocs().end(), hiReloc,
740 [](const Relocation &lhs, const Relocation &rhs) {
741 return lhs.offset < rhs.offset;
742 });
743
744 for (auto it = range.first; it != range.second; ++it)
745 if (PCRel::isHiReloc(it->type))
746 return &*it;
747
748 Err(ctx) << loSec->getLocation(offset: loReloc.offset) << ": " << PCRel::loReloc
749 << " relocation points to " << hiSec->getObjMsg(offset: d->value)
750 << " without an associated " << PCRel::hiReloc << " relocation";
751 return nullptr;
752}
753
754// A TLS symbol's virtual address is relative to the TLS segment. Add a
755// target-specific adjustment to produce a thread-pointer-relative offset.
756static int64_t getTlsTpOffset(Ctx &ctx, const Symbol &s) {
757 // On targets that support TLSDESC, _TLS_MODULE_BASE_@tpoff = 0.
758 if (&s == ctx.sym.tlsModuleBase)
759 return 0;
760
761 // There are 2 TLS layouts. Among targets we support, x86 uses TLS Variant 2
762 // while most others use Variant 1. At run time TP will be aligned to p_align.
763
764 // Variant 1. TP will be followed by an optional gap (which is the size of 2
765 // pointers on ARM/AArch64, 0 on other targets), followed by alignment
766 // padding, then the static TLS blocks. The alignment padding is added so that
767 // (TP + gap + padding) is congruent to p_vaddr modulo p_align.
768 //
769 // Variant 2. Static TLS blocks, followed by alignment padding are placed
770 // before TP. The alignment padding is added so that (TP - padding -
771 // p_memsz) is congruent to p_vaddr modulo p_align.
772 PhdrEntry *tls = ctx.tlsPhdr;
773 if (!tls) // Reported an error in getSymVA
774 return 0;
775 switch (ctx.arg.emachine) {
776 // Variant 1.
777 case EM_ARM:
778 case EM_AARCH64:
779 return s.getVA(ctx, addend: 0) + ctx.arg.wordsize * 2 +
780 ((tls->p_vaddr - ctx.arg.wordsize * 2) & (tls->p_align - 1));
781 case EM_MIPS:
782 case EM_PPC:
783 case EM_PPC64:
784 // Adjusted Variant 1. TP is placed with a displacement of 0x7000, which is
785 // to allow a signed 16-bit offset to reach 0x1000 of TCB/thread-library
786 // data and 0xf000 of the program's TLS segment.
787 return s.getVA(ctx, addend: 0) + (tls->p_vaddr & (tls->p_align - 1)) - 0x7000;
788 case EM_LOONGARCH:
789 case EM_RISCV:
790 // For TLSDESC=>IE, R_RISCV_TLSDESC_{LOAD_LO12,ADD_LO12_I,CALL} reference
791 // a non-TLS label and reach here.
792 if (s.type != STT_TLS)
793 return 0;
794 return s.getVA(ctx, addend: 0) + (tls->p_vaddr & (tls->p_align - 1));
795
796 // Variant 2.
797 case EM_HEXAGON:
798 case EM_S390:
799 case EM_SPARCV9:
800 case EM_386:
801 case EM_X86_64:
802 return s.getVA(ctx, addend: 0) - tls->p_memsz -
803 ((-tls->p_vaddr - tls->p_memsz) & (tls->p_align - 1));
804 default:
805 llvm_unreachable("unhandled ctx.arg.emachine");
806 }
807}
808
809uint64_t InputSectionBase::getRelocTargetVA(Ctx &ctx, const Relocation &r,
810 uint64_t p) const {
811 int64_t a = r.addend;
812 switch (r.expr) {
813 case R_ABS:
814 case R_DTPREL:
815 case R_RELAX_GOT_PC_NOPIC:
816 case RE_AARCH64_AUTH:
817 case RE_RISCV_ADD:
818 case RE_RISCV_LEB128:
819 return r.sym->getVA(ctx, addend: a);
820 case R_ADDEND:
821 return a;
822 case R_ADDEND_NEG:
823 return -static_cast<uint64_t>(a);
824 case R_RELAX_HINT:
825 return 0;
826 case RE_ARM_SBREL:
827 return r.sym->getVA(ctx, addend: a) - getARMStaticBase(sym: *r.sym);
828 case R_GOT:
829 return r.sym->getGotVA(ctx) + a;
830 case RE_LOONGARCH_GOT:
831 // The LoongArch TLS GD relocs reuse the R_LARCH_GOT_PC_LO12 reloc r.type
832 // for their page offsets. The arithmetics are different in the TLS case
833 // so we have to duplicate some logic here.
834 if (r.sym->hasFlag(bit: NEEDS_TLSGD) && r.type != R_LARCH_TLS_IE_PC_LO12)
835 // Like RE_LOONGARCH_TLSGD_PAGE_PC but taking the absolute value.
836 return ctx.in.got->getGlobalDynAddr(b: *r.sym) + a;
837 return r.sym->getGotVA(ctx) + a;
838 case R_GOTONLY_PC:
839 return ctx.in.got->getVA() + a - p;
840 case R_GOTPLTONLY_PC:
841 return ctx.in.gotPlt->getVA() + a - p;
842 case R_GOTREL:
843 return r.sym->getVA(ctx, addend: a) - ctx.in.got->getVA();
844 case R_GOTPLTREL:
845 return r.sym->getVA(ctx, addend: a) - ctx.in.gotPlt->getVA();
846 case R_GOTPLT:
847 return r.sym->getGotVA(ctx) + a - ctx.in.gotPlt->getVA();
848 case R_TLSLD_GOT_OFF:
849 case R_GOT_OFF:
850 return r.sym->getGotOffset(ctx) + a;
851 case RE_AARCH64_GOT_PAGE_PC:
852 return getAArch64Page(expr: r.sym->getGotVA(ctx) + a) - getAArch64Page(expr: p);
853 case RE_AARCH64_GOT_PAGE:
854 return r.sym->getGotVA(ctx) + a - getAArch64Page(expr: ctx.in.got->getVA());
855 case R_GOT_PC:
856 return r.sym->getGotVA(ctx) + a - p;
857 case R_GOTPLT_GOTREL:
858 return r.sym->getGotPltVA(ctx) + a - ctx.in.got->getVA();
859 case R_GOTPLT_PC:
860 return r.sym->getGotPltVA(ctx) + a - p;
861 case RE_LOONGARCH_GOT_PAGE_PC:
862 if (r.sym->hasFlag(bit: NEEDS_TLSGD))
863 return getLoongArchPageDelta(dest: ctx.in.got->getGlobalDynAddr(b: *r.sym) + a, pc: p,
864 type: r.type);
865 return getLoongArchPageDelta(dest: r.sym->getGotVA(ctx) + a, pc: p, type: r.type);
866 case RE_MIPS_GOTREL:
867 return r.sym->getVA(ctx, addend: a) - ctx.in.mipsGot->getGp(f: file);
868 case RE_MIPS_GOT_GP:
869 return ctx.in.mipsGot->getGp(f: file) + a;
870 case RE_MIPS_GOT_GP_PC: {
871 // R_MIPS_LO16 expression has RE_MIPS_GOT_GP_PC r.type iif the target
872 // is _gp_disp symbol. In that case we should use the following
873 // formula for calculation "AHL + GP - P + 4". For details see p. 4-19 at
874 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
875 // microMIPS variants of these relocations use slightly different
876 // expressions: AHL + GP - P + 3 for %lo() and AHL + GP - P - 1 for %hi()
877 // to correctly handle less-significant bit of the microMIPS symbol.
878 uint64_t v = ctx.in.mipsGot->getGp(f: file) + a - p;
879 if (r.type == R_MIPS_LO16 || r.type == R_MICROMIPS_LO16)
880 v += 4;
881 if (r.type == R_MICROMIPS_LO16 || r.type == R_MICROMIPS_HI16)
882 v -= 1;
883 return v;
884 }
885 case RE_MIPS_GOT_LOCAL_PAGE:
886 // If relocation against MIPS local symbol requires GOT entry, this entry
887 // should be initialized by 'page address'. This address is high 16-bits
888 // of sum the symbol's value and the addend.
889 return ctx.in.mipsGot->getVA() +
890 ctx.in.mipsGot->getPageEntryOffset(f: file, s: *r.sym, addend: a) -
891 ctx.in.mipsGot->getGp(f: file);
892 case RE_MIPS_OSEC_LOCAL_PAGE:
893 // This is used by the MIPS multi-GOT implementation. It relocates
894 // addresses of 64kb pages that lie inside the output section that sym is
895 // a representative for.
896 return getMipsPageAddr(addr: r.sym->getOutputSection()->addr) + a;
897 case RE_MIPS_GOT_OFF:
898 case RE_MIPS_GOT_OFF32:
899 // In case of MIPS if a GOT relocation has non-zero addend this addend
900 // should be applied to the GOT entry content not to the GOT entry offset.
901 // That is why we use separate expression r.type.
902 return ctx.in.mipsGot->getVA() +
903 ctx.in.mipsGot->getSymEntryOffset(f: file, s: *r.sym, addend: a) -
904 ctx.in.mipsGot->getGp(f: file);
905 case RE_MIPS_TLSGD:
906 return ctx.in.mipsGot->getVA() +
907 ctx.in.mipsGot->getGlobalDynOffset(f: file, s: *r.sym) -
908 ctx.in.mipsGot->getGp(f: file);
909 case RE_MIPS_TLSLD:
910 return ctx.in.mipsGot->getVA() + ctx.in.mipsGot->getTlsIndexOffset(f: file) -
911 ctx.in.mipsGot->getGp(f: file);
912 case RE_AARCH64_PAGE_PC: {
913 uint64_t val = r.sym->isUndefWeak() ? p + a : r.sym->getVA(ctx, addend: a);
914 return getAArch64Page(expr: val) - getAArch64Page(expr: p);
915 }
916 case RE_RISCV_PC_INDIRECT: {
917 if (const Relocation *hiRel = getPCRelHi20<RISCVPCRel>(ctx, loSec: this, loReloc: r))
918 return getRelocTargetVA(ctx, r: *hiRel, p: r.sym->getVA(ctx));
919 return 0;
920 }
921 case RE_LOONGARCH_PC_INDIRECT: {
922 if (const Relocation *hiRel = getPCRelHi20<LoongArchPCAdd>(ctx, loSec: this, loReloc: r))
923 return getRelocTargetVA(ctx, r: *hiRel, p: r.sym->getVA(ctx, addend: a));
924 return 0;
925 }
926 case RE_LOONGARCH_PAGE_PC:
927 return getLoongArchPageDelta(dest: r.sym->getVA(ctx, addend: a), pc: p, type: r.type);
928 case R_PC:
929 case RE_ARM_PCA: {
930 uint64_t dest;
931 if (r.expr == RE_ARM_PCA)
932 // Some PC relative ARM (Thumb) relocations align down the place.
933 p = p & 0xfffffffc;
934 if (r.sym->isUndefined()) {
935 // On ARM and AArch64 a branch to an undefined weak resolves to the next
936 // instruction, otherwise the place. On RISC-V, resolve an undefined weak
937 // to the same instruction to cause an infinite loop (making the user
938 // aware of the issue) while ensuring no overflow.
939 // Note: if the symbol is hidden, its binding has been converted to local,
940 // so we just check isUndefined() here.
941 if (ctx.arg.emachine == EM_ARM)
942 dest = getARMUndefinedRelativeWeakVA(type: r.type, a, p);
943 else if (ctx.arg.emachine == EM_AARCH64)
944 dest = getAArch64UndefinedRelativeWeakVA(type: r.type, p) + a;
945 else if (ctx.arg.emachine == EM_PPC)
946 dest = p;
947 else if (ctx.arg.emachine == EM_RISCV)
948 dest = getRISCVUndefinedRelativeWeakVA(type: r.type, p) + a;
949 else
950 dest = r.sym->getVA(ctx, addend: a);
951 } else {
952 dest = r.sym->getVA(ctx, addend: a);
953 }
954 return dest - p;
955 }
956 case R_PLT:
957 return r.sym->getPltVA(ctx) + a;
958 case R_PLT_PC:
959 case RE_PPC64_CALL_PLT:
960 return r.sym->getPltVA(ctx) + a - p;
961 case RE_LOONGARCH_PLT_PAGE_PC:
962 return getLoongArchPageDelta(dest: r.sym->getPltVA(ctx) + a, pc: p, type: r.type);
963 case R_PLT_GOTPLT:
964 return r.sym->getPltVA(ctx) + a - ctx.in.gotPlt->getVA();
965 case R_PLT_GOTREL:
966 return r.sym->getPltVA(ctx) + a - ctx.in.got->getVA();
967 case RE_PPC32_PLTREL:
968 // R_PPC_PLTREL24 uses the addend (usually 0 or 0x8000) to indicate r30
969 // stores _GLOBAL_OFFSET_TABLE_ or .got2+0x8000. The addend is ignored for
970 // target VA computation.
971 return r.sym->getPltVA(ctx) - p;
972 case RE_PPC64_CALL: {
973 uint64_t symVA = r.sym->getVA(ctx, addend: a);
974 // If we have an undefined weak symbol, we might get here with a symbol
975 // address of zero. That could overflow, but the code must be unreachable,
976 // so don't bother doing anything at all.
977 if (!symVA)
978 return 0;
979
980 // PPC64 V2 ABI describes two entry points to a function. The global entry
981 // point is used for calls where the caller and callee (may) have different
982 // TOC base pointers and r2 needs to be modified to hold the TOC base for
983 // the callee. For local calls the caller and callee share the same
984 // TOC base and so the TOC pointer initialization code should be skipped by
985 // branching to the local entry point.
986 return symVA - p +
987 getPPC64GlobalEntryToLocalEntryOffset(ctx, stOther: r.sym->stOther);
988 }
989 case RE_PPC64_TOCBASE:
990 return getPPC64TocBase(ctx) + a;
991 case R_RELAX_GOT_PC:
992 return r.sym->getVA(ctx, addend: a) - p;
993 case R_TPREL:
994 // It is not very clear what to return if the symbol is undefined. With
995 // --noinhibit-exec, even a non-weak undefined reference may reach here.
996 // Just return A, which matches R_ABS, and the behavior of some dynamic
997 // loaders.
998 if (r.sym->isUndefined())
999 return a;
1000 return getTlsTpOffset(ctx, s: *r.sym) + a;
1001 case R_TPREL_NEG:
1002 if (r.sym->isUndefined())
1003 return a;
1004 return -getTlsTpOffset(ctx, s: *r.sym) + a;
1005 case R_SIZE:
1006 return r.sym->getSize() + a;
1007 case R_TLSDESC:
1008 return ctx.in.got->getTlsDescAddr(sym: *r.sym) + a;
1009 case R_TLSDESC_PC:
1010 return ctx.in.got->getTlsDescAddr(sym: *r.sym) + a - p;
1011 case R_TLSDESC_GOTPLT:
1012 return ctx.in.got->getTlsDescAddr(sym: *r.sym) + a - ctx.in.gotPlt->getVA();
1013 case RE_AARCH64_TLSDESC_PAGE:
1014 return getAArch64Page(expr: ctx.in.got->getTlsDescAddr(sym: *r.sym) + a) -
1015 getAArch64Page(expr: p);
1016 case RE_LOONGARCH_TLSDESC_PAGE_PC:
1017 return getLoongArchPageDelta(dest: ctx.in.got->getTlsDescAddr(sym: *r.sym) + a, pc: p,
1018 type: r.type);
1019 case R_TLSGD_GOT:
1020 return ctx.in.got->getGlobalDynOffset(b: *r.sym) + a;
1021 case R_TLSGD_GOTPLT:
1022 return ctx.in.got->getGlobalDynAddr(b: *r.sym) + a - ctx.in.gotPlt->getVA();
1023 case R_TLSGD_PC:
1024 return ctx.in.got->getGlobalDynAddr(b: *r.sym) + a - p;
1025 case RE_LOONGARCH_TLSGD_PAGE_PC:
1026 return getLoongArchPageDelta(dest: ctx.in.got->getGlobalDynAddr(b: *r.sym) + a, pc: p,
1027 type: r.type);
1028 case R_TLSLD_GOTPLT:
1029 return ctx.in.got->getVA() + ctx.in.got->getTlsIndexOff() + a -
1030 ctx.in.gotPlt->getVA();
1031 case R_TLSLD_GOT:
1032 return ctx.in.got->getTlsIndexOff() + a;
1033 case R_TLSLD_PC:
1034 return ctx.in.got->getTlsIndexVA() + a - p;
1035 default:
1036 llvm_unreachable("invalid expression");
1037 }
1038}
1039
1040// This function applies relocations to sections without SHF_ALLOC bit.
1041// Such sections are never mapped to memory at runtime. Debug sections are
1042// an example. Relocations in non-alloc sections are much easier to
1043// handle than in allocated sections because it will never need complex
1044// treatment such as GOT or PLT (because at runtime no one refers them).
1045// So, we handle relocations for non-alloc sections directly in this
1046// function as a performance optimization.
1047template <class ELFT, class RelTy>
1048void InputSection::relocateNonAlloc(Ctx &ctx, uint8_t *buf,
1049 Relocs<RelTy> rels) {
1050 const unsigned bits = sizeof(typename ELFT::uint) * 8;
1051 const TargetInfo &target = *ctx.target;
1052 const auto emachine = ctx.arg.emachine;
1053 const bool isDebug = isDebugSection(sec: *this);
1054 const bool isDebugLine = isDebug && name == ".debug_line";
1055 std::optional<uint64_t> tombstone;
1056 if (isDebug) {
1057 if (name == ".debug_loc" || name == ".debug_ranges")
1058 tombstone = 1;
1059 else if (name == ".debug_names")
1060 tombstone = UINT64_MAX; // tombstone value
1061 else
1062 tombstone = 0;
1063 }
1064 for (const auto &patAndValue : llvm::reverse(C&: ctx.arg.deadRelocInNonAlloc))
1065 if (patAndValue.first.match(S: this->name)) {
1066 tombstone = patAndValue.second;
1067 break;
1068 }
1069
1070 const InputFile *f = this->file;
1071 for (auto it = rels.begin(), end = rels.end(); it != end; ++it) {
1072 const RelTy &rel = *it;
1073 const RelType type = rel.getType(ctx.arg.isMips64EL);
1074 const uint64_t offset = rel.r_offset;
1075 uint8_t *bufLoc = buf + offset;
1076 int64_t addend = getAddend<ELFT>(rel);
1077 if (!RelTy::HasAddend)
1078 addend += target.getImplicitAddend(buf: bufLoc, type);
1079
1080 Symbol &sym = f->getRelocTargetSym(rel);
1081 RelExpr expr = target.getRelExpr(type, s: sym, loc: bufLoc);
1082 if (expr == R_NONE)
1083 continue;
1084 auto *ds = dyn_cast<Defined>(Val: &sym);
1085
1086 if (emachine == EM_RISCV && type == R_RISCV_SET_ULEB128) {
1087 if (++it != end &&
1088 it->getType(/*isMips64EL=*/false) == R_RISCV_SUB_ULEB128 &&
1089 it->r_offset == offset) {
1090 uint64_t val;
1091 if (!ds && tombstone) {
1092 val = *tombstone;
1093 } else {
1094 val = sym.getVA(ctx, addend) -
1095 (f->getRelocTargetSym(*it).getVA(ctx) + getAddend<ELFT>(*it));
1096 }
1097 if (overwriteULEB128(bufLoc, val) >= 0x80)
1098 Err(ctx) << getLocation(offset) << ": ULEB128 value " << val
1099 << " exceeds available space; references '" << &sym << "'";
1100 continue;
1101 }
1102 Err(ctx) << getLocation(offset)
1103 << ": R_RISCV_SET_ULEB128 not paired with R_RISCV_SUB_ULEB128";
1104 return;
1105 }
1106
1107 if (tombstone && (expr == R_ABS || expr == R_DTPREL)) {
1108 // Resolve relocations in .debug_* referencing (discarded symbols or ICF
1109 // folded section symbols) to a tombstone value. Resolving to addend is
1110 // unsatisfactory because the result address range may collide with a
1111 // valid range of low address, or leave multiple CUs claiming ownership of
1112 // the same range of code, which may confuse consumers.
1113 //
1114 // To address the problems, we use -1 as a tombstone value for most
1115 // .debug_* sections. We have to ignore the addend because we don't want
1116 // to resolve an address attribute (which may have a non-zero addend) to
1117 // -1+addend (wrap around to a low address).
1118 //
1119 // R_DTPREL type relocations represent an offset into the dynamic thread
1120 // vector. The computed value is st_value plus a non-negative offset.
1121 // Negative values are invalid, so -1 can be used as the tombstone value.
1122 //
1123 // If the referenced symbol is relative to a discarded section (due to
1124 // --gc-sections, COMDAT, etc), it has been converted to a Undefined.
1125 // `ds->folded` catches the ICF folded case. However, resolving a
1126 // relocation in .debug_line to -1 would stop debugger users from setting
1127 // breakpoints on the folded-in function, so exclude .debug_line.
1128 //
1129 // For pre-DWARF-v5 .debug_loc and .debug_ranges, -1 is a reserved value
1130 // (base address selection entry), use 1 (which is used by GNU ld for
1131 // .debug_ranges).
1132 //
1133 // TODO To reduce disruption, we use 0 instead of -1 as the tombstone
1134 // value. Enable -1 in a future release.
1135 if (!ds || (ds->folded && !isDebugLine)) {
1136 // If -z dead-reloc-in-nonalloc= is specified, respect it.
1137 uint64_t value = SignExtend64<bits>(*tombstone);
1138 // For a 32-bit local TU reference in .debug_names, X86_64::relocate
1139 // requires that the unsigned value for R_X86_64_32 is truncated to
1140 // 32-bit. Other 64-bit targets's don't discern signed/unsigned 32-bit
1141 // absolute relocations and do not need this change.
1142 if (emachine == EM_X86_64 && type == R_X86_64_32)
1143 value = static_cast<uint32_t>(value);
1144 target.relocateNoSym(loc: bufLoc, type, val: value);
1145 continue;
1146 }
1147 }
1148
1149 // For a relocatable link, content relocated by relocation types with an
1150 // explicit addend, such as RELA, remain unchanged and we can stop here.
1151 // While content relocated by relocation types with an implicit addend, such
1152 // as REL, needs the implicit addend updated.
1153 if (ctx.arg.relocatable && (RelTy::HasAddend || sym.type != STT_SECTION))
1154 continue;
1155
1156 // R_ABS/R_DTPREL and some other relocations can be used from non-SHF_ALLOC
1157 // sections.
1158 if (LLVM_LIKELY(expr == R_ABS) || expr == R_DTPREL || expr == R_GOTPLTREL ||
1159 expr == RE_RISCV_ADD || expr == RE_ARM_SBREL) {
1160 target.relocateNoSym(loc: bufLoc, type,
1161 val: SignExtend64<bits>(sym.getVA(ctx, addend)));
1162 continue;
1163 }
1164
1165 if (expr == R_SIZE) {
1166 target.relocateNoSym(loc: bufLoc, type,
1167 val: SignExtend64<bits>(sym.getSize() + addend));
1168 continue;
1169 }
1170
1171 // If the control reaches here, we found a PC-relative relocation in a
1172 // non-ALLOC section. Since non-ALLOC section is not loaded into memory
1173 // at runtime, the notion of PC-relative doesn't make sense here. So,
1174 // this is a usage error. However, GNU linkers historically accept such
1175 // relocations without any errors and relocate them as if they were at
1176 // address 0. For bug-compatibility, we accept them with warnings. We
1177 // know Steel Bank Common Lisp as of 2018 have this bug.
1178 //
1179 // GCC 8.0 or earlier have a bug that they emit R_386_GOTPC relocations
1180 // against _GLOBAL_OFFSET_TABLE_ for .debug_info. The bug has been fixed in
1181 // 2017 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82630), but we need to
1182 // keep this bug-compatible code for a while.
1183 bool isErr = expr != R_PC && !(emachine == EM_386 && type == R_386_GOTPC);
1184 {
1185 ELFSyncStream diag(ctx, isErr && !ctx.arg.noinhibitExec
1186 ? DiagLevel::Err
1187 : DiagLevel::Warn);
1188 diag << getLocation(offset) << ": has non-ABS relocation " << type
1189 << " against symbol '" << &sym << "'";
1190 }
1191 if (!isErr)
1192 target.relocateNoSym(
1193 loc: bufLoc, type,
1194 val: SignExtend64<bits>(sym.getVA(ctx, addend: addend - offset - outSecOff)));
1195 }
1196}
1197
1198template <class ELFT>
1199void InputSection::relocate(Ctx &ctx, uint8_t *buf, uint8_t *bufEnd) {
1200 if ((flags & SHF_EXECINSTR) && LLVM_UNLIKELY(getFile<ELFT>()->splitStack))
1201 adjustSplitStackFunctionPrologues<ELFT>(ctx, buf, bufEnd);
1202
1203 if (flags & SHF_ALLOC) {
1204 ctx.target->relocateAlloc(sec&: *this, buf);
1205 return;
1206 }
1207
1208 auto *sec = cast<InputSection>(Val: this);
1209 // For a relocatable link, also call relocateNonAlloc() to rewrite applicable
1210 // locations with tombstone values.
1211 invokeOnRelocs(*sec, sec->relocateNonAlloc<ELFT>, ctx, buf);
1212}
1213
1214// For each function-defining prologue, find any calls to __morestack,
1215// and replace them with calls to __morestack_non_split.
1216static void switchMorestackCallsToMorestackNonSplit(
1217 Ctx &ctx, DenseSet<Defined *> &prologues,
1218 SmallVector<Relocation *, 0> &morestackCalls) {
1219
1220 // If the target adjusted a function's prologue, all calls to
1221 // __morestack inside that function should be switched to
1222 // __morestack_non_split.
1223 Symbol *moreStackNonSplit = ctx.symtab->find(name: "__morestack_non_split");
1224 if (!moreStackNonSplit) {
1225 ErrAlways(ctx) << "mixing split-stack objects requires a definition of "
1226 "__morestack_non_split";
1227 return;
1228 }
1229
1230 // Sort both collections to compare addresses efficiently.
1231 llvm::sort(C&: morestackCalls, Comp: [](const Relocation *l, const Relocation *r) {
1232 return l->offset < r->offset;
1233 });
1234 std::vector<Defined *> functions(prologues.begin(), prologues.end());
1235 llvm::sort(C&: functions, Comp: [](const Defined *l, const Defined *r) {
1236 return l->value < r->value;
1237 });
1238
1239 auto it = morestackCalls.begin();
1240 for (Defined *f : functions) {
1241 // Find the first call to __morestack within the function.
1242 while (it != morestackCalls.end() && (*it)->offset < f->value)
1243 ++it;
1244 // Adjust all calls inside the function.
1245 while (it != morestackCalls.end() && (*it)->offset < f->value + f->size) {
1246 (*it)->sym = moreStackNonSplit;
1247 ++it;
1248 }
1249 }
1250}
1251
1252static bool enclosingPrologueAttempted(uint64_t offset,
1253 const DenseSet<Defined *> &prologues) {
1254 for (Defined *f : prologues)
1255 if (f->value <= offset && offset < f->value + f->size)
1256 return true;
1257 return false;
1258}
1259
1260// If a function compiled for split stack calls a function not
1261// compiled for split stack, then the caller needs its prologue
1262// adjusted to ensure that the called function will have enough stack
1263// available. Find those functions, and adjust their prologues.
1264template <class ELFT>
1265void InputSectionBase::adjustSplitStackFunctionPrologues(Ctx &ctx, uint8_t *buf,
1266 uint8_t *end) {
1267 DenseSet<Defined *> prologues;
1268 SmallVector<Relocation *, 0> morestackCalls;
1269
1270 for (Relocation &rel : relocs()) {
1271 // Ignore calls into the split-stack api.
1272 if (rel.sym->getName().starts_with(Prefix: "__morestack")) {
1273 if (rel.sym->getName() == "__morestack")
1274 morestackCalls.push_back(Elt: &rel);
1275 continue;
1276 }
1277
1278 // A relocation to non-function isn't relevant. Sometimes
1279 // __morestack is not marked as a function, so this check comes
1280 // after the name check.
1281 if (rel.sym->type != STT_FUNC)
1282 continue;
1283
1284 // If the callee's-file was compiled with split stack, nothing to do. In
1285 // this context, a "Defined" symbol is one "defined by the binary currently
1286 // being produced". So an "undefined" symbol might be provided by a shared
1287 // library. It is not possible to tell how such symbols were compiled, so be
1288 // conservative.
1289 if (Defined *d = dyn_cast<Defined>(Val: rel.sym))
1290 if (InputSection *isec = cast_or_null<InputSection>(Val: d->section))
1291 if (!isec || !isec->getFile<ELFT>() || isec->getFile<ELFT>()->splitStack)
1292 continue;
1293
1294 if (enclosingPrologueAttempted(offset: rel.offset, prologues))
1295 continue;
1296
1297 if (Defined *f = getEnclosingFunction(offset: rel.offset)) {
1298 prologues.insert(V: f);
1299 if (ctx.target->adjustPrologueForCrossSplitStack(loc: buf + f->value, end,
1300 stOther: f->stOther))
1301 continue;
1302 if (!getFile<ELFT>()->someNoSplitStack)
1303 Err(ctx)
1304 << this << ": " << f->getName() << " (with -fsplit-stack) calls "
1305 << rel.sym->getName()
1306 << " (without -fsplit-stack), but couldn't adjust its prologue";
1307 }
1308 }
1309
1310 if (ctx.target->needsMoreStackNonSplit)
1311 switchMorestackCallsToMorestackNonSplit(ctx, prologues, morestackCalls);
1312}
1313
1314template <class ELFT> void InputSection::writeTo(Ctx &ctx, uint8_t *buf) {
1315 if (LLVM_UNLIKELY(type == SHT_NOBITS))
1316 return;
1317 // If -r or --emit-relocs is given, then an InputSection
1318 // may be a relocation section.
1319 if (LLVM_UNLIKELY(type == SHT_RELA)) {
1320 copyRelocations<ELFT, typename ELFT::Rela>(ctx, buf);
1321 return;
1322 }
1323 if (LLVM_UNLIKELY(type == SHT_REL)) {
1324 copyRelocations<ELFT, typename ELFT::Rel>(ctx, buf);
1325 return;
1326 }
1327
1328 // If -r is given, we may have a SHT_GROUP section.
1329 if (LLVM_UNLIKELY(type == SHT_GROUP)) {
1330 copyShtGroup<ELFT>(buf);
1331 return;
1332 }
1333
1334 // If this is a compressed section, uncompress section contents directly
1335 // to the buffer.
1336 if (compressed) {
1337 auto *hdr = reinterpret_cast<const typename ELFT::Chdr *>(content_);
1338 auto compressed = ArrayRef<uint8_t>(content_, compressedSize)
1339 .slice(N: sizeof(typename ELFT::Chdr));
1340 size_t size = this->size;
1341 if (Error e = hdr->ch_type == ELFCOMPRESS_ZLIB
1342 ? compression::zlib::decompress(Input: compressed, Output: buf, UncompressedSize&: size)
1343 : compression::zstd::decompress(Input: compressed, Output: buf, UncompressedSize&: size))
1344 Err(ctx) << this << ": decompress failed: " << std::move(e);
1345 uint8_t *bufEnd = buf + size;
1346 relocate<ELFT>(ctx, buf, bufEnd);
1347 return;
1348 }
1349
1350 // Copy section contents from source object file to output file
1351 // and then apply relocations.
1352 memcpy(dest: buf, src: content().data(), n: content().size());
1353 relocate<ELFT>(ctx, buf, buf + content().size());
1354}
1355
1356void InputSection::replace(InputSection *other) {
1357 addralign = std::max(a: addralign, b: other->addralign);
1358
1359 other->repl = repl;
1360 other->markDead();
1361}
1362
1363template <class ELFT>
1364EhInputSection::EhInputSection(ObjFile<ELFT> &f,
1365 const typename ELFT::Shdr &header,
1366 StringRef name)
1367 : InputSectionBase(f, header, name, InputSectionBase::EHFrame) {}
1368
1369SyntheticSection *EhInputSection::getParent() const {
1370 return cast_or_null<SyntheticSection>(Val: parent);
1371}
1372
1373// .eh_frame is a sequence of CIE or FDE records.
1374// This function splits an input section into records and returns them.
1375// In rare cases (.eh_frame pieces are reordered by a linker script), the
1376// relocations may be unordered.
1377template <class ELFT> void EhInputSection::split() {
1378 const RelsOrRelas<ELFT> elfRels = relsOrRelas<ELFT>();
1379 if (elfRels.areRelocsCrel())
1380 preprocessRelocs<ELFT>(elfRels.crels);
1381 else if (elfRels.areRelocsRel())
1382 preprocessRelocs<ELFT>(elfRels.rels);
1383 else
1384 preprocessRelocs<ELFT>(elfRels.relas);
1385
1386 // The loop below expects the relocations to be sorted by offset.
1387 auto cmp = [](const Relocation &a, const Relocation &b) {
1388 return a.offset < b.offset;
1389 };
1390 if (!llvm::is_sorted(rels, cmp))
1391 llvm::stable_sort(rels, cmp);
1392
1393 ArrayRef<uint8_t> d = content();
1394 const char *msg = nullptr;
1395 unsigned relI = 0;
1396 while (!d.empty()) {
1397 if (d.size() < 4) {
1398 msg = "CIE/FDE too small";
1399 break;
1400 }
1401 uint64_t size = endian::read32<ELFT::Endianness>(d.data());
1402 if (size == 0) // ZERO terminator
1403 break;
1404 uint32_t id = endian::read32<ELFT::Endianness>(d.data() + 4);
1405 size += 4;
1406 if (LLVM_UNLIKELY(size > d.size())) {
1407 // If it is 0xFFFFFFFF, the next 8 bytes contain the size instead,
1408 // but we do not support that format yet.
1409 msg = size == UINT32_MAX + uint64_t(4)
1410 ? "CIE/FDE too large"
1411 : "CIE/FDE ends past the end of the section";
1412 break;
1413 }
1414
1415 // Find the first relocation that points to [off,off+size). Relocations
1416 // have been sorted by r_offset.
1417 const uint64_t off = d.data() - content().data();
1418 while (relI != rels.size() && rels[relI].offset < off)
1419 ++relI;
1420 unsigned firstRel = -1;
1421 if (relI != rels.size() && rels[relI].offset < off + size)
1422 firstRel = relI;
1423 if (id == 0) {
1424 cies.emplace_back(Args: off, Args&: size, Args&: firstRel, Args: -1);
1425 } else {
1426 auto cieOff = off + 4 - id;
1427 auto it = partition_point(
1428 cies, [=](const EhSectionPiece &p) { return p.inputOff < cieOff; });
1429 if (it == cies.end() || it->inputOff != cieOff) {
1430 msg = "invalid CIE reference";
1431 break;
1432 }
1433 fdes.emplace_back(off, size, firstRel, it - cies.begin());
1434 }
1435 d = d.slice(N: size);
1436 }
1437 if (msg)
1438 Err(ctx&: file->ctx) << "corrupted .eh_frame: " << msg << "\n>>> defined in "
1439 << getObjMsg(offset: d.data() - content().data());
1440}
1441
1442template <class ELFT, class RelTy>
1443void EhInputSection::preprocessRelocs(Relocs<RelTy> elfRels) {
1444 Ctx &ctx = file->ctx;
1445 rels.reserve(N: elfRels.size());
1446 for (auto rel : elfRels) {
1447 uint64_t offset = rel.r_offset;
1448 Symbol &sym = file->getSymbol(symbolIndex: rel.getSymbol(ctx.arg.isMips64EL));
1449 RelType type = rel.getType(ctx.arg.isMips64EL);
1450 RelExpr expr = ctx.target->getRelExpr(type, s: sym, loc: content().data() + offset);
1451 int64_t addend =
1452 RelTy::HasAddend
1453 ? getAddend<ELFT>(rel)
1454 : ctx.target->getImplicitAddend(buf: content().data() + offset, type);
1455 rels.push_back(Elt: {.expr: expr, .type: type, .offset: offset, .addend: addend, .sym: &sym});
1456 }
1457}
1458
1459// Return the offset in an output section for a given input offset.
1460uint64_t EhInputSection::getParentOffset(uint64_t offset) const {
1461 auto it = partition_point(
1462 Range: fdes, P: [=](EhSectionPiece p) { return p.inputOff <= offset; });
1463 if (it == fdes.begin() || it[-1].inputOff + it[-1].size <= offset) {
1464 it = partition_point(
1465 Range: cies, P: [=](EhSectionPiece p) { return p.inputOff <= offset; });
1466 if (it == cies.begin()) // invalid piece
1467 return offset;
1468 }
1469 if (it[-1].outputOff == -1) // invalid piece
1470 return offset - it[-1].inputOff;
1471 return it[-1].outputOff + (offset - it[-1].inputOff);
1472}
1473
1474static size_t findNull(StringRef s, size_t entSize) {
1475 for (unsigned i = 0, n = s.size(); i != n; i += entSize) {
1476 const char *b = s.begin() + i;
1477 if (std::all_of(first: b, last: b + entSize, pred: [](char c) { return c == 0; }))
1478 return i;
1479 }
1480 llvm_unreachable("");
1481}
1482
1483// Split SHF_STRINGS section. Such section is a sequence of
1484// null-terminated strings.
1485void MergeInputSection::splitStrings(StringRef s, size_t entSize) {
1486 const bool live = !(flags & SHF_ALLOC) || !getCtx().arg.gcSections;
1487 const char *p = s.data(), *end = s.data() + s.size();
1488 if (!std::all_of(first: end - entSize, last: end, pred: [](char c) { return c == 0; })) {
1489 Err(ctx&: getCtx()) << this << ": string is not null terminated";
1490 pieces.emplace_back(Args&: entSize, Args: 0, Args: false);
1491 return;
1492 }
1493 if (entSize == 1) {
1494 // Optimize the common case.
1495 do {
1496 size_t size = strlen(s: p);
1497 pieces.emplace_back(Args: p - s.begin(), Args: xxh3_64bits(data: StringRef(p, size)), Args: live);
1498 p += size + 1;
1499 } while (p != end);
1500 } else {
1501 do {
1502 size_t size = findNull(s: StringRef(p, end - p), entSize);
1503 pieces.emplace_back(Args: p - s.begin(), Args: xxh3_64bits(data: StringRef(p, size)), Args: live);
1504 p += size + entSize;
1505 } while (p != end);
1506 }
1507}
1508
1509// Split non-SHF_STRINGS section. Such section is a sequence of
1510// fixed size records.
1511void MergeInputSection::splitNonStrings(ArrayRef<uint8_t> data,
1512 size_t entSize) {
1513 size_t size = data.size();
1514 assert((size % entSize) == 0);
1515 const bool live = !(flags & SHF_ALLOC) || !getCtx().arg.gcSections;
1516
1517 pieces.resize_for_overwrite(N: size / entSize);
1518 for (size_t i = 0, j = 0; i != size; i += entSize, j++)
1519 pieces[j] = {i, (uint32_t)xxh3_64bits(data: data.slice(N: i, M: entSize)), live};
1520}
1521
1522template <class ELFT>
1523MergeInputSection::MergeInputSection(ObjFile<ELFT> &f,
1524 const typename ELFT::Shdr &header,
1525 StringRef name)
1526 : InputSectionBase(f, header, name, InputSectionBase::Merge) {}
1527
1528MergeInputSection::MergeInputSection(Ctx &ctx, StringRef name, uint32_t type,
1529 uint64_t flags, uint64_t entsize,
1530 ArrayRef<uint8_t> data)
1531 : InputSectionBase(ctx.internalFile, name, type, flags, /*link=*/0,
1532 /*info=*/0,
1533 /*addralign=*/entsize, entsize, data,
1534 SectionBase::Merge) {}
1535
1536// This function is called after we obtain a complete list of input sections
1537// that need to be linked. This is responsible to split section contents
1538// into small chunks for further processing.
1539//
1540// Note that this function is called from parallelForEach. This must be
1541// thread-safe (i.e. no memory allocation from the pools).
1542void MergeInputSection::splitIntoPieces() {
1543 assert(pieces.empty());
1544
1545 if (flags & SHF_STRINGS)
1546 splitStrings(s: toStringRef(Input: contentMaybeDecompress()), entSize: entsize);
1547 else
1548 splitNonStrings(data: contentMaybeDecompress(), entSize: entsize);
1549}
1550
1551SectionPiece &MergeInputSection::getSectionPiece(uint64_t offset) {
1552 // Pre-resolved by splitSections: pieceIdx + 1 in upper bits,
1553 // intra-piece offset in lower bits.
1554 if (uint32_t idx = offset >> mergeValueShift)
1555 return pieces[idx - 1];
1556 assert(offset < content().size());
1557 // For non-string fixed-size records, piece index = offset / entsize.
1558 if (!(flags & SHF_STRINGS))
1559 return pieces[offset / entsize];
1560 // Find the last piece whose inputOff <= offset. Prefer a conditional move
1561 // to a mispredicated branch.
1562 SectionPiece *p = pieces.data();
1563 for (size_t n = pieces.size(); n > 1; n -= n / 2)
1564 p = LLVM_UNPREDICTABLE(p[n / 2].inputOff <= offset) ? p + n / 2 : p;
1565 return *p;
1566}
1567
1568// Return the offset in an output section for a given input offset.
1569uint64_t MergeInputSection::getParentOffset(uint64_t offset) const {
1570 // Pre-resolved by splitSections: pieceIdx + 1 in upper bits,
1571 // intra-piece offset in lower bits.
1572 if (uint32_t idx = offset >> mergeValueShift)
1573 return pieces[idx - 1].outputOff +
1574 (offset & llvm::maskTrailingOnes<uint64_t>(N: mergeValueShift));
1575 const SectionPiece &piece = getSectionPiece(offset);
1576 return piece.outputOff + (offset - piece.inputOff);
1577}
1578
1579template InputSection::InputSection(ObjFile<ELF32LE> &, const ELF32LE::Shdr &,
1580 StringRef);
1581template InputSection::InputSection(ObjFile<ELF32BE> &, const ELF32BE::Shdr &,
1582 StringRef);
1583template InputSection::InputSection(ObjFile<ELF64LE> &, const ELF64LE::Shdr &,
1584 StringRef);
1585template InputSection::InputSection(ObjFile<ELF64BE> &, const ELF64BE::Shdr &,
1586 StringRef);
1587
1588template void InputSection::writeTo<ELF32LE>(Ctx &, uint8_t *);
1589template void InputSection::writeTo<ELF32BE>(Ctx &, uint8_t *);
1590template void InputSection::writeTo<ELF64LE>(Ctx &, uint8_t *);
1591template void InputSection::writeTo<ELF64BE>(Ctx &, uint8_t *);
1592
1593template RelsOrRelas<ELF32LE>
1594InputSectionBase::relsOrRelas<ELF32LE>(bool) const;
1595template RelsOrRelas<ELF32BE>
1596InputSectionBase::relsOrRelas<ELF32BE>(bool) const;
1597template RelsOrRelas<ELF64LE>
1598InputSectionBase::relsOrRelas<ELF64LE>(bool) const;
1599template RelsOrRelas<ELF64BE>
1600InputSectionBase::relsOrRelas<ELF64BE>(bool) const;
1601
1602template MergeInputSection::MergeInputSection(ObjFile<ELF32LE> &,
1603 const ELF32LE::Shdr &, StringRef);
1604template MergeInputSection::MergeInputSection(ObjFile<ELF32BE> &,
1605 const ELF32BE::Shdr &, StringRef);
1606template MergeInputSection::MergeInputSection(ObjFile<ELF64LE> &,
1607 const ELF64LE::Shdr &, StringRef);
1608template MergeInputSection::MergeInputSection(ObjFile<ELF64BE> &,
1609 const ELF64BE::Shdr &, StringRef);
1610
1611template EhInputSection::EhInputSection(ObjFile<ELF32LE> &,
1612 const ELF32LE::Shdr &, StringRef);
1613template EhInputSection::EhInputSection(ObjFile<ELF32BE> &,
1614 const ELF32BE::Shdr &, StringRef);
1615template EhInputSection::EhInputSection(ObjFile<ELF64LE> &,
1616 const ELF64LE::Shdr &, StringRef);
1617template EhInputSection::EhInputSection(ObjFile<ELF64BE> &,
1618 const ELF64BE::Shdr &, StringRef);
1619
1620template void EhInputSection::split<ELF32LE>();
1621template void EhInputSection::split<ELF32BE>();
1622template void EhInputSection::split<ELF64LE>();
1623template void EhInputSection::split<ELF64BE>();
1624