#include "Writer.h"
#include "AArch64ErrataFix.h"
#include "ARMErrataFix.h"
#include "CallGraphSort.h"
#include "Config.h"
#include "InputFiles.h"
#include "LinkerScript.h"
#include "MapFile.h"
#include "OutputSections.h"
#include "Relocations.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "SyntheticSections.h"
#include "Target.h"
#include "lld/Common/Arrays.h"
#include "lld/Common/CommonLinkerContext.h"
#include "lld/Common/Filesystem.h"
#include "lld/Common/Strings.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/BLAKE3.h"
#include "llvm/Support/Parallel.h"
#include "llvm/Support/RandomNumberGenerator.h"
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/xxhash.h"
#include <climits>
#define DEBUG_TYPE "lld"
using namespace llvm;
using namespace llvm::ELF;
using namespace llvm::object;
using namespace llvm::support;
using namespace llvm::support::endian;
using namespace lld;
using namespace lld::elf;
namespace {
template <class ELFT> class Writer {
public:
LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
Writer() : buffer(errorHandler().outputBuffer) {}
void run();
private:
void addSectionSymbols();
void sortSections();
void resolveShfLinkOrder();
void finalizeAddressDependentContent();
void optimizeBasicBlockJumps();
void sortInputSections();
void sortOrphanSections();
void finalizeSections();
void checkExecuteOnly();
void setReservedSymbolSections();
SmallVector<PhdrEntry *, 0> createPhdrs(Partition &part);
void addPhdrForSection(Partition &part, unsigned shType, unsigned pType,
unsigned pFlags);
void assignFileOffsets();
void assignFileOffsetsBinary();
void setPhdrs(Partition &part);
void checkSections();
void fixSectionAlignments();
void openFile();
void writeTrapInstr();
void writeHeader();
void writeSections();
void writeSectionsBinary();
void writeBuildId();
std::unique_ptr<FileOutputBuffer> &buffer;
void addRelIpltSymbols();
void addStartEndSymbols();
void addStartStopSymbols(OutputSection &osec);
uint64_t fileSize;
uint64_t sectionHeaderOff;
};
}
template <class ELFT> void elf::writeResult() {
Writer<ELFT>().run();
}
static void removeEmptyPTLoad(SmallVector<PhdrEntry *, 0> &phdrs) {
auto it = std::stable_partition(
phdrs.begin(), phdrs.end(), [&](const PhdrEntry *p) {
if (p->p_type != PT_LOAD)
return true;
if (!p->firstSec)
return false;
uint64_t size = p->lastSec->addr + p->lastSec->size - p->firstSec->addr;
return size != 0;
});
DenseSet<PhdrEntry *> removed(it, phdrs.end());
for (OutputSection *sec : outputSections)
if (removed.count(sec->ptLoad))
sec->ptLoad = nullptr;
phdrs.erase(it, phdrs.end());
}
void elf::copySectionsIntoPartitions() {
SmallVector<InputSectionBase *, 0> newSections;
const size_t ehSize = ctx.ehInputSections.size();
for (unsigned part = 2; part != partitions.size() + 1; ++part) {
for (InputSectionBase *s : ctx.inputSections) {
if (!(s->flags & SHF_ALLOC) || !s->isLive() || s->type != SHT_NOTE)
continue;
auto *copy = make<InputSection>(cast<InputSection>(*s));
copy->partition = part;
newSections.push_back(copy);
}
for (size_t i = 0; i != ehSize; ++i) {
assert(ctx.ehInputSections[i]->isLive());
auto *copy = make<EhInputSection>(*ctx.ehInputSections[i]);
copy->partition = part;
ctx.ehInputSections.push_back(copy);
}
}
ctx.inputSections.insert(ctx.inputSections.end(), newSections.begin(),
newSections.end());
}
static Defined *addOptionalRegular(StringRef name, SectionBase *sec,
uint64_t val, uint8_t stOther = STV_HIDDEN) {
Symbol *s = symtab.find(name);
if (!s || s->isDefined() || s->isCommon())
return nullptr;
s->resolve(Defined{ctx.internalFile, StringRef(), STB_GLOBAL, stOther,
STT_NOTYPE, val,
0, sec});
s->isUsedInRegularObj = true;
return cast<Defined>(s);
}
void elf::addReservedSymbols() {
if (config->emachine == EM_MIPS) {
auto addAbsolute = [](StringRef name) {
Symbol *sym =
symtab.addSymbol(Defined{ctx.internalFile, name, STB_GLOBAL,
STV_HIDDEN, STT_NOTYPE, 0, 0, nullptr});
sym->isUsedInRegularObj = true;
return cast<Defined>(sym);
};
ElfSym::mipsGp = addAbsolute("_gp");
if (symtab.find("_gp_disp"))
ElfSym::mipsGpDisp = addAbsolute("_gp_disp");
if (symtab.find("__gnu_local_gp"))
ElfSym::mipsLocalGp = addAbsolute("__gnu_local_gp");
} else if (config->emachine == EM_PPC) {
addOptionalRegular("_SDA_BASE_", nullptr, 0, STV_HIDDEN);
} else if (config->emachine == EM_PPC64) {
addPPC64SaveRestore();
}
StringRef gotSymName =
(config->emachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
if (Symbol *s = symtab.find(gotSymName)) {
if (s->isDefined()) {
error(toString(s->file) + " cannot redefine linker defined symbol '" +
gotSymName + "'");
return;
}
uint64_t gotOff = 0;
if (config->emachine == EM_PPC64)
gotOff = 0x8000;
s->resolve(Defined{ctx.internalFile, StringRef(), STB_GLOBAL, STV_HIDDEN,
STT_NOTYPE, gotOff, 0, Out::elfHeader});
ElfSym::globalOffsetTable = cast<Defined>(s);
}
addOptionalRegular("__ehdr_start", Out::elfHeader, 0, STV_HIDDEN);
addOptionalRegular("__executable_start", Out::elfHeader, 0, STV_HIDDEN);
addOptionalRegular("__dso_handle", Out::elfHeader, 0, STV_HIDDEN);
if (script->hasSectionsCommand)
return;
auto add = [](StringRef s, int64_t pos) {
return addOptionalRegular(s, Out::elfHeader, pos, STV_DEFAULT);
};
ElfSym::bss = add("__bss_start", 0);
ElfSym::end1 = add("end", -1);
ElfSym::end2 = add("_end", -1);
ElfSym::etext1 = add("etext", -1);
ElfSym::etext2 = add("_etext", -1);
ElfSym::edata1 = add("edata", -1);
ElfSym::edata2 = add("_edata", -1);
}
static void demoteDefined(Defined &sym, DenseMap<SectionBase *, size_t> &map) {
if (map.empty())
for (auto [i, sec] : llvm::enumerate(sym.file->getSections()))
map.try_emplace(sec, i);
uint8_t binding = sym.isWeak() ? uint8_t(STB_GLOBAL) : sym.binding;
Undefined(sym.file, sym.getName(), binding, sym.stOther, sym.type,
map.lookup(sym.section))
.overwrite(sym);
sym.isUsedInRegularObj = false;
}
static void demoteSymbolsAndComputeIsPreemptible() {
llvm::TimeTraceScope timeScope("Demote symbols");
DenseMap<InputFile *, DenseMap<SectionBase *, size_t>> sectionIndexMap;
for (Symbol *sym : symtab.getSymbols()) {
if (auto *d = dyn_cast<Defined>(sym)) {
if (d->section && !d->section->isLive())
demoteDefined(*d, sectionIndexMap[d->file]);
} else {
auto *s = dyn_cast<SharedSymbol>(sym);
if (sym->isLazy() || (s && !cast<SharedFile>(s->file)->isNeeded)) {
uint8_t binding = sym->isLazy() ? sym->binding : uint8_t(STB_WEAK);
Undefined(ctx.internalFile, sym->getName(), binding, sym->stOther,
sym->type)
.overwrite(*sym);
sym->versionId = VER_NDX_GLOBAL;
}
}
if (config->hasDynSymTab)
sym->isPreemptible = computeIsPreemptible(*sym);
}
}
static OutputSection *findSection(StringRef name, unsigned partition = 1) {
for (SectionCommand *cmd : script->sectionCommands)
if (auto *osd = dyn_cast<OutputDesc>(cmd))
if (osd->osec.name == name && osd->osec.partition == partition)
return &osd->osec;
return nullptr;
}
template <class ELFT> void Writer<ELFT>::run() {
finalizeSections();
checkExecuteOnly();
for (OutputSection *sec : outputSections)
sec->maybeCompress<ELFT>();
if (script->hasSectionsCommand)
script->allocateHeaders(mainPart->phdrs);
for (Partition &part : partitions)
removeEmptyPTLoad(part.phdrs);
if (!config->oFormatBinary)
assignFileOffsets();
else
assignFileOffsetsBinary();
for (Partition &part : partitions)
setPhdrs(part);
writeMapAndCref();
if (config->printMemoryUsage)
script->printMemoryUsage(lld::outs());
if (config->checkSections)
checkSections();
if (errorCount())
return;
{
llvm::TimeTraceScope timeScope("Write output file");
openFile();
if (errorCount())
return;
if (!config->oFormatBinary) {
if (config->zSeparate != SeparateSegmentKind::None)
writeTrapInstr();
writeHeader();
writeSections();
} else {
writeSectionsBinary();
}
writeBuildId();
if (errorCount())
return;
if (auto e = buffer->commit())
fatal("failed to write output '" + buffer->getPath() +
"': " + toString(std::move(e)));
if (!config->cmseOutputLib.empty())
writeARMCmseImportLib<ELFT>();
}
}
template <class ELFT, class RelTy>
static void markUsedLocalSymbolsImpl(ObjFile<ELFT> *file,
llvm::ArrayRef<RelTy> rels) {
for (const RelTy &rel : rels) {
Symbol &sym = file->getRelocTargetSym(rel);
if (sym.isLocal())
sym.used = true;
}
}
template <class ELFT> static void markUsedLocalSymbols() {
if (config->gcSections)
return;
for (ELFFileBase *file : ctx.objectFiles) {
ObjFile<ELFT> *f = cast<ObjFile<ELFT>>(file);
for (InputSectionBase *s : f->getSections()) {
InputSection *isec = dyn_cast_or_null<InputSection>(s);
if (!isec)
continue;
if (isec->type == SHT_REL) {
markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rel>());
} else if (isec->type == SHT_RELA) {
markUsedLocalSymbolsImpl(f, isec->getDataAs<typename ELFT::Rela>());
} else if (isec->type == SHT_CREL) {
for (Elf_Crel_Impl<true> r : RelocsCrel<true>(isec->content_)) {
Symbol &sym = file->getSymbol(r.r_symidx);
if (sym.isLocal())
sym.used = true;
}
}
}
}
}
static bool shouldKeepInSymtab(const Defined &sym) {
if (sym.isSection())
return false;
if (sym.used && config->copyRelocs)
return true;
if (config->emachine == EM_ARM && sym.section &&
sym.section->type == SHT_ARM_EXIDX)
return false;
if (config->discard == DiscardPolicy::None)
return true;
if (config->discard == DiscardPolicy::All)
return false;
if (sym.getName().starts_with(".L") &&
(config->discard == DiscardPolicy::Locals ||
(sym.section && (sym.section->flags & SHF_MERGE))))
return false;
return true;
}
bool lld::elf::includeInSymtab(const Symbol &b) {
if (auto *d = dyn_cast<Defined>(&b)) {
SectionBase *sec = d->section;
if (!sec)
return true;
assert(sec->isLive());
if (auto *s = dyn_cast<MergeInputSection>(sec))
return s->getSectionPiece(d->value).live;
return true;
}
return b.used || !config->gcSections;
}
static void demoteAndCopyLocalSymbols() {
llvm::TimeTraceScope timeScope("Add local symbols");
for (ELFFileBase *file : ctx.objectFiles) {
DenseMap<SectionBase *, size_t> sectionIndexMap;
for (Symbol *b : file->getLocalSymbols()) {
assert(b->isLocal() && "should have been caught in initializeSymbols()");
auto *dr = dyn_cast<Defined>(b);
if (!dr)
continue;
if (dr->section && !dr->section->isLive())
demoteDefined(*dr, sectionIndexMap);
else if (in.symTab && includeInSymtab(*b) && shouldKeepInSymtab(*dr))
in.symTab->addSymbol(b);
}
}
}
template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
for (SectionCommand *cmd : script->sectionCommands) {
auto *osd = dyn_cast<OutputDesc>(cmd);
if (!osd)
continue;
OutputSection &osec = osd->osec;
InputSectionBase *isec = nullptr;
for (SectionCommand *cmd : osec.commands) {
auto *isd = dyn_cast<InputSectionDescription>(cmd);
if (!isd)
continue;
for (InputSectionBase *s : isd->sections) {
if (isStaticRelSecType(s->type))
continue;
if (isa<SyntheticSection>(s) && !(s->flags & SHF_MERGE))
continue;
isec = s;
break;
}
}
if (!isec)
continue;
in.symTab->addSymbol(makeDefined(isec->file, "", STB_LOCAL, 0,
STT_SECTION,
0, 0, &osec));
}
}
static bool isRelroSection(const OutputSection *sec) {
if (!config->zRelro)
return false;
if (sec->relro)
return true;
uint64_t flags = sec->flags;
if (!(flags & SHF_ALLOC) || !(flags & SHF_WRITE))
return false;
if (flags & SHF_TLS)
return true;
uint32_t type = sec->type;
if (type == SHT_INIT_ARRAY || type == SHT_FINI_ARRAY ||
type == SHT_PREINIT_ARRAY)
return true;
if (in.got && sec == in.got->getParent())
return true;
if (sec->name == ".toc")
return true;
if (sec == in.gotPlt->getParent())
return config->zNow;
if (in.relroPadding && sec == in.relroPadding->getParent())
return true;
if (sec->name == ".dynamic")
return true;
StringRef s = sec->name;
bool abiAgnostic = s == ".data.rel.ro" || s == ".bss.rel.ro" ||
s == ".ctors" || s == ".dtors" || s == ".jcr" ||
s == ".eh_frame" || s == ".fini_array" ||
s == ".init_array" || s == ".preinit_array";
bool abiSpecific =
config->osabi == ELFOSABI_OPENBSD && s == ".openbsd.randomdata";
return abiAgnostic || abiSpecific;
}
enum RankFlags {
RF_NOT_ADDR_SET = 1 << 27,
RF_NOT_ALLOC = 1 << 26,
RF_PARTITION = 1 << 18,
RF_LARGE_ALT = 1 << 15,
RF_WRITE = 1 << 14,
RF_EXEC_WRITE = 1 << 13,
RF_EXEC = 1 << 12,
RF_RODATA = 1 << 11,
RF_LARGE = 1 << 10,
RF_NOT_RELRO = 1 << 9,
RF_NOT_TLS = 1 << 8,
RF_BSS = 1 << 7,
};
unsigned elf::getSectionRank(OutputSection &osec) {
unsigned rank = osec.partition * RF_PARTITION;
if (config->sectionStartMap.count(osec.name))
return rank;
rank |= RF_NOT_ADDR_SET;
if (!(osec.flags & SHF_ALLOC))
return rank | RF_NOT_ALLOC;
bool isExec = osec.flags & SHF_EXECINSTR;
bool isWrite = osec.flags & SHF_WRITE;
if (!isWrite && !isExec) {
if (osec.flags & SHF_X86_64_LARGE && config->emachine == EM_X86_64)
rank |= config->zLrodataAfterBss ? RF_LARGE_ALT : 0;
else
rank |= config->zLrodataAfterBss ? 0 : RF_LARGE;
if (osec.type == SHT_LLVM_PART_EHDR)
;
else if (osec.type == SHT_LLVM_PART_PHDR)
rank |= 1;
else if (osec.name == ".interp")
rank |= 2;
else if (osec.type == SHT_NOTE)
rank |= 3;
else if (osec.type != SHT_PROGBITS)
rank |= 4;
else
rank |= RF_RODATA;
} else if (isExec) {
rank |= isWrite ? RF_EXEC_WRITE : RF_EXEC;
} else {
rank |= RF_WRITE;
if (!(osec.flags & SHF_TLS))
rank |= RF_NOT_TLS;
if (isRelroSection(&osec))
osec.relro = true;
else
rank |= RF_NOT_RELRO;
if (osec.flags & SHF_X86_64_LARGE && config->emachine == EM_X86_64) {
rank |= config->zLrodataAfterBss
? (osec.type == SHT_NOBITS ? 1 : RF_LARGE_ALT)
: RF_LARGE;
}
}
if (osec.type == SHT_NOBITS)
rank |= RF_BSS;
if (config->emachine == EM_PPC64) {
StringRef name = osec.name;
if (name == ".got")
rank |= 1;
else if (name == ".toc")
rank |= 2;
}
if (config->emachine == EM_MIPS) {
if (osec.name != ".got")
rank |= 1;
if (osec.flags & SHF_MIPS_GPREL)
rank |= 2;
}
if (config->emachine == EM_RISCV) {
StringRef name = osec.name;
if (name == ".sdata" || (osec.type == SHT_NOBITS && name != ".sbss"))
rank |= 1;
}
return rank;
}
static bool compareSections(const SectionCommand *aCmd,
const SectionCommand *bCmd) {
const OutputSection *a = &cast<OutputDesc>(aCmd)->osec;
const OutputSection *b = &cast<OutputDesc>(bCmd)->osec;
if (a->sortRank != b->sortRank)
return a->sortRank < b->sortRank;
if (!(a->sortRank & RF_NOT_ADDR_SET))
return config->sectionStartMap.lookup(a->name) <
config->sectionStartMap.lookup(b->name);
return false;
}
void PhdrEntry::add(OutputSection *sec) {
lastSec = sec;
if (!firstSec)
firstSec = sec;
p_align = std::max(p_align, sec->addralign);
if (p_type == PT_LOAD)
sec->ptLoad = this;
}
template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
if (config->isPic)
return;
std::string name = config->isRela ? "__rela_iplt_start" : "__rel_iplt_start";
ElfSym::relaIpltStart =
addOptionalRegular(name, Out::elfHeader, 0, STV_HIDDEN);
name.replace(name.size() - 5, 5, "end");
ElfSym::relaIpltEnd = addOptionalRegular(name, Out::elfHeader, 0, STV_HIDDEN);
}
template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
if (ElfSym::globalOffsetTable) {
InputSection *sec = in.gotPlt.get();
if (!target->gotBaseSymInGotPlt)
sec = in.mipsGot ? cast<InputSection>(in.mipsGot.get())
: cast<InputSection>(in.got.get());
ElfSym::globalOffsetTable->section = sec;
}
if (ElfSym::relaIpltStart && mainPart->relaDyn->isNeeded()) {
ElfSym::relaIpltStart->section = mainPart->relaDyn.get();
ElfSym::relaIpltEnd->section = mainPart->relaDyn.get();
ElfSym::relaIpltEnd->value = mainPart->relaDyn->getSize();
}
PhdrEntry *last = nullptr;
OutputSection *lastRO = nullptr;
auto isLarge = [](OutputSection *osec) {
return config->emachine == EM_X86_64 && osec->flags & SHF_X86_64_LARGE;
};
for (Partition &part : partitions) {
for (PhdrEntry *p : part.phdrs) {
if (p->p_type != PT_LOAD)
continue;
last = p;
if (!(p->p_flags & PF_W) && p->lastSec && !isLarge(p->lastSec))
lastRO = p->lastSec;
}
}
if (lastRO) {
if (ElfSym::etext1)
ElfSym::etext1->section = lastRO;
if (ElfSym::etext2)
ElfSym::etext2->section = lastRO;
}
if (last) {
OutputSection *edata = nullptr;
for (OutputSection *os : outputSections) {
if (os->type != SHT_NOBITS && !isLarge(os))
edata = os;
if (os == last->lastSec)
break;
}
if (ElfSym::edata1)
ElfSym::edata1->section = edata;
if (ElfSym::edata2)
ElfSym::edata2->section = edata;
if (ElfSym::end1)
ElfSym::end1->section = last->lastSec;
if (ElfSym::end2)
ElfSym::end2->section = last->lastSec;
}
if (ElfSym::bss) {
OutputSection *sbss =
config->emachine == EM_RISCV ? findSection(".sbss") : nullptr;
ElfSym::bss->section = sbss ? sbss : findSection(".bss");
}
if (ElfSym::mipsGp) {
for (OutputSection *os : outputSections) {
if (os->flags & SHF_MIPS_GPREL) {
ElfSym::mipsGp->section = os;
ElfSym::mipsGp->value = 0x7ff0;
break;
}
}
}
}
static int getRankProximity(OutputSection *a, SectionCommand *b) {
auto *osd = dyn_cast<OutputDesc>(b);
return (osd && osd->osec.hasInputSections)
? llvm::countl_zero(a->sortRank ^ osd->osec.sortRank)
: -1;
}
static bool shouldSkip(SectionCommand *cmd) {
if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
return assign->name != ".";
return false;
}
static SmallVectorImpl<SectionCommand *>::iterator
findOrphanPos(SmallVectorImpl<SectionCommand *>::iterator b,
SmallVectorImpl<SectionCommand *>::iterator e) {
OutputSection *sec = &cast<OutputDesc>(*e)->osec;
if (!(sec->flags & SHF_ALLOC))
return e;
if (in.relroPadding && sec == in.relroPadding->getParent()) {
auto i = std::find_if(b, e, [=](SectionCommand *a) {
if (auto *assign = dyn_cast<SymbolAssignment>(a))
return assign->dataSegmentRelroEnd;
return false;
});
if (i != e)
return i;
}
int maxP = 0;
auto i = e;
for (auto j = b; j != e; ++j) {
int p = getRankProximity(sec, *j);
if (p > maxP ||
(p == maxP && cast<OutputDesc>(*j)->osec.sortRank <= sec->sortRank)) {
maxP = p;
i = j;
}
}
if (i == e)
return e;
auto isOutputSecWithInputSections = [](SectionCommand *cmd) {
auto *osd = dyn_cast<OutputDesc>(cmd);
return osd && osd->osec.hasInputSections;
};
bool mustAfter = script->hasPhdrsCommands() || !script->memoryRegions.empty();
if (cast<OutputDesc>(*i)->osec.sortRank <= sec->sortRank || mustAfter) {
for (auto j = ++i; j != e; ++j) {
if (!isOutputSecWithInputSections(*j))
continue;
if (getRankProximity(sec, *j) != maxP)
break;
i = j + 1;
}
} else {
for (; i != b; --i)
if (isOutputSecWithInputSections(i[-1]))
break;
}
if (std::find_if(i, e, isOutputSecWithInputSections) == e)
return e;
while (i != e && shouldSkip(*i))
++i;
return i;
}
static void maybeShuffle(DenseMap<const InputSectionBase *, int> &order) {
if (config->shuffleSections.empty())
return;
SmallVector<InputSectionBase *, 0> matched, sections = ctx.inputSections;
matched.reserve(sections.size());
for (const auto &patAndSeed : config->shuffleSections) {
matched.clear();
for (InputSectionBase *sec : sections)
if (patAndSeed.first.match(sec->name))
matched.push_back(sec);
const uint32_t seed = patAndSeed.second;
if (seed == UINT32_MAX) {
std::reverse(matched.begin(), matched.end());
} else {
std::mt19937 g(seed ? seed : std::random_device()());
llvm::shuffle(matched.begin(), matched.end(), g);
}
size_t i = 0;
for (InputSectionBase *&sec : sections)
if (patAndSeed.first.match(sec->name))
sec = matched[i++];
}
int prio = 0;
for (InputSectionBase *sec : sections) {
if (order.try_emplace(sec, prio).second)
++prio;
}
}
static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
DenseMap<const InputSectionBase *, int> sectionOrder;
if (!config->callGraphProfile.empty())
return computeCallGraphProfileOrder();
if (config->symbolOrderingFile.empty())
return sectionOrder;
struct SymbolOrderEntry {
int priority;
bool present;
};
DenseMap<CachedHashStringRef, SymbolOrderEntry> symbolOrder;
int priority = -config->symbolOrderingFile.size();
for (StringRef s : config->symbolOrderingFile)
symbolOrder.insert({CachedHashStringRef(s), {priority++, false}});
auto addSym = [&](Symbol &sym) {
auto it = symbolOrder.find(CachedHashStringRef(sym.getName()));
if (it == symbolOrder.end())
return;
SymbolOrderEntry &ent = it->second;
ent.present = true;
maybeWarnUnorderableSymbol(&sym);
if (auto *d = dyn_cast<Defined>(&sym)) {
if (auto *sec = dyn_cast_or_null<InputSectionBase>(d->section)) {
int &priority = sectionOrder[cast<InputSectionBase>(sec)];
priority = std::min(priority, ent.priority);
}
}
};
for (Symbol *sym : symtab.getSymbols())
addSym(*sym);
for (ELFFileBase *file : ctx.objectFiles)
for (Symbol *sym : file->getLocalSymbols())
addSym(*sym);
if (config->warnSymbolOrdering)
for (auto orderEntry : symbolOrder)
if (!orderEntry.second.present)
warn("symbol ordering file: no such symbol: " + orderEntry.first.val());
return sectionOrder;
}
static void
sortISDBySectionOrder(InputSectionDescription *isd,
const DenseMap<const InputSectionBase *, int> &order,
bool executableOutputSection) {
SmallVector<InputSection *, 0> unorderedSections;
SmallVector<std::pair<InputSection *, int>, 0> orderedSections;
uint64_t unorderedSize = 0;
uint64_t totalSize = 0;
for (InputSection *isec : isd->sections) {
if (executableOutputSection)
totalSize += isec->getSize();
auto i = order.find(isec);
if (i == order.end()) {
unorderedSections.push_back(isec);
unorderedSize += isec->getSize();
continue;
}
orderedSections.push_back({isec, i->second});
}
llvm::sort(orderedSections, llvm::less_second());
size_t insPt = 0;
if (executableOutputSection && !orderedSections.empty() &&
target->getThunkSectionSpacing() &&
totalSize >= target->getThunkSectionSpacing()) {
uint64_t unorderedPos = 0;
for (; insPt != unorderedSections.size(); ++insPt) {
unorderedPos += unorderedSections[insPt]->getSize();
if (unorderedPos > unorderedSize / 2)
break;
}
}
isd->sections.clear();
for (InputSection *isec : ArrayRef(unorderedSections).slice(0, insPt))
isd->sections.push_back(isec);
for (std::pair<InputSection *, int> p : orderedSections)
isd->sections.push_back(p.first);
for (InputSection *isec : ArrayRef(unorderedSections).slice(insPt))
isd->sections.push_back(isec);
}
static void sortSection(OutputSection &osec,
const DenseMap<const InputSectionBase *, int> &order) {
StringRef name = osec.name;
if (name == ".init" || name == ".fini")
return;
if (!order.empty())
for (SectionCommand *b : osec.commands)
if (auto *isd = dyn_cast<InputSectionDescription>(b))
sortISDBySectionOrder(isd, order, osec.flags & SHF_EXECINSTR);
if (script->hasSectionsCommand)
return;
if (name == ".init_array" || name == ".fini_array") {
osec.sortInitFini();
} else if (name == ".ctors" || name == ".dtors") {
osec.sortCtorsDtors();
} else if (config->emachine == EM_PPC64 && name == ".toc") {
assert(osec.commands.size() == 1);
auto *isd = cast<InputSectionDescription>(osec.commands[0]);
llvm::stable_sort(isd->sections,
[](const InputSection *a, const InputSection *b) -> bool {
return a->file->ppc64SmallCodeModelTocRelocs &&
!b->file->ppc64SmallCodeModelTocRelocs;
});
}
}
template <class ELFT> void Writer<ELFT>::sortInputSections() {
DenseMap<const InputSectionBase *, int> order = buildSectionOrder();
maybeShuffle(order);
for (SectionCommand *cmd : script->sectionCommands)
if (auto *osd = dyn_cast<OutputDesc>(cmd))
sortSection(osd->osec, order);
}
template <class ELFT> void Writer<ELFT>::sortSections() {
llvm::TimeTraceScope timeScope("Sort sections");
if (config->relocatable) {
script->adjustOutputSections();
return;
}
sortInputSections();
for (SectionCommand *cmd : script->sectionCommands)
if (auto *osd = dyn_cast<OutputDesc>(cmd))
osd->osec.sortRank = getSectionRank(osd->osec);
if (!script->hasSectionsCommand) {
auto mid = std::stable_partition(
script->sectionCommands.begin(), script->sectionCommands.end(),
[](SectionCommand *cmd) { return isa<OutputDesc>(cmd); });
std::stable_sort(script->sectionCommands.begin(), mid, compareSections);
}
script->processInsertCommands();
script->adjustOutputSections();
if (script->hasSectionsCommand)
sortOrphanSections();
script->adjustSectionsAfterSorting();
}
template <class ELFT> void Writer<ELFT>::sortOrphanSections() {
auto i = script->sectionCommands.begin();
auto e = script->sectionCommands.end();
auto nonScriptI = std::find_if(i, e, [](SectionCommand *cmd) {
if (auto *osd = dyn_cast<OutputDesc>(cmd))
return osd->osec.sectionIndex == UINT32_MAX;
return false;
});
std::stable_sort(nonScriptI, e, compareSections);
auto firstSectionOrDotAssignment =
std::find_if(i, e, [](SectionCommand *cmd) { return !shouldSkip(cmd); });
if (firstSectionOrDotAssignment != e &&
isa<SymbolAssignment>(**firstSectionOrDotAssignment))
++firstSectionOrDotAssignment;
i = firstSectionOrDotAssignment;
while (nonScriptI != e) {
auto pos = findOrphanPos(i, nonScriptI);
OutputSection *orphan = &cast<OutputDesc>(*nonScriptI)->osec;
unsigned rank = orphan->sortRank;
auto end = std::find_if(nonScriptI + 1, e, [=](SectionCommand *cmd) {
return cast<OutputDesc>(cmd)->osec.sortRank != rank;
});
std::rotate(pos, nonScriptI, end);
nonScriptI = end;
}
}
static bool compareByFilePosition(InputSection *a, InputSection *b) {
InputSection *la = a->flags & SHF_LINK_ORDER ? a->getLinkOrderDep() : nullptr;
InputSection *lb = b->flags & SHF_LINK_ORDER ? b->getLinkOrderDep() : nullptr;
if (!la || !lb)
return la && !lb;
OutputSection *aOut = la->getParent();
OutputSection *bOut = lb->getParent();
if (aOut == bOut)
return la->outSecOff < lb->outSecOff;
if (aOut->addr == bOut->addr)
return aOut->sectionIndex < bOut->sectionIndex;
return aOut->addr < bOut->addr;
}
template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
llvm::TimeTraceScope timeScope("Resolve SHF_LINK_ORDER");
for (OutputSection *sec : outputSections) {
if (!(sec->flags & SHF_LINK_ORDER))
continue;
if (!config->relocatable && config->emachine == EM_ARM &&
sec->type == SHT_ARM_EXIDX)
continue;
SmallVector<InputSection **, 0> scriptSections;
SmallVector<InputSection *, 0> sections;
for (SectionCommand *cmd : sec->commands) {
auto *isd = dyn_cast<InputSectionDescription>(cmd);
if (!isd)
continue;
bool hasLinkOrder = false;
scriptSections.clear();
sections.clear();
for (InputSection *&isec : isd->sections) {
if (isec->flags & SHF_LINK_ORDER) {
InputSection *link = isec->getLinkOrderDep();
if (link && !link->getParent())
error(toString(isec) + ": sh_link points to discarded section " +
toString(link));
hasLinkOrder = true;
}
scriptSections.push_back(&isec);
sections.push_back(isec);
}
if (hasLinkOrder && errorCount() == 0) {
llvm::stable_sort(sections, compareByFilePosition);
for (int i = 0, n = sections.size(); i != n; ++i)
*scriptSections[i] = sections[i];
}
}
}
}
static void finalizeSynthetic(SyntheticSection *sec) {
if (sec && sec->isNeeded() && sec->getParent()) {
llvm::TimeTraceScope timeScope("Finalize synthetic sections", sec->name);
sec->finalizeContents();
}
}
template <class ELFT> void Writer<ELFT>::finalizeAddressDependentContent() {
llvm::TimeTraceScope timeScope("Finalize address dependent content");
ThunkCreator tc;
AArch64Err843419Patcher a64p;
ARMErr657417Patcher a32p;
script->assignAddresses();
const auto finalizeOrderDependentContent = [this] {
for (Partition &part : partitions)
finalizeSynthetic(part.armExidx.get());
resolveShfLinkOrder();
};
finalizeOrderDependentContent();
if (config->emachine == EM_HEXAGON)
hexagonTLSSymbolUpdate(outputSections);
uint32_t pass = 0, assignPasses = 0;
for (;;) {
bool changed = target->needsThunks ? tc.createThunks(pass, outputSections)
: target->relaxOnce(pass);
bool spilled = script->spillSections();
changed |= spilled;
++pass;
if (changed && pass >= 30) {
error(target->needsThunks ? "thunk creation not converged"
: "relaxation not converged");
break;
}
if (config->fixCortexA53Errata843419) {
if (changed)
script->assignAddresses();
changed |= a64p.createFixes();
}
if (config->fixCortexA8) {
if (changed)
script->assignAddresses();
changed |= a32p.createFixes();
}
finalizeSynthetic(in.got.get());
if (in.mipsGot)
in.mipsGot->updateAllocSize();
for (Partition &part : partitions) {
if (part.relrAuthDyn) {
auto it = llvm::remove_if(
part.relrAuthDyn->relocs, [&part](const RelativeReloc &elem) {
const Relocation &reloc = elem.inputSec->relocs()[elem.relocIdx];
if (isInt<32>(reloc.sym->getVA(reloc.addend)))
return false;
part.relaDyn->addReloc({R_AARCH64_AUTH_RELATIVE, elem.inputSec,
reloc.offset,
DynamicReloc::AddendOnlyWithTargetVA,
*reloc.sym, reloc.addend, R_ABS});
return true;
});
changed |= (it != part.relrAuthDyn->relocs.end());
part.relrAuthDyn->relocs.erase(it, part.relrAuthDyn->relocs.end());
}
if (part.relaDyn)
changed |= part.relaDyn->updateAllocSize();
if (part.relrDyn)
changed |= part.relrDyn->updateAllocSize();
if (part.relrAuthDyn)
changed |= part.relrAuthDyn->updateAllocSize();
if (part.memtagGlobalDescriptors)
changed |= part.memtagGlobalDescriptors->updateAllocSize();
}
std::pair<const OutputSection *, const Defined *> changes =
script->assignAddresses();
if (!changed) {
if (!changes.first && !changes.second)
break;
if (++assignPasses == 5) {
if (changes.first)
errorOrWarn("address (0x" + Twine::utohexstr(changes.first->addr) +
") of section '" + changes.first->name +
"' does not converge");
if (changes.second)
errorOrWarn("assignment to symbol " + toString(*changes.second) +
" does not converge");
break;
}
} else if (spilled) {
finalizeOrderDependentContent();
}
}
if (!config->relocatable)
target->finalizeRelax(pass);
if (config->relocatable)
for (OutputSection *sec : outputSections)
sec->addr = 0;
for (SectionCommand *cmd : script->sectionCommands)
if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
OutputSection *osec = &osd->osec;
if (osec->addr % osec->addralign != 0)
warn("address (0x" + Twine::utohexstr(osec->addr) + ") of section " +
osec->name + " is not a multiple of alignment (" +
Twine(osec->addralign) + ")");
}
script->erasePotentialSpillSections();
}
static void fixSymbolsAfterShrinking() {
for (InputFile *File : ctx.objectFiles) {
parallelForEach(File->getSymbols(), [&](Symbol *Sym) {
auto *def = dyn_cast<Defined>(Sym);
if (!def)
return;
const SectionBase *sec = def->section;
if (!sec)
return;
const InputSectionBase *inputSec = dyn_cast<InputSectionBase>(sec);
if (!inputSec || !inputSec->bytesDropped)
return;
const size_t OldSize = inputSec->content().size();
const size_t NewSize = OldSize - inputSec->bytesDropped;
if (def->value > NewSize && def->value <= OldSize) {
LLVM_DEBUG(llvm::dbgs()
<< "Moving symbol " << Sym->getName() << " from "
<< def->value << " to "
<< def->value - inputSec->bytesDropped << " bytes\n");
def->value -= inputSec->bytesDropped;
return;
}
if (def->value + def->size > NewSize && def->value <= OldSize &&
def->value + def->size <= OldSize) {
LLVM_DEBUG(llvm::dbgs()
<< "Shrinking symbol " << Sym->getName() << " from "
<< def->size << " to " << def->size - inputSec->bytesDropped
<< " bytes\n");
def->size -= inputSec->bytesDropped;
}
});
}
}
template <class ELFT> void Writer<ELFT>::optimizeBasicBlockJumps() {
assert(config->optimizeBBJumps);
SmallVector<InputSection *, 0> storage;
script->assignAddresses();
for (OutputSection *osec : outputSections) {
if (!(osec->flags & SHF_EXECINSTR))
continue;
ArrayRef<InputSection *> sections = getInputSections(*osec, storage);
size_t numDeleted = 0;
for (size_t i = 0, e = sections.size(); i != e; ++i) {
InputSection *next = i + 1 < sections.size() ? sections[i + 1] : nullptr;
InputSection &sec = *sections[i];
numDeleted += target->deleteFallThruJmpInsn(sec, sec.file, next);
}
if (numDeleted > 0) {
script->assignAddresses();
LLVM_DEBUG(llvm::dbgs()
<< "Removing " << numDeleted << " fall through jumps\n");
}
}
fixSymbolsAfterShrinking();
for (OutputSection *osec : outputSections)
for (InputSection *is : getInputSections(*osec, storage))
is->trim();
}
static void removeUnusedSyntheticSections() {
auto start =
llvm::find_if(llvm::reverse(ctx.inputSections), [](InputSectionBase *s) {
return !isa<SyntheticSection>(s);
}).base();
DenseSet<InputSectionBase *> unused;
auto end =
std::remove_if(start, ctx.inputSections.end(), [&](InputSectionBase *s) {
auto *sec = cast<SyntheticSection>(s);
if (sec->getParent() && sec->isNeeded())
return false;
if (config->emachine == EM_AARCH64 && config->relrPackDynRelocs)
if (auto *relSec = dyn_cast<RelocationBaseSection>(sec))
if (relSec == mainPart->relaDyn.get())
return false;
unused.insert(sec);
return true;
});
ctx.inputSections.erase(end, ctx.inputSections.end());
for (auto *sec : unused)
if (OutputSection *osec = cast<SyntheticSection>(sec)->getParent())
for (SectionCommand *cmd : osec->commands)
if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
llvm::erase_if(isd->sections, [&](InputSection *isec) {
return unused.count(isec);
});
llvm::erase_if(script->orphanSections, [&](const InputSectionBase *sec) {
return unused.count(sec);
});
}
template <class ELFT> void Writer<ELFT>::finalizeSections() {
if (!config->relocatable) {
Out::preinitArray = findSection(".preinit_array");
Out::initArray = findSection(".init_array");
Out::finiArray = findSection(".fini_array");
addStartEndSymbols();
for (SectionCommand *cmd : script->sectionCommands)
if (auto *osd = dyn_cast<OutputDesc>(cmd))
addStartStopSymbols(osd->osec);
if (mainPart->dynamic->parent) {
Symbol *s = symtab.addSymbol(Defined{
ctx.internalFile, "_DYNAMIC", STB_WEAK, STV_HIDDEN, STT_NOTYPE,
0, 0, mainPart->dynamic.get()});
s->isUsedInRegularObj = true;
}
addRelIpltSymbols();
if (config->emachine == EM_RISCV) {
ElfSym::riscvGlobalPointer = nullptr;
if (!config->shared) {
OutputSection *sec = findSection(".sdata");
addOptionalRegular(
"__global_pointer$", sec ? sec : Out::elfHeader, 0x800, STV_DEFAULT);
if (config->relaxGP) {
Symbol *s = symtab.find("__global_pointer$");
if (s && s->isDefined())
ElfSym::riscvGlobalPointer = cast<Defined>(s);
}
}
}
if (config->emachine == EM_386 || config->emachine == EM_X86_64) {
Symbol *s = symtab.find("_TLS_MODULE_BASE_");
if (s && s->isUndefined()) {
s->resolve(Defined{ctx.internalFile, StringRef(), STB_GLOBAL,
STV_HIDDEN, STT_TLS, 0, 0,
nullptr});
ElfSym::tlsModuleBase = cast<Defined>(s);
}
}
{
llvm::TimeTraceScope timeScope("Finalize .eh_frame");
for (Partition &part : partitions)
finalizeSynthetic(part.ehFrame.get());
}
}
demoteSymbolsAndComputeIsPreemptible();
if (config->copyRelocs && config->discard != DiscardPolicy::None)
markUsedLocalSymbols<ELFT>();
demoteAndCopyLocalSymbols();
if (config->copyRelocs)
addSectionSymbols();
script->processSymbolAssignments();
if (!config->relocatable) {
llvm::TimeTraceScope timeScope("Scan relocations");
ppc64noTocRelax.clear();
scanRelocations<ELFT>();
reportUndefinedSymbols();
postScanRelocations();
if (in.plt && in.plt->isNeeded())
in.plt->addSymbols();
if (in.iplt && in.iplt->isNeeded())
in.iplt->addSymbols();
if (config->unresolvedSymbolsInShlib != UnresolvedPolicy::Ignore) {
auto diagnose =
config->unresolvedSymbolsInShlib == UnresolvedPolicy::ReportError
? errorOrWarn
: warn;
for (SharedFile *file : ctx.sharedFiles) {
bool allNeededIsKnown =
llvm::all_of(file->dtNeeded, [&](StringRef needed) {
return symtab.soNames.count(CachedHashStringRef(needed));
});
if (!allNeededIsKnown)
continue;
for (Symbol *sym : file->requiredSymbols) {
if (sym->dsoDefined)
continue;
if (sym->isUndefined() && !sym->isWeak()) {
diagnose("undefined reference: " + toString(*sym) +
"\n>>> referenced by " + toString(file) +
" (disallowed by --no-allow-shlib-undefined)");
} else if (sym->isDefined() && sym->computeBinding() == STB_LOCAL) {
diagnose("non-exported symbol '" + toString(*sym) + "' in '" +
toString(sym->file) + "' is referenced by DSO '" +
toString(file) + "'");
}
}
}
}
}
{
llvm::TimeTraceScope timeScope("Add symbols to symtabs");
for (Symbol *sym : symtab.getSymbols()) {
if (!sym->isUsedInRegularObj || !includeInSymtab(*sym))
continue;
if (!config->relocatable)
sym->binding = sym->computeBinding();
if (in.symTab)
in.symTab->addSymbol(sym);
if (sym->includeInDynsym()) {
partitions[sym->partition - 1].dynSymTab->addSymbol(sym);
if (auto *file = dyn_cast_or_null<SharedFile>(sym->file))
if (file->isNeeded && !sym->isUndefined())
addVerneed(sym);
}
}
for (Partition &part : MutableArrayRef<Partition>(partitions).slice(1)) {
DenseSet<Symbol *> syms;
for (const SymbolTableEntry &e : part.dynSymTab->getSymbols())
syms.insert(e.sym);
for (DynamicReloc &reloc : part.relaDyn->relocs)
if (reloc.sym && reloc.needsDynSymIndex() &&
syms.insert(reloc.sym).second)
part.dynSymTab->addSymbol(reloc.sym);
}
}
if (in.mipsGot)
in.mipsGot->build();
removeUnusedSyntheticSections();
script->diagnoseOrphanHandling();
script->diagnoseMissingSGSectionAddress();
sortSections();
for (SectionCommand *cmd : script->sectionCommands)
if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
OutputSection *osec = &osd->osec;
outputSections.push_back(osec);
osec->sectionIndex = outputSections.size();
osec->shName = in.shStrTab->addString(osec->name);
}
for (OutputSection *sec : outputSections) {
auto i = config->sectionStartMap.find(sec->name);
if (i != config->sectionStartMap.end())
sec->addrExpr = [=] { return i->second; };
}
if (config->emachine == EM_HEXAGON && hexagonNeedsTLSSymbol(outputSections)) {
Symbol *sym =
symtab.addSymbol(Undefined{ctx.internalFile, "__tls_get_addr",
STB_GLOBAL, STV_DEFAULT, STT_NOTYPE});
sym->isPreemptible = true;
partitions[0].dynSymTab->addSymbol(sym);
}
Out::elfHeader->sectionIndex = 1;
Out::elfHeader->size = sizeof(typename ELFT::Ehdr);
if (!config->relocatable && !config->oFormatBinary) {
for (Partition &part : partitions) {
part.phdrs = script->hasPhdrsCommands() ? script->createPhdrs()
: createPhdrs(part);
if (config->emachine == EM_ARM) {
addPhdrForSection(part, SHT_ARM_EXIDX, PT_ARM_EXIDX, PF_R);
}
if (config->emachine == EM_MIPS) {
addPhdrForSection(part, SHT_MIPS_REGINFO, PT_MIPS_REGINFO, PF_R);
addPhdrForSection(part, SHT_MIPS_OPTIONS, PT_MIPS_OPTIONS, PF_R);
addPhdrForSection(part, SHT_MIPS_ABIFLAGS, PT_MIPS_ABIFLAGS, PF_R);
}
if (config->emachine == EM_RISCV)
addPhdrForSection(part, SHT_RISCV_ATTRIBUTES, PT_RISCV_ATTRIBUTES,
PF_R);
}
Out::programHeaders->size = sizeof(Elf_Phdr) * mainPart->phdrs.size();
for (PhdrEntry *p : mainPart->phdrs)
if (p->p_type == PT_TLS)
Out::tlsPhdr = p;
}
setReservedSymbolSections();
if (script->noCrossRefs.size()) {
llvm::TimeTraceScope timeScope("Check NOCROSSREFS");
checkNoCrossRefs<ELFT>();
}
{
llvm::TimeTraceScope timeScope("Finalize synthetic sections");
finalizeSynthetic(in.bss.get());
finalizeSynthetic(in.bssRelRo.get());
finalizeSynthetic(in.symTabShndx.get());
finalizeSynthetic(in.shStrTab.get());
finalizeSynthetic(in.strTab.get());
finalizeSynthetic(in.got.get());
finalizeSynthetic(in.mipsGot.get());
finalizeSynthetic(in.igotPlt.get());
finalizeSynthetic(in.gotPlt.get());
finalizeSynthetic(in.relaPlt.get());
finalizeSynthetic(in.plt.get());
finalizeSynthetic(in.iplt.get());
finalizeSynthetic(in.ppc32Got2.get());
finalizeSynthetic(in.partIndex.get());
for (Partition &part : partitions) {
if (part.relaDyn) {
part.relaDyn->mergeRels();
part.relaDyn->partitionRels();
finalizeSynthetic(part.relaDyn.get());
}
if (part.relrDyn) {
part.relrDyn->mergeRels();
finalizeSynthetic(part.relrDyn.get());
}
if (part.relrAuthDyn) {
part.relrAuthDyn->mergeRels();
finalizeSynthetic(part.relrAuthDyn.get());
}
finalizeSynthetic(part.dynSymTab.get());
finalizeSynthetic(part.gnuHashTab.get());
finalizeSynthetic(part.hashTab.get());
finalizeSynthetic(part.verDef.get());
finalizeSynthetic(part.ehFrameHdr.get());
finalizeSynthetic(part.verSym.get());
finalizeSynthetic(part.verNeed.get());
finalizeSynthetic(part.dynamic.get());
}
}
if (!script->hasSectionsCommand && !config->relocatable)
fixSectionAlignments();
finalizeAddressDependentContent();
if (errorCount())
return;
{
llvm::TimeTraceScope timeScope("Finalize synthetic sections");
finalizeSynthetic(in.symTab.get());
finalizeSynthetic(in.debugNames.get());
finalizeSynthetic(in.ppc64LongBranchTarget.get());
finalizeSynthetic(in.armCmseSGSection.get());
}
if (config->optimizeBBJumps)
optimizeBasicBlockJumps();
for (OutputSection *sec : outputSections)
sec->finalize();
script->checkFinalScriptConditions();
if (config->emachine == EM_ARM && !config->isLE && config->armBe8) {
addArmInputSectionMappingSymbols();
sortArmMappingSymbols();
}
}
template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
if (!config->executeOnly)
return;
SmallVector<InputSection *, 0> storage;
for (OutputSection *osec : outputSections)
if (osec->flags & SHF_EXECINSTR)
for (InputSection *isec : getInputSections(*osec, storage))
if (!(isec->flags & SHF_EXECINSTR))
error("cannot place " + toString(isec) + " into " +
toString(osec->name) +
": --execute-only does not support intermingling data and code");
}
template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
auto define = [=](StringRef start, StringRef end, OutputSection *os) {
if (os) {
Defined *startSym = addOptionalRegular(start, os, 0);
Defined *stopSym = addOptionalRegular(end, os, -1);
if (startSym || stopSym)
os->usedInExpression = true;
} else {
addOptionalRegular(start, Out::elfHeader, 0);
addOptionalRegular(end, Out::elfHeader, 0);
}
};
define("__preinit_array_start", "__preinit_array_end", Out::preinitArray);
define("__init_array_start", "__init_array_end", Out::initArray);
define("__fini_array_start", "__fini_array_end", Out::finiArray);
if (OutputSection *sec = findSection(".ARM.exidx"))
define("__exidx_start", "__exidx_end", sec);
}
template <class ELFT>
void Writer<ELFT>::addStartStopSymbols(OutputSection &osec) {
StringRef s = osec.name;
if (!isValidCIdentifier(s))
return;
Defined *startSym = addOptionalRegular(saver().save("__start_" + s), &osec, 0,
config->zStartStopVisibility);
Defined *stopSym = addOptionalRegular(saver().save("__stop_" + s), &osec, -1,
config->zStartStopVisibility);
if (startSym || stopSym)
osec.usedInExpression = true;
}
static bool needsPtLoad(OutputSection *sec) {
if (!(sec->flags & SHF_ALLOC))
return false;
if ((sec->flags & SHF_TLS) && sec->type == SHT_NOBITS)
return false;
return true;
}
static uint64_t computeFlags(uint64_t flags) {
if (config->omagic)
return PF_R | PF_W | PF_X;
if (config->executeOnly && (flags & PF_X))
return flags & ~PF_R;
return flags;
}
template <class ELFT>
SmallVector<PhdrEntry *, 0> Writer<ELFT>::createPhdrs(Partition &part) {
SmallVector<PhdrEntry *, 0> ret;
auto addHdr = [&](unsigned type, unsigned flags) -> PhdrEntry * {
ret.push_back(make<PhdrEntry>(type, flags));
return ret.back();
};
unsigned partNo = part.getNumber();
bool isMain = partNo == 1;
uint64_t flags = computeFlags(PF_R);
PhdrEntry *load = nullptr;
if (!config->nmagic && !config->omagic) {
if (isMain)
addHdr(PT_PHDR, PF_R)->add(Out::programHeaders);
else
addHdr(PT_PHDR, PF_R)->add(part.programHeaders->getParent());
if (OutputSection *cmd = findSection(".interp", partNo))
addHdr(PT_INTERP, cmd->getPhdrFlags())->add(cmd);
if (isMain) {
load = addHdr(PT_LOAD, flags);
load->add(Out::elfHeader);
load->add(Out::programHeaders);
}
}
PhdrEntry *relRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
bool inRelroPhdr = false;
OutputSection *relroEnd = nullptr;
for (OutputSection *sec : outputSections) {
if (sec->partition != partNo || !needsPtLoad(sec))
continue;
if (isRelroSection(sec)) {
inRelroPhdr = true;
if (!relroEnd)
relRo->add(sec);
else
error("section: " + sec->name + " is not contiguous with other relro" +
" sections");
} else if (inRelroPhdr) {
inRelroPhdr = false;
relroEnd = sec;
}
}
relRo->p_align = 1;
for (OutputSection *sec : outputSections) {
if (!needsPtLoad(sec))
continue;
if (sec->partition != partNo) {
if (isMain && sec->partition == 255)
addHdr(PT_LOAD, computeFlags(sec->getPhdrFlags()))->add(sec);
continue;
}
uint64_t newFlags = computeFlags(sec->getPhdrFlags());
uint32_t incompatible = flags ^ newFlags;
if (config->singleRoRx && !(newFlags & PF_W))
incompatible &= ~PF_X;
if (incompatible)
load = nullptr;
bool sameLMARegion =
load && !sec->lmaExpr && sec->lmaRegion == load->firstSec->lmaRegion;
if (load && sec != relroEnd &&
sec->memRegion == load->firstSec->memRegion &&
(sameLMARegion || load->lastSec == Out::programHeaders) &&
(script->hasSectionsCommand || sec->type == SHT_NOBITS ||
load->lastSec->type != SHT_NOBITS)) {
load->p_flags |= newFlags;
} else {
load = addHdr(PT_LOAD, newFlags);
flags = newFlags;
}
load->add(sec);
}
PhdrEntry *tlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
for (OutputSection *sec : outputSections)
if (sec->partition == partNo && sec->flags & SHF_TLS)
tlsHdr->add(sec);
if (tlsHdr->firstSec)
ret.push_back(tlsHdr);
if (OutputSection *sec = part.dynamic->getParent())
addHdr(PT_DYNAMIC, sec->getPhdrFlags())->add(sec);
if (relRo->firstSec)
ret.push_back(relRo);
if (part.ehFrame->isNeeded() && part.ehFrameHdr &&
part.ehFrame->getParent() && part.ehFrameHdr->getParent())
addHdr(PT_GNU_EH_FRAME, part.ehFrameHdr->getParent()->getPhdrFlags())
->add(part.ehFrameHdr->getParent());
if (config->osabi == ELFOSABI_OPENBSD) {
if (OutputSection *cmd = findSection(".openbsd.mutable", partNo))
addHdr(PT_OPENBSD_MUTABLE, cmd->getPhdrFlags())->add(cmd);
if (OutputSection *cmd = findSection(".openbsd.randomdata", partNo))
addHdr(PT_OPENBSD_RANDOMIZE, cmd->getPhdrFlags())->add(cmd);
if (OutputSection *cmd = findSection(".openbsd.syscalls", partNo))
addHdr(PT_OPENBSD_SYSCALLS, cmd->getPhdrFlags())->add(cmd);
}
if (config->zGnustack != GnuStackKind::None) {
unsigned perm = PF_R | PF_W;
if (config->zGnustack == GnuStackKind::Exec)
perm |= PF_X;
addHdr(PT_GNU_STACK, perm)->p_memsz = config->zStackSize;
}
if (config->zWxneeded)
addHdr(PT_OPENBSD_WXNEEDED, PF_X);
if (OutputSection *cmd = findSection(".note.gnu.property", partNo))
addHdr(PT_GNU_PROPERTY, PF_R)->add(cmd);
PhdrEntry *note = nullptr;
for (OutputSection *sec : outputSections) {
if (sec->partition != partNo)
continue;
if (sec->type == SHT_NOTE && (sec->flags & SHF_ALLOC)) {
if (!note || sec->lmaExpr || note->lastSec->addralign != sec->addralign)
note = addHdr(PT_NOTE, PF_R);
note->add(sec);
} else {
note = nullptr;
}
}
return ret;
}
template <class ELFT>
void Writer<ELFT>::addPhdrForSection(Partition &part, unsigned shType,
unsigned pType, unsigned pFlags) {
unsigned partNo = part.getNumber();
auto i = llvm::find_if(outputSections, [=](OutputSection *cmd) {
return cmd->partition == partNo && cmd->type == shType;
});
if (i == outputSections.end())
return;
PhdrEntry *entry = make<PhdrEntry>(pType, pFlags);
entry->add(*i);
part.phdrs.push_back(entry);
}
template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
const PhdrEntry *prev;
auto pageAlign = [&](const PhdrEntry *p) {
OutputSection *cmd = p->firstSec;
if (!cmd)
return;
cmd->alignExpr = [align = cmd->addralign]() { return align; };
if (!cmd->addrExpr) {
if (config->zSeparate == SeparateSegmentKind::Loadable ||
(config->zSeparate == SeparateSegmentKind::Code && prev &&
(prev->p_flags & PF_X) != (p->p_flags & PF_X)) ||
cmd->type == SHT_LLVM_PART_EHDR)
cmd->addrExpr = [] {
return alignToPowerOf2(script->getDot(), config->maxPageSize);
};
else if (Out::tlsPhdr && Out::tlsPhdr->firstSec == p->firstSec)
cmd->addrExpr = [] {
return alignToPowerOf2(script->getDot(), config->maxPageSize) +
alignToPowerOf2(script->getDot() % config->maxPageSize,
Out::tlsPhdr->p_align);
};
else
cmd->addrExpr = [] {
return alignToPowerOf2(script->getDot(), config->maxPageSize) +
script->getDot() % config->maxPageSize;
};
}
};
for (Partition &part : partitions) {
prev = nullptr;
for (const PhdrEntry *p : part.phdrs)
if (p->p_type == PT_LOAD && p->firstSec) {
pageAlign(p);
prev = p;
}
}
}
static uint64_t computeFileOffset(OutputSection *os, uint64_t off) {
if (os->ptLoad && os->ptLoad->firstSec == os)
return alignTo(off, os->ptLoad->p_align, os->addr);
if (os->type == SHT_NOBITS &&
(!Out::tlsPhdr || Out::tlsPhdr->firstSec != os))
return off;
if (!os->ptLoad)
return alignToPowerOf2(off, os->addralign);
OutputSection *first = os->ptLoad->firstSec;
return first->offset + os->addr - first->addr;
}
template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
auto needsOffset = [](OutputSection &sec) {
return sec.type != SHT_NOBITS && (sec.flags & SHF_ALLOC) && sec.size > 0;
};
uint64_t minAddr = UINT64_MAX;
for (OutputSection *sec : outputSections)
if (needsOffset(*sec)) {
sec->offset = sec->getLMA();
minAddr = std::min(minAddr, sec->offset);
}
fileSize = 0;
for (OutputSection *sec : outputSections)
if (needsOffset(*sec)) {
sec->offset -= minAddr;
fileSize = std::max(fileSize, sec->offset + sec->size);
}
}
static std::string rangeToString(uint64_t addr, uint64_t len) {
return "[0x" + utohexstr(addr) + ", 0x" + utohexstr(addr + len - 1) + "]";
}
template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
Out::programHeaders->offset = Out::elfHeader->size;
uint64_t off = Out::elfHeader->size + Out::programHeaders->size;
PhdrEntry *lastRX = nullptr;
for (Partition &part : partitions)
for (PhdrEntry *p : part.phdrs)
if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
lastRX = p;
for (OutputSection *sec : outputSections) {
if (!(sec->flags & SHF_ALLOC))
continue;
off = computeFileOffset(sec, off);
sec->offset = off;
if (sec->type != SHT_NOBITS)
off += sec->size;
if (config->zSeparate != SeparateSegmentKind::None && lastRX &&
lastRX->lastSec == sec)
off = alignToPowerOf2(off, config->maxPageSize);
}
for (OutputSection *osec : outputSections) {
if (osec->flags & SHF_ALLOC)
continue;
osec->offset = alignToPowerOf2(off, osec->addralign);
off = osec->offset + osec->size;
}
sectionHeaderOff = alignToPowerOf2(off, config->wordsize);
fileSize = sectionHeaderOff + (outputSections.size() + 1) * sizeof(Elf_Shdr);
for (OutputSection *sec : outputSections) {
if (sec->type == SHT_NOBITS)
continue;
if ((sec->offset > fileSize) || (sec->offset + sec->size > fileSize))
error("unable to place section " + sec->name + " at file offset " +
rangeToString(sec->offset, sec->size) +
"; check your linker script for overflows");
}
}
template <class ELFT> void Writer<ELFT>::setPhdrs(Partition &part) {
for (PhdrEntry *p : part.phdrs) {
OutputSection *first = p->firstSec;
OutputSection *last = p->lastSec;
if (part.armExidx && p->p_type == PT_ARM_EXIDX) {
p->p_filesz = part.armExidx->getSize();
p->p_memsz = part.armExidx->getSize();
p->p_offset = first->offset + part.armExidx->outSecOff;
p->p_vaddr = first->addr + part.armExidx->outSecOff;
p->p_align = part.armExidx->addralign;
if (part.elfHeader)
p->p_offset -= part.elfHeader->getParent()->offset;
if (!p->hasLMA)
p->p_paddr = first->getLMA() + part.armExidx->outSecOff;
return;
}
if (first) {
p->p_filesz = last->offset - first->offset;
if (last->type != SHT_NOBITS)
p->p_filesz += last->size;
p->p_memsz = last->addr + last->size - first->addr;
p->p_offset = first->offset;
p->p_vaddr = first->addr;
if (part.elfHeader)
p->p_offset -= part.elfHeader->getParent()->offset;
if (!p->hasLMA)
p->p_paddr = first->getLMA();
}
}
}
namespace {
struct SectionOffset {
OutputSection *sec;
uint64_t offset;
};
}
static void checkOverlap(StringRef name, std::vector<SectionOffset> §ions,
bool isVirtualAddr) {
llvm::sort(sections, [=](const SectionOffset &a, const SectionOffset &b) {
return a.offset < b.offset;
});
for (size_t i = 1, end = sections.size(); i < end; ++i) {
SectionOffset a = sections[i - 1];
SectionOffset b = sections[i];
if (b.offset >= a.offset + a.sec->size)
continue;
if (isVirtualAddr && a.sec->inOverlay && b.sec->inOverlay)
continue;
errorOrWarn("section " + a.sec->name + " " + name +
" range overlaps with " + b.sec->name + "\n>>> " + a.sec->name +
" range is " + rangeToString(a.offset, a.sec->size) + "\n>>> " +
b.sec->name + " range is " +
rangeToString(b.offset, b.sec->size));
}
}
template <class ELFT> void Writer<ELFT>::checkSections() {
for (OutputSection *os : outputSections)
if ((os->addr + os->size < os->addr) ||
(!ELFT::Is64Bits && os->addr + os->size > uint64_t(UINT32_MAX) + 1))
errorOrWarn("section " + os->name + " at 0x" + utohexstr(os->addr) +
" of size 0x" + utohexstr(os->size) +
" exceeds available address space");
std::vector<SectionOffset> fileOffs;
for (OutputSection *sec : outputSections)
if (sec->size > 0 && sec->type != SHT_NOBITS &&
(!config->oFormatBinary || (sec->flags & SHF_ALLOC)))
fileOffs.push_back({sec, sec->offset});
checkOverlap("file", fileOffs, false);
if (config->relocatable)
return;
std::vector<SectionOffset> vmas;
for (OutputSection *sec : outputSections)
if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
vmas.push_back({sec, sec->addr});
checkOverlap("virtual address", vmas, true);
std::vector<SectionOffset> lmas;
for (OutputSection *sec : outputSections)
if (sec->size > 0 && (sec->flags & SHF_ALLOC) && !(sec->flags & SHF_TLS))
lmas.push_back({sec, sec->getLMA()});
checkOverlap("load address", lmas, false);
}
static uint64_t getEntryAddr() {
if (Symbol *b = symtab.find(config->entry))
return b->getVA();
uint64_t addr;
if (to_integer(config->entry, addr))
return addr;
if (config->warnMissingEntry)
warn("cannot find entry symbol " + config->entry +
"; not setting start address");
return 0;
}
static uint16_t getELFType() {
if (config->isPic)
return ET_DYN;
if (config->relocatable)
return ET_REL;
return ET_EXEC;
}
template <class ELFT> void Writer<ELFT>::writeHeader() {
writeEhdr<ELFT>(Out::bufferStart, *mainPart);
writePhdrs<ELFT>(Out::bufferStart + sizeof(Elf_Ehdr), *mainPart);
auto *eHdr = reinterpret_cast<Elf_Ehdr *>(Out::bufferStart);
eHdr->e_type = getELFType();
eHdr->e_entry = getEntryAddr();
eHdr->e_shoff = sectionHeaderOff;
auto *sHdrs = reinterpret_cast<Elf_Shdr *>(Out::bufferStart + eHdr->e_shoff);
size_t num = outputSections.size() + 1;
if (num >= SHN_LORESERVE)
sHdrs->sh_size = num;
else
eHdr->e_shnum = num;
uint32_t strTabIndex = in.shStrTab->getParent()->sectionIndex;
if (strTabIndex >= SHN_LORESERVE) {
sHdrs->sh_link = strTabIndex;
eHdr->e_shstrndx = SHN_XINDEX;
} else {
eHdr->e_shstrndx = strTabIndex;
}
for (OutputSection *sec : outputSections)
sec->writeHeaderTo<ELFT>(++sHdrs);
}
template <class ELFT> void Writer<ELFT>::openFile() {
uint64_t maxSize = config->is64 ? INT64_MAX : UINT32_MAX;
if (fileSize != size_t(fileSize) || maxSize < fileSize) {
std::string msg;
raw_string_ostream s(msg);
s << "output file too large: " << Twine(fileSize) << " bytes\n"
<< "section sizes:\n";
for (OutputSection *os : outputSections)
s << os->name << ' ' << os->size << "\n";
error(s.str());
return;
}
unlinkAsync(config->outputFile);
unsigned flags = 0;
if (!config->relocatable)
flags |= FileOutputBuffer::F_executable;
if (!config->mmapOutputFile)
flags |= FileOutputBuffer::F_no_mmap;
Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
FileOutputBuffer::create(config->outputFile, fileSize, flags);
if (!bufferOrErr) {
error("failed to open " + config->outputFile + ": " +
llvm::toString(bufferOrErr.takeError()));
return;
}
buffer = std::move(*bufferOrErr);
Out::bufferStart = buffer->getBufferStart();
}
template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
parallel::TaskGroup tg;
for (OutputSection *sec : outputSections)
if (sec->flags & SHF_ALLOC)
sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);
}
static void fillTrap(uint8_t *i, uint8_t *end) {
for (; i + 4 <= end; i += 4)
memcpy(i, &target->trapInstr, 4);
}
template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
for (Partition &part : partitions) {
for (PhdrEntry *p : part.phdrs)
if (p->p_type == PT_LOAD && (p->p_flags & PF_X))
fillTrap(Out::bufferStart +
alignDown(p->firstSec->offset + p->p_filesz, 4),
Out::bufferStart +
alignToPowerOf2(p->firstSec->offset + p->p_filesz,
config->maxPageSize));
PhdrEntry *last = nullptr;
for (PhdrEntry *p : part.phdrs)
if (p->p_type == PT_LOAD)
last = p;
if (last && (last->p_flags & PF_X))
last->p_memsz = last->p_filesz =
alignToPowerOf2(last->p_filesz, config->maxPageSize);
}
}
template <class ELFT> void Writer<ELFT>::writeSections() {
llvm::TimeTraceScope timeScope("Write sections");
{
parallel::TaskGroup tg;
for (OutputSection *sec : outputSections)
if (isStaticRelSecType(sec->type))
sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);
}
{
parallel::TaskGroup tg;
for (OutputSection *sec : outputSections)
if (!isStaticRelSecType(sec->type))
sec->writeTo<ELFT>(Out::bufferStart + sec->offset, tg);
}
if (config->checkDynamicRelocs && config->writeAddends) {
for (OutputSection *sec : outputSections)
if (isStaticRelSecType(sec->type))
sec->checkDynRelAddends(Out::bufferStart);
}
}
static void
computeHash(llvm::MutableArrayRef<uint8_t> hashBuf,
llvm::ArrayRef<uint8_t> data,
std::function<void(uint8_t *dest, ArrayRef<uint8_t> arr)> hashFn) {
std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
const size_t hashesSize = chunks.size() * hashBuf.size();
std::unique_ptr<uint8_t[]> hashes(new uint8_t[hashesSize]);
parallelFor(0, chunks.size(), [&](size_t i) {
hashFn(hashes.get() + i * hashBuf.size(), chunks[i]);
});
hashFn(hashBuf.data(), ArrayRef(hashes.get(), hashesSize));
}
template <class ELFT> void Writer<ELFT>::writeBuildId() {
if (!mainPart->buildId || !mainPart->buildId->getParent())
return;
if (config->buildId == BuildIdKind::Hexstring) {
for (Partition &part : partitions)
part.buildId->writeBuildId(config->buildIdVector);
return;
}
size_t hashSize = mainPart->buildId->hashSize;
std::unique_ptr<uint8_t[]> buildId(new uint8_t[hashSize]);
MutableArrayRef<uint8_t> output(buildId.get(), hashSize);
llvm::ArrayRef<uint8_t> input{Out::bufferStart, size_t(fileSize)};
switch (config->buildId) {
case BuildIdKind::Fast:
computeHash(output, input, [](uint8_t *dest, ArrayRef<uint8_t> arr) {
write64le(dest, xxh3_64bits(arr));
});
break;
case BuildIdKind::Md5:
computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
memcpy(dest, BLAKE3::hash<16>(arr).data(), hashSize);
});
break;
case BuildIdKind::Sha1:
computeHash(output, input, [&](uint8_t *dest, ArrayRef<uint8_t> arr) {
memcpy(dest, BLAKE3::hash<20>(arr).data(), hashSize);
});
break;
case BuildIdKind::Uuid:
if (auto ec = llvm::getRandomBytes(buildId.get(), hashSize))
error("entropy source failure: " + ec.message());
break;
default:
llvm_unreachable("unknown BuildIdKind");
}
for (Partition &part : partitions)
part.buildId->writeBuildId(output);
}
template void elf::writeResult<ELF32LE>();
template void elf::writeResult<ELF32BE>();
template void elf::writeResult<ELF64LE>();
template void elf::writeResult<ELF64BE>();