Path: blob/main/contrib/llvm-project/lld/ELF/OutputSections.cpp
34869 views
//===- OutputSections.cpp -------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "OutputSections.h"9#include "Config.h"10#include "InputFiles.h"11#include "LinkerScript.h"12#include "Symbols.h"13#include "SyntheticSections.h"14#include "Target.h"15#include "lld/Common/Arrays.h"16#include "lld/Common/Memory.h"17#include "llvm/BinaryFormat/Dwarf.h"18#include "llvm/Config/llvm-config.h" // LLVM_ENABLE_ZLIB19#include "llvm/Support/Compression.h"20#include "llvm/Support/LEB128.h"21#include "llvm/Support/Parallel.h"22#include "llvm/Support/Path.h"23#include "llvm/Support/TimeProfiler.h"24#if LLVM_ENABLE_ZLIB25// Avoid introducing max as a macro from Windows headers.26#define NOMINMAX27#include <zlib.h>28#endif29#if LLVM_ENABLE_ZSTD30#include <zstd.h>31#endif3233using namespace llvm;34using namespace llvm::dwarf;35using namespace llvm::object;36using namespace llvm::support::endian;37using namespace llvm::ELF;38using namespace lld;39using namespace lld::elf;4041uint8_t *Out::bufferStart;42PhdrEntry *Out::tlsPhdr;43OutputSection *Out::elfHeader;44OutputSection *Out::programHeaders;45OutputSection *Out::preinitArray;46OutputSection *Out::initArray;47OutputSection *Out::finiArray;4849SmallVector<OutputSection *, 0> elf::outputSections;5051uint32_t OutputSection::getPhdrFlags() const {52uint32_t ret = 0;53if (config->emachine != EM_ARM || !(flags & SHF_ARM_PURECODE))54ret |= PF_R;55if (flags & SHF_WRITE)56ret |= PF_W;57if (flags & SHF_EXECINSTR)58ret |= PF_X;59return ret;60}6162template <class ELFT>63void OutputSection::writeHeaderTo(typename ELFT::Shdr *shdr) {64shdr->sh_entsize = entsize;65shdr->sh_addralign = addralign;66shdr->sh_type = type;67shdr->sh_offset = offset;68shdr->sh_flags = flags;69shdr->sh_info = info;70shdr->sh_link = link;71shdr->sh_addr = addr;72shdr->sh_size = size;73shdr->sh_name = shName;74}7576OutputSection::OutputSection(StringRef name, uint32_t type, uint64_t flags)77: SectionBase(Output, name, flags, /*Entsize*/ 0, /*Alignment*/ 1, type,78/*Info*/ 0, /*Link*/ 0) {}7980// We allow sections of types listed below to merged into a81// single progbits section. This is typically done by linker82// scripts. Merging nobits and progbits will force disk space83// to be allocated for nobits sections. Other ones don't require84// any special treatment on top of progbits, so there doesn't85// seem to be a harm in merging them.86//87// NOTE: clang since rL252300 emits SHT_X86_64_UNWIND .eh_frame sections. Allow88// them to be merged into SHT_PROGBITS .eh_frame (GNU as .cfi_*).89static bool canMergeToProgbits(unsigned type) {90return type == SHT_NOBITS || type == SHT_PROGBITS || type == SHT_INIT_ARRAY ||91type == SHT_PREINIT_ARRAY || type == SHT_FINI_ARRAY ||92type == SHT_NOTE ||93(type == SHT_X86_64_UNWIND && config->emachine == EM_X86_64);94}9596// Record that isec will be placed in the OutputSection. isec does not become97// permanent until finalizeInputSections() is called. The function should not be98// used after finalizeInputSections() is called. If you need to add an99// InputSection post finalizeInputSections(), then you must do the following:100//101// 1. Find or create an InputSectionDescription to hold InputSection.102// 2. Add the InputSection to the InputSectionDescription::sections.103// 3. Call commitSection(isec).104void OutputSection::recordSection(InputSectionBase *isec) {105partition = isec->partition;106isec->parent = this;107if (commands.empty() || !isa<InputSectionDescription>(commands.back()))108commands.push_back(make<InputSectionDescription>(""));109auto *isd = cast<InputSectionDescription>(commands.back());110isd->sectionBases.push_back(isec);111}112113// Update fields (type, flags, alignment, etc) according to the InputSection114// isec. Also check whether the InputSection flags and type are consistent with115// other InputSections.116void OutputSection::commitSection(InputSection *isec) {117if (LLVM_UNLIKELY(type != isec->type)) {118if (!hasInputSections && !typeIsSet) {119type = isec->type;120} else if (isStaticRelSecType(type) && isStaticRelSecType(isec->type) &&121(type == SHT_CREL) != (isec->type == SHT_CREL)) {122// Combine mixed SHT_REL[A] and SHT_CREL to SHT_CREL.123type = SHT_CREL;124if (type == SHT_REL) {125if (name.consume_front(".rel"))126name = saver().save(".crel" + name);127} else if (name.consume_front(".rela")) {128name = saver().save(".crel" + name);129}130} else {131if (typeIsSet || !canMergeToProgbits(type) ||132!canMergeToProgbits(isec->type)) {133// The (NOLOAD) changes the section type to SHT_NOBITS, the intention is134// that the contents at that address is provided by some other means.135// Some projects (e.g.136// https://github.com/ClangBuiltLinux/linux/issues/1597) rely on the137// behavior. Other types get an error.138if (type != SHT_NOBITS) {139errorOrWarn("section type mismatch for " + isec->name + "\n>>> " +140toString(isec) + ": " +141getELFSectionTypeName(config->emachine, isec->type) +142"\n>>> output section " + name + ": " +143getELFSectionTypeName(config->emachine, type));144}145}146if (!typeIsSet)147type = SHT_PROGBITS;148}149}150if (!hasInputSections) {151// If IS is the first section to be added to this section,152// initialize type, entsize and flags from isec.153hasInputSections = true;154entsize = isec->entsize;155flags = isec->flags;156} else {157// Otherwise, check if new type or flags are compatible with existing ones.158if ((flags ^ isec->flags) & SHF_TLS)159error("incompatible section flags for " + name + "\n>>> " +160toString(isec) + ": 0x" + utohexstr(isec->flags) +161"\n>>> output section " + name + ": 0x" + utohexstr(flags));162}163164isec->parent = this;165uint64_t andMask =166config->emachine == EM_ARM ? (uint64_t)SHF_ARM_PURECODE : 0;167uint64_t orMask = ~andMask;168uint64_t andFlags = (flags & isec->flags) & andMask;169uint64_t orFlags = (flags | isec->flags) & orMask;170flags = andFlags | orFlags;171if (nonAlloc)172flags &= ~(uint64_t)SHF_ALLOC;173174addralign = std::max(addralign, isec->addralign);175176// If this section contains a table of fixed-size entries, sh_entsize177// holds the element size. If it contains elements of different size we178// set sh_entsize to 0.179if (entsize != isec->entsize)180entsize = 0;181}182183static MergeSyntheticSection *createMergeSynthetic(StringRef name,184uint32_t type,185uint64_t flags,186uint32_t addralign) {187if ((flags & SHF_STRINGS) && config->optimize >= 2)188return make<MergeTailSection>(name, type, flags, addralign);189return make<MergeNoTailSection>(name, type, flags, addralign);190}191192// This function scans over the InputSectionBase list sectionBases to create193// InputSectionDescription::sections.194//195// It removes MergeInputSections from the input section array and adds196// new synthetic sections at the location of the first input section197// that it replaces. It then finalizes each synthetic section in order198// to compute an output offset for each piece of each input section.199void OutputSection::finalizeInputSections(LinkerScript *script) {200std::vector<MergeSyntheticSection *> mergeSections;201for (SectionCommand *cmd : commands) {202auto *isd = dyn_cast<InputSectionDescription>(cmd);203if (!isd)204continue;205isd->sections.reserve(isd->sectionBases.size());206for (InputSectionBase *s : isd->sectionBases) {207MergeInputSection *ms = dyn_cast<MergeInputSection>(s);208if (!ms) {209isd->sections.push_back(cast<InputSection>(s));210continue;211}212213// We do not want to handle sections that are not alive, so just remove214// them instead of trying to merge.215if (!ms->isLive())216continue;217218auto i = llvm::find_if(mergeSections, [=](MergeSyntheticSection *sec) {219// While we could create a single synthetic section for two different220// values of Entsize, it is better to take Entsize into consideration.221//222// With a single synthetic section no two pieces with different Entsize223// could be equal, so we may as well have two sections.224//225// Using Entsize in here also allows us to propagate it to the synthetic226// section.227//228// SHF_STRINGS section with different alignments should not be merged.229return sec->flags == ms->flags && sec->entsize == ms->entsize &&230(sec->addralign == ms->addralign || !(sec->flags & SHF_STRINGS));231});232if (i == mergeSections.end()) {233MergeSyntheticSection *syn =234createMergeSynthetic(s->name, ms->type, ms->flags, ms->addralign);235mergeSections.push_back(syn);236i = std::prev(mergeSections.end());237syn->entsize = ms->entsize;238isd->sections.push_back(syn);239// The merge synthetic section inherits the potential spill locations of240// its first contained section.241auto it = script->potentialSpillLists.find(ms);242if (it != script->potentialSpillLists.end())243script->potentialSpillLists.try_emplace(syn, it->second);244}245(*i)->addSection(ms);246}247248// sectionBases should not be used from this point onwards. Clear it to249// catch misuses.250isd->sectionBases.clear();251252// Some input sections may be removed from the list after ICF.253for (InputSection *s : isd->sections)254commitSection(s);255}256for (auto *ms : mergeSections)257ms->finalizeContents();258}259260static void sortByOrder(MutableArrayRef<InputSection *> in,261llvm::function_ref<int(InputSectionBase *s)> order) {262std::vector<std::pair<int, InputSection *>> v;263for (InputSection *s : in)264v.emplace_back(order(s), s);265llvm::stable_sort(v, less_first());266267for (size_t i = 0; i < v.size(); ++i)268in[i] = v[i].second;269}270271uint64_t elf::getHeaderSize() {272if (config->oFormatBinary)273return 0;274return Out::elfHeader->size + Out::programHeaders->size;275}276277void OutputSection::sort(llvm::function_ref<int(InputSectionBase *s)> order) {278assert(isLive());279for (SectionCommand *b : commands)280if (auto *isd = dyn_cast<InputSectionDescription>(b))281sortByOrder(isd->sections, order);282}283284static void nopInstrFill(uint8_t *buf, size_t size) {285if (size == 0)286return;287unsigned i = 0;288if (size == 0)289return;290std::vector<std::vector<uint8_t>> nopFiller = *target->nopInstrs;291unsigned num = size / nopFiller.back().size();292for (unsigned c = 0; c < num; ++c) {293memcpy(buf + i, nopFiller.back().data(), nopFiller.back().size());294i += nopFiller.back().size();295}296unsigned remaining = size - i;297if (!remaining)298return;299assert(nopFiller[remaining - 1].size() == remaining);300memcpy(buf + i, nopFiller[remaining - 1].data(), remaining);301}302303// Fill [Buf, Buf + Size) with Filler.304// This is used for linker script "=fillexp" command.305static void fill(uint8_t *buf, size_t size,306const std::array<uint8_t, 4> &filler) {307size_t i = 0;308for (; i + 4 < size; i += 4)309memcpy(buf + i, filler.data(), 4);310memcpy(buf + i, filler.data(), size - i);311}312313#if LLVM_ENABLE_ZLIB314static SmallVector<uint8_t, 0> deflateShard(ArrayRef<uint8_t> in, int level,315int flush) {316// 15 and 8 are default. windowBits=-15 is negative to generate raw deflate317// data with no zlib header or trailer.318z_stream s = {};319auto res = deflateInit2(&s, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY);320if (res != 0) {321errorOrWarn("--compress-sections: deflateInit2 returned " + Twine(res));322return {};323}324s.next_in = const_cast<uint8_t *>(in.data());325s.avail_in = in.size();326327// Allocate a buffer of half of the input size, and grow it by 1.5x if328// insufficient.329SmallVector<uint8_t, 0> out;330size_t pos = 0;331out.resize_for_overwrite(std::max<size_t>(in.size() / 2, 64));332do {333if (pos == out.size())334out.resize_for_overwrite(out.size() * 3 / 2);335s.next_out = out.data() + pos;336s.avail_out = out.size() - pos;337(void)deflate(&s, flush);338pos = s.next_out - out.data();339} while (s.avail_out == 0);340assert(s.avail_in == 0);341342out.truncate(pos);343deflateEnd(&s);344return out;345}346#endif347348// Compress certain non-SHF_ALLOC sections:349//350// * (if --compress-debug-sections is specified) non-empty .debug_* sections351// * (if --compress-sections is specified) matched sections352template <class ELFT> void OutputSection::maybeCompress() {353using Elf_Chdr = typename ELFT::Chdr;354(void)sizeof(Elf_Chdr);355356DebugCompressionType ctype = DebugCompressionType::None;357size_t compressedSize = sizeof(Elf_Chdr);358unsigned level = 0; // default compression level359if (!(flags & SHF_ALLOC) && config->compressDebugSections &&360name.starts_with(".debug_"))361ctype = *config->compressDebugSections;362for (auto &[glob, t, l] : config->compressSections)363if (glob.match(name))364std::tie(ctype, level) = {t, l};365if (ctype == DebugCompressionType::None)366return;367if (flags & SHF_ALLOC) {368errorOrWarn("--compress-sections: section '" + name +369"' with the SHF_ALLOC flag cannot be compressed");370return;371}372373llvm::TimeTraceScope timeScope("Compress sections");374auto buf = std::make_unique<uint8_t[]>(size);375// Write uncompressed data to a temporary zero-initialized buffer.376{377parallel::TaskGroup tg;378writeTo<ELFT>(buf.get(), tg);379}380// The generic ABI specifies "The sh_size and sh_addralign fields of the381// section header for a compressed section reflect the requirements of the382// compressed section." However, 1-byte alignment has been wildly accepted383// and utilized for a long time. Removing alignment padding is particularly384// useful when there are many compressed output sections.385addralign = 1;386387// Split input into 1-MiB shards.388[[maybe_unused]] constexpr size_t shardSize = 1 << 20;389auto shardsIn = split(ArrayRef<uint8_t>(buf.get(), size), shardSize);390const size_t numShards = shardsIn.size();391auto shardsOut = std::make_unique<SmallVector<uint8_t, 0>[]>(numShards);392393#if LLVM_ENABLE_ZSTD394// Use ZSTD's streaming compression API. See395// http://facebook.github.io/zstd/zstd_manual.html "Streaming compression -396// HowTo".397if (ctype == DebugCompressionType::Zstd) {398parallelFor(0, numShards, [&](size_t i) {399SmallVector<uint8_t, 0> out;400ZSTD_CCtx *cctx = ZSTD_createCCtx();401ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, level);402ZSTD_inBuffer zib = {shardsIn[i].data(), shardsIn[i].size(), 0};403ZSTD_outBuffer zob = {nullptr, 0, 0};404size_t size;405do {406// Allocate a buffer of half of the input size, and grow it by 1.5x if407// insufficient.408if (zob.pos == zob.size) {409out.resize_for_overwrite(410zob.size ? zob.size * 3 / 2 : std::max<size_t>(zib.size / 4, 64));411zob = {out.data(), out.size(), zob.pos};412}413size = ZSTD_compressStream2(cctx, &zob, &zib, ZSTD_e_end);414assert(!ZSTD_isError(size));415} while (size != 0);416out.truncate(zob.pos);417ZSTD_freeCCtx(cctx);418shardsOut[i] = std::move(out);419});420compressed.type = ELFCOMPRESS_ZSTD;421for (size_t i = 0; i != numShards; ++i)422compressedSize += shardsOut[i].size();423}424#endif425426#if LLVM_ENABLE_ZLIB427// We chose 1 (Z_BEST_SPEED) as the default compression level because it is428// fast and provides decent compression ratios.429if (ctype == DebugCompressionType::Zlib) {430if (!level)431level = Z_BEST_SPEED;432433// Compress shards and compute Alder-32 checksums. Use Z_SYNC_FLUSH for all434// shards but the last to flush the output to a byte boundary to be435// concatenated with the next shard.436auto shardsAdler = std::make_unique<uint32_t[]>(numShards);437parallelFor(0, numShards, [&](size_t i) {438shardsOut[i] = deflateShard(shardsIn[i], level,439i != numShards - 1 ? Z_SYNC_FLUSH : Z_FINISH);440shardsAdler[i] = adler32(1, shardsIn[i].data(), shardsIn[i].size());441});442443// Update section size and combine Alder-32 checksums.444uint32_t checksum = 1; // Initial Adler-32 value445compressedSize += 2; // Elf_Chdir and zlib header446for (size_t i = 0; i != numShards; ++i) {447compressedSize += shardsOut[i].size();448checksum = adler32_combine(checksum, shardsAdler[i], shardsIn[i].size());449}450compressedSize += 4; // checksum451compressed.type = ELFCOMPRESS_ZLIB;452compressed.checksum = checksum;453}454#endif455456if (compressedSize >= size)457return;458compressed.uncompressedSize = size;459compressed.shards = std::move(shardsOut);460compressed.numShards = numShards;461size = compressedSize;462flags |= SHF_COMPRESSED;463}464465static void writeInt(uint8_t *buf, uint64_t data, uint64_t size) {466if (size == 1)467*buf = data;468else if (size == 2)469write16(buf, data);470else if (size == 4)471write32(buf, data);472else if (size == 8)473write64(buf, data);474else475llvm_unreachable("unsupported Size argument");476}477478template <class ELFT>479void OutputSection::writeTo(uint8_t *buf, parallel::TaskGroup &tg) {480llvm::TimeTraceScope timeScope("Write sections", name);481if (type == SHT_NOBITS)482return;483if (type == SHT_CREL && !(flags & SHF_ALLOC)) {484buf += encodeULEB128(crelHeader, buf);485memcpy(buf, crelBody.data(), crelBody.size());486return;487}488489// If the section is compressed due to490// --compress-debug-section/--compress-sections, the content is already known.491if (compressed.shards) {492auto *chdr = reinterpret_cast<typename ELFT::Chdr *>(buf);493chdr->ch_type = compressed.type;494chdr->ch_size = compressed.uncompressedSize;495chdr->ch_addralign = addralign;496buf += sizeof(*chdr);497498auto offsets = std::make_unique<size_t[]>(compressed.numShards);499if (compressed.type == ELFCOMPRESS_ZLIB) {500buf[0] = 0x78; // CMF501buf[1] = 0x01; // FLG: best speed502offsets[0] = 2; // zlib header503write32be(buf + (size - sizeof(*chdr) - 4), compressed.checksum);504}505506// Compute shard offsets.507for (size_t i = 1; i != compressed.numShards; ++i)508offsets[i] = offsets[i - 1] + compressed.shards[i - 1].size();509parallelFor(0, compressed.numShards, [&](size_t i) {510memcpy(buf + offsets[i], compressed.shards[i].data(),511compressed.shards[i].size());512});513return;514}515516// Write leading padding.517ArrayRef<InputSection *> sections = getInputSections(*this, storage);518std::array<uint8_t, 4> filler = getFiller();519bool nonZeroFiller = read32(filler.data()) != 0;520if (nonZeroFiller)521fill(buf, sections.empty() ? size : sections[0]->outSecOff, filler);522523if (type == SHT_CREL && !(flags & SHF_ALLOC)) {524buf += encodeULEB128(crelHeader, buf);525memcpy(buf, crelBody.data(), crelBody.size());526return;527}528529auto fn = [=](size_t begin, size_t end) {530size_t numSections = sections.size();531for (size_t i = begin; i != end; ++i) {532InputSection *isec = sections[i];533if (auto *s = dyn_cast<SyntheticSection>(isec))534s->writeTo(buf + isec->outSecOff);535else536isec->writeTo<ELFT>(buf + isec->outSecOff);537538// When in Arm BE8 mode, the linker has to convert the big-endian539// instructions to little-endian, leaving the data big-endian.540if (config->emachine == EM_ARM && !config->isLE && config->armBe8 &&541(flags & SHF_EXECINSTR))542convertArmInstructionstoBE8(isec, buf + isec->outSecOff);543544// Fill gaps between sections.545if (nonZeroFiller) {546uint8_t *start = buf + isec->outSecOff + isec->getSize();547uint8_t *end;548if (i + 1 == numSections)549end = buf + size;550else551end = buf + sections[i + 1]->outSecOff;552if (isec->nopFiller) {553assert(target->nopInstrs);554nopInstrFill(start, end - start);555} else556fill(start, end - start, filler);557}558}559};560561// If there is any BYTE()-family command (rare), write the section content562// first then process BYTE to overwrite the filler content. The write is563// serial due to the limitation of llvm/Support/Parallel.h.564bool written = false;565size_t numSections = sections.size();566for (SectionCommand *cmd : commands)567if (auto *data = dyn_cast<ByteCommand>(cmd)) {568if (!std::exchange(written, true))569fn(0, numSections);570writeInt(buf + data->offset, data->expression().getValue(), data->size);571}572if (written || !numSections)573return;574575// There is no data command. Write content asynchronously to overlap the write576// time with other output sections. Note, if a linker script specifies577// overlapping output sections (needs --noinhibit-exec or --no-check-sections578// to supress the error), the output may be non-deterministic.579const size_t taskSizeLimit = 4 << 20;580for (size_t begin = 0, i = 0, taskSize = 0;;) {581taskSize += sections[i]->getSize();582bool done = ++i == numSections;583if (done || taskSize >= taskSizeLimit) {584tg.spawn([=] { fn(begin, i); });585if (done)586break;587begin = i;588taskSize = 0;589}590}591}592593static void finalizeShtGroup(OutputSection *os, InputSection *section) {594// sh_link field for SHT_GROUP sections should contain the section index of595// the symbol table.596os->link = in.symTab->getParent()->sectionIndex;597598if (!section)599return;600601// sh_info then contain index of an entry in symbol table section which602// provides signature of the section group.603ArrayRef<Symbol *> symbols = section->file->getSymbols();604os->info = in.symTab->getSymbolIndex(*symbols[section->info]);605606// Some group members may be combined or discarded, so we need to compute the607// new size. The content will be rewritten in InputSection::copyShtGroup.608DenseSet<uint32_t> seen;609ArrayRef<InputSectionBase *> sections = section->file->getSections();610for (const uint32_t &idx : section->getDataAs<uint32_t>().slice(1))611if (OutputSection *osec = sections[read32(&idx)]->getOutputSection())612seen.insert(osec->sectionIndex);613os->size = (1 + seen.size()) * sizeof(uint32_t);614}615616template <class uint>617LLVM_ATTRIBUTE_ALWAYS_INLINE static void618encodeOneCrel(raw_svector_ostream &os, Elf_Crel<sizeof(uint) == 8> &out,619uint offset, const Symbol &sym, uint32_t type, uint addend) {620const auto deltaOffset = static_cast<uint64_t>(offset - out.r_offset);621out.r_offset = offset;622int64_t symidx = in.symTab->getSymbolIndex(sym);623if (sym.type == STT_SECTION) {624auto *d = dyn_cast<Defined>(&sym);625if (d) {626SectionBase *section = d->section;627assert(section->isLive());628addend = sym.getVA(addend) - section->getOutputSection()->addr;629} else {630// Encode R_*_NONE(symidx=0).631symidx = type = addend = 0;632}633}634635// Similar to llvm::ELF::encodeCrel.636uint8_t b = deltaOffset * 8 + (out.r_symidx != symidx) +637(out.r_type != type ? 2 : 0) +638(uint(out.r_addend) != addend ? 4 : 0);639if (deltaOffset < 0x10) {640os << char(b);641} else {642os << char(b | 0x80);643encodeULEB128(deltaOffset >> 4, os);644}645if (b & 1) {646encodeSLEB128(static_cast<int32_t>(symidx - out.r_symidx), os);647out.r_symidx = symidx;648}649if (b & 2) {650encodeSLEB128(static_cast<int32_t>(type - out.r_type), os);651out.r_type = type;652}653if (b & 4) {654encodeSLEB128(std::make_signed_t<uint>(addend - out.r_addend), os);655out.r_addend = addend;656}657}658659template <class ELFT>660static size_t relToCrel(raw_svector_ostream &os, Elf_Crel<ELFT::Is64Bits> &out,661InputSection *relSec, InputSectionBase *sec) {662const auto &file = *cast<ELFFileBase>(relSec->file);663if (relSec->type == SHT_REL) {664// REL conversion is complex and unsupported yet.665errorOrWarn(toString(relSec) + ": REL cannot be converted to CREL");666return 0;667}668auto rels = relSec->getDataAs<typename ELFT::Rela>();669for (auto rel : rels) {670encodeOneCrel<typename ELFT::uint>(671os, out, sec->getVA(rel.r_offset), file.getRelocTargetSym(rel),672rel.getType(config->isMips64EL), getAddend<ELFT>(rel));673}674return rels.size();675}676677// Compute the content of a non-alloc CREL section due to -r or --emit-relocs.678// Input CREL sections are decoded while REL[A] need to be converted.679template <bool is64> void OutputSection::finalizeNonAllocCrel() {680using uint = typename Elf_Crel_Impl<is64>::uint;681raw_svector_ostream os(crelBody);682uint64_t totalCount = 0;683Elf_Crel<is64> out{};684assert(commands.size() == 1);685auto *isd = cast<InputSectionDescription>(commands[0]);686for (InputSection *relSec : isd->sections) {687const auto &file = *cast<ELFFileBase>(relSec->file);688InputSectionBase *sec = relSec->getRelocatedSection();689if (relSec->type == SHT_CREL) {690RelocsCrel<is64> entries(relSec->content_);691totalCount += entries.size();692for (Elf_Crel_Impl<is64> r : entries) {693encodeOneCrel<uint>(os, out, uint(sec->getVA(r.r_offset)),694file.getSymbol(r.r_symidx), r.r_type, r.r_addend);695}696continue;697}698699// Convert REL[A] to CREL.700if constexpr (is64) {701totalCount += config->isLE ? relToCrel<ELF64LE>(os, out, relSec, sec)702: relToCrel<ELF64BE>(os, out, relSec, sec);703} else {704totalCount += config->isLE ? relToCrel<ELF32LE>(os, out, relSec, sec)705: relToCrel<ELF32BE>(os, out, relSec, sec);706}707}708709crelHeader = totalCount * 8 + 4;710size = getULEB128Size(crelHeader) + crelBody.size();711}712713void OutputSection::finalize() {714InputSection *first = getFirstInputSection(this);715716if (flags & SHF_LINK_ORDER) {717// We must preserve the link order dependency of sections with the718// SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We719// need to translate the InputSection sh_link to the OutputSection sh_link,720// all InputSections in the OutputSection have the same dependency.721if (auto *ex = dyn_cast<ARMExidxSyntheticSection>(first))722link = ex->getLinkOrderDep()->getParent()->sectionIndex;723else if (first->flags & SHF_LINK_ORDER)724if (auto *d = first->getLinkOrderDep())725link = d->getParent()->sectionIndex;726}727728if (type == SHT_GROUP) {729finalizeShtGroup(this, first);730return;731}732733if (!config->copyRelocs || !isStaticRelSecType(type))734return;735736// Skip if 'first' is synthetic, i.e. not a section created by --emit-relocs.737// Normally 'type' was changed by 'first' so 'first' should be non-null.738// However, if the output section is .rela.dyn, 'type' can be set by the empty739// synthetic .rela.plt and first can be null.740if (!first || isa<SyntheticSection>(first))741return;742743link = in.symTab->getParent()->sectionIndex;744// sh_info for SHT_REL[A] sections should contain the section header index of745// the section to which the relocation applies.746InputSectionBase *s = first->getRelocatedSection();747info = s->getOutputSection()->sectionIndex;748flags |= SHF_INFO_LINK;749// Finalize the content of non-alloc CREL.750if (type == SHT_CREL) {751if (config->is64)752finalizeNonAllocCrel<true>();753else754finalizeNonAllocCrel<false>();755}756}757758// Returns true if S is in one of the many forms the compiler driver may pass759// crtbegin files.760//761// Gcc uses any of crtbegin[<empty>|S|T].o.762// Clang uses Gcc's plus clang_rt.crtbegin[-<arch>|<empty>].o.763764static bool isCrt(StringRef s, StringRef beginEnd) {765s = sys::path::filename(s);766if (!s.consume_back(".o"))767return false;768if (s.consume_front("clang_rt."))769return s.consume_front(beginEnd);770return s.consume_front(beginEnd) && s.size() <= 1;771}772773// .ctors and .dtors are sorted by this order:774//775// 1. .ctors/.dtors in crtbegin (which contains a sentinel value -1).776// 2. The section is named ".ctors" or ".dtors" (priority: 65536).777// 3. The section has an optional priority value in the form of ".ctors.N" or778// ".dtors.N" where N is a number in the form of %05u (priority: 65535-N).779// 4. .ctors/.dtors in crtend (which contains a sentinel value 0).780//781// For 2 and 3, the sections are sorted by priority from high to low, e.g.782// .ctors (65536), .ctors.00100 (65436), .ctors.00200 (65336). In GNU ld's783// internal linker scripts, the sorting is by string comparison which can784// achieve the same goal given the optional priority values are of the same785// length.786//787// In an ideal world, we don't need this function because .init_array and788// .ctors are duplicate features (and .init_array is newer.) However, there789// are too many real-world use cases of .ctors, so we had no choice to790// support that with this rather ad-hoc semantics.791static bool compCtors(const InputSection *a, const InputSection *b) {792bool beginA = isCrt(a->file->getName(), "crtbegin");793bool beginB = isCrt(b->file->getName(), "crtbegin");794if (beginA != beginB)795return beginA;796bool endA = isCrt(a->file->getName(), "crtend");797bool endB = isCrt(b->file->getName(), "crtend");798if (endA != endB)799return endB;800return getPriority(a->name) > getPriority(b->name);801}802803// Sorts input sections by the special rules for .ctors and .dtors.804// Unfortunately, the rules are different from the one for .{init,fini}_array.805// Read the comment above.806void OutputSection::sortCtorsDtors() {807assert(commands.size() == 1);808auto *isd = cast<InputSectionDescription>(commands[0]);809llvm::stable_sort(isd->sections, compCtors);810}811812// If an input string is in the form of "foo.N" where N is a number, return N813// (65535-N if .ctors.N or .dtors.N). Otherwise, returns 65536, which is one814// greater than the lowest priority.815int elf::getPriority(StringRef s) {816size_t pos = s.rfind('.');817if (pos == StringRef::npos)818return 65536;819int v = 65536;820if (to_integer(s.substr(pos + 1), v, 10) &&821(pos == 6 && (s.starts_with(".ctors") || s.starts_with(".dtors"))))822v = 65535 - v;823return v;824}825826InputSection *elf::getFirstInputSection(const OutputSection *os) {827for (SectionCommand *cmd : os->commands)828if (auto *isd = dyn_cast<InputSectionDescription>(cmd))829if (!isd->sections.empty())830return isd->sections[0];831return nullptr;832}833834ArrayRef<InputSection *>835elf::getInputSections(const OutputSection &os,836SmallVector<InputSection *, 0> &storage) {837ArrayRef<InputSection *> ret;838storage.clear();839for (SectionCommand *cmd : os.commands) {840auto *isd = dyn_cast<InputSectionDescription>(cmd);841if (!isd)842continue;843if (ret.empty()) {844ret = isd->sections;845} else {846if (storage.empty())847storage.assign(ret.begin(), ret.end());848storage.insert(storage.end(), isd->sections.begin(), isd->sections.end());849}850}851return storage.empty() ? ret : ArrayRef(storage);852}853854// Sorts input sections by section name suffixes, so that .foo.N comes855// before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.856// We want to keep the original order if the priorities are the same857// because the compiler keeps the original initialization order in a858// translation unit and we need to respect that.859// For more detail, read the section of the GCC's manual about init_priority.860void OutputSection::sortInitFini() {861// Sort sections by priority.862sort([](InputSectionBase *s) { return getPriority(s->name); });863}864865std::array<uint8_t, 4> OutputSection::getFiller() {866if (filler)867return *filler;868if (flags & SHF_EXECINSTR)869return target->trapInstr;870return {0, 0, 0, 0};871}872873void OutputSection::checkDynRelAddends(const uint8_t *bufStart) {874assert(config->writeAddends && config->checkDynamicRelocs);875assert(isStaticRelSecType(type));876SmallVector<InputSection *, 0> storage;877ArrayRef<InputSection *> sections = getInputSections(*this, storage);878parallelFor(0, sections.size(), [&](size_t i) {879// When linking with -r or --emit-relocs we might also call this function880// for input .rel[a].<sec> sections which we simply pass through to the881// output. We skip over those and only look at the synthetic relocation882// sections created during linking.883const auto *sec = dyn_cast<RelocationBaseSection>(sections[i]);884if (!sec)885return;886for (const DynamicReloc &rel : sec->relocs) {887int64_t addend = rel.addend;888const OutputSection *relOsec = rel.inputSec->getOutputSection();889assert(relOsec != nullptr && "missing output section for relocation");890// Some targets have NOBITS synthetic sections with dynamic relocations891// with non-zero addends. Skip such sections.892if (is_contained({EM_PPC, EM_PPC64}, config->emachine) &&893(rel.inputSec == in.ppc64LongBranchTarget.get() ||894rel.inputSec == in.igotPlt.get()))895continue;896const uint8_t *relocTarget =897bufStart + relOsec->offset + rel.inputSec->getOffset(rel.offsetInSec);898// For SHT_NOBITS the written addend is always zero.899int64_t writtenAddend =900relOsec->type == SHT_NOBITS901? 0902: target->getImplicitAddend(relocTarget, rel.type);903if (addend != writtenAddend)904internalLinkerError(905getErrorLocation(relocTarget),906"wrote incorrect addend value 0x" + utohexstr(writtenAddend) +907" instead of 0x" + utohexstr(addend) +908" for dynamic relocation " + toString(rel.type) +909" at offset 0x" + utohexstr(rel.getOffset()) +910(rel.sym ? " against symbol " + toString(*rel.sym) : ""));911}912});913}914915template void OutputSection::writeHeaderTo<ELF32LE>(ELF32LE::Shdr *Shdr);916template void OutputSection::writeHeaderTo<ELF32BE>(ELF32BE::Shdr *Shdr);917template void OutputSection::writeHeaderTo<ELF64LE>(ELF64LE::Shdr *Shdr);918template void OutputSection::writeHeaderTo<ELF64BE>(ELF64BE::Shdr *Shdr);919920template void OutputSection::writeTo<ELF32LE>(uint8_t *,921llvm::parallel::TaskGroup &);922template void OutputSection::writeTo<ELF32BE>(uint8_t *,923llvm::parallel::TaskGroup &);924template void OutputSection::writeTo<ELF64LE>(uint8_t *,925llvm::parallel::TaskGroup &);926template void OutputSection::writeTo<ELF64BE>(uint8_t *,927llvm::parallel::TaskGroup &);928929template void OutputSection::maybeCompress<ELF32LE>();930template void OutputSection::maybeCompress<ELF32BE>();931template void OutputSection::maybeCompress<ELF64LE>();932template void OutputSection::maybeCompress<ELF64BE>();933934935