Path: blob/main/contrib/llvm-project/lld/MachO/ConcatOutputSection.cpp
34878 views
//===- ConcatOutputSection.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 "ConcatOutputSection.h"9#include "Config.h"10#include "OutputSegment.h"11#include "SymbolTable.h"12#include "Symbols.h"13#include "SyntheticSections.h"14#include "Target.h"15#include "lld/Common/CommonLinkerContext.h"16#include "llvm/BinaryFormat/MachO.h"17#include "llvm/Support/ScopedPrinter.h"18#include "llvm/Support/TimeProfiler.h"1920using namespace llvm;21using namespace llvm::MachO;22using namespace lld;23using namespace lld::macho;2425MapVector<NamePair, ConcatOutputSection *> macho::concatOutputSections;2627void ConcatOutputSection::addInput(ConcatInputSection *input) {28assert(input->parent == this);29if (inputs.empty()) {30align = input->align;31flags = input->getFlags();32} else {33align = std::max(align, input->align);34finalizeFlags(input);35}36inputs.push_back(input);37}3839// Branch-range extension can be implemented in two ways, either through ...40//41// (1) Branch islands: Single branch instructions (also of limited range),42// that might be chained in multiple hops to reach the desired43// destination. On ARM64, as 16 branch islands are needed to hop between44// opposite ends of a 2 GiB program. LD64 uses branch islands exclusively,45// even when it needs excessive hops.46//47// (2) Thunks: Instruction(s) to load the destination address into a scratch48// register, followed by a register-indirect branch. Thunks are49// constructed to reach any arbitrary address, so need not be50// chained. Although thunks need not be chained, a program might need51// multiple thunks to the same destination distributed throughout a large52// program so that all call sites can have one within range.53//54// The optimal approach is to mix islands for destinations within two hops,55// and use thunks for destinations at greater distance. For now, we only56// implement thunks. TODO: Adding support for branch islands!57//58// Internally -- as expressed in LLD's data structures -- a59// branch-range-extension thunk consists of:60//61// (1) new Defined symbol for the thunk named62// <FUNCTION>.thunk.<SEQUENCE>, which references ...63// (2) new InputSection, which contains ...64// (3.1) new data for the instructions to load & branch to the far address +65// (3.2) new Relocs on instructions to load the far address, which reference ...66// (4.1) existing Defined symbol for the real function in __text, or67// (4.2) existing DylibSymbol for the real function in a dylib68//69// Nearly-optimal thunk-placement algorithm features:70//71// * Single pass: O(n) on the number of call sites.72//73// * Accounts for the exact space overhead of thunks - no heuristics74//75// * Exploits the full range of call instructions - forward & backward76//77// Data:78//79// * DenseMap<Symbol *, ThunkInfo> thunkMap: Maps the function symbol80// to its thunk bookkeeper.81//82// * struct ThunkInfo (bookkeeper): Call instructions have limited range, and83// distant call sites might be unable to reach the same thunk, so multiple84// thunks are necessary to serve all call sites in a very large program. A85// thunkInfo stores state for all thunks associated with a particular86// function:87// (a) thunk symbol88// (b) input section containing stub code, and89// (c) sequence number for the active thunk incarnation.90// When an old thunk goes out of range, we increment the sequence number and91// create a new thunk named <FUNCTION>.thunk.<SEQUENCE>.92//93// * A thunk consists of94// (a) a Defined symbol pointing to95// (b) an InputSection holding machine code (similar to a MachO stub), and96// (c) relocs referencing the real function for fixing up the stub code.97//98// * std::vector<InputSection *> MergedInputSection::thunks: A vector parallel99// to the inputs vector. We store new thunks via cheap vector append, rather100// than costly insertion into the inputs vector.101//102// Control Flow:103//104// * During address assignment, MergedInputSection::finalize() examines call105// sites by ascending address and creates thunks. When a function is beyond106// the range of a call site, we need a thunk. Place it at the largest107// available forward address from the call site. Call sites increase108// monotonically and thunks are always placed as far forward as possible;109// thus, we place thunks at monotonically increasing addresses. Once a thunk110// is placed, it and all previous input-section addresses are final.111//112// * ConcatInputSection::finalize() and ConcatInputSection::writeTo() merge113// the inputs and thunks vectors (both ordered by ascending address), which114// is simple and cheap.115116DenseMap<Symbol *, ThunkInfo> lld::macho::thunkMap;117118// Determine whether we need thunks, which depends on the target arch -- RISC119// (i.e., ARM) generally does because it has limited-range branch/call120// instructions, whereas CISC (i.e., x86) generally doesn't. RISC only needs121// thunks for programs so large that branch source & destination addresses122// might differ more than the range of branch instruction(s).123bool TextOutputSection::needsThunks() const {124if (!target->usesThunks())125return false;126uint64_t isecAddr = addr;127for (ConcatInputSection *isec : inputs)128isecAddr = alignToPowerOf2(isecAddr, isec->align) + isec->getSize();129if (isecAddr - addr + in.stubs->getSize() <=130std::min(target->backwardBranchRange, target->forwardBranchRange))131return false;132// Yes, this program is large enough to need thunks.133for (ConcatInputSection *isec : inputs) {134for (Reloc &r : isec->relocs) {135if (!target->hasAttr(r.type, RelocAttrBits::BRANCH))136continue;137auto *sym = r.referent.get<Symbol *>();138// Pre-populate the thunkMap and memoize call site counts for every139// InputSection and ThunkInfo. We do this for the benefit of140// estimateStubsInRangeVA().141ThunkInfo &thunkInfo = thunkMap[sym];142// Knowing ThunkInfo call site count will help us know whether or not we143// might need to create more for this referent at the time we are144// estimating distance to __stubs in estimateStubsInRangeVA().145++thunkInfo.callSiteCount;146// We can avoid work on InputSections that have no BRANCH relocs.147isec->hasCallSites = true;148}149}150return true;151}152153// Since __stubs is placed after __text, we must estimate the address154// beyond which stubs are within range of a simple forward branch.155// This is called exactly once, when the last input section has been finalized.156uint64_t TextOutputSection::estimateStubsInRangeVA(size_t callIdx) const {157// Tally the functions which still have call sites remaining to process,158// which yields the maximum number of thunks we might yet place.159size_t maxPotentialThunks = 0;160for (auto &tp : thunkMap) {161ThunkInfo &ti = tp.second;162// This overcounts: Only sections that are in forward jump range from the163// currently-active section get finalized, and all input sections are164// finalized when estimateStubsInRangeVA() is called. So only backward165// jumps will need thunks, but we count all jumps.166if (ti.callSitesUsed < ti.callSiteCount)167maxPotentialThunks += 1;168}169// Tally the total size of input sections remaining to process.170uint64_t isecVA = inputs[callIdx]->getVA();171uint64_t isecEnd = isecVA;172for (size_t i = callIdx; i < inputs.size(); i++) {173InputSection *isec = inputs[i];174isecEnd = alignToPowerOf2(isecEnd, isec->align) + isec->getSize();175}176// Estimate the address after which call sites can safely call stubs177// directly rather than through intermediary thunks.178uint64_t forwardBranchRange = target->forwardBranchRange;179assert(isecEnd > forwardBranchRange &&180"should not run thunk insertion if all code fits in jump range");181assert(isecEnd - isecVA <= forwardBranchRange &&182"should only finalize sections in jump range");183uint64_t stubsInRangeVA = isecEnd + maxPotentialThunks * target->thunkSize +184in.stubs->getSize() - forwardBranchRange;185log("thunks = " + std::to_string(thunkMap.size()) +186", potential = " + std::to_string(maxPotentialThunks) +187", stubs = " + std::to_string(in.stubs->getSize()) + ", isecVA = " +188utohexstr(isecVA) + ", threshold = " + utohexstr(stubsInRangeVA) +189", isecEnd = " + utohexstr(isecEnd) +190", tail = " + utohexstr(isecEnd - isecVA) +191", slop = " + utohexstr(forwardBranchRange - (isecEnd - isecVA)));192return stubsInRangeVA;193}194195void ConcatOutputSection::finalizeOne(ConcatInputSection *isec) {196size = alignToPowerOf2(size, isec->align);197fileSize = alignToPowerOf2(fileSize, isec->align);198isec->outSecOff = size;199isec->isFinal = true;200size += isec->getSize();201fileSize += isec->getFileSize();202}203204void ConcatOutputSection::finalizeContents() {205for (ConcatInputSection *isec : inputs)206finalizeOne(isec);207}208209void TextOutputSection::finalize() {210if (!needsThunks()) {211for (ConcatInputSection *isec : inputs)212finalizeOne(isec);213return;214}215216uint64_t forwardBranchRange = target->forwardBranchRange;217uint64_t backwardBranchRange = target->backwardBranchRange;218uint64_t stubsInRangeVA = TargetInfo::outOfRangeVA;219size_t thunkSize = target->thunkSize;220size_t relocCount = 0;221size_t callSiteCount = 0;222size_t thunkCallCount = 0;223size_t thunkCount = 0;224225// Walk all sections in order. Finalize all sections that are less than226// forwardBranchRange in front of it.227// isecVA is the address of the current section.228// addr + size is the start address of the first non-finalized section.229230// inputs[finalIdx] is for finalization (address-assignment)231size_t finalIdx = 0;232// Kick-off by ensuring that the first input section has an address233for (size_t callIdx = 0, endIdx = inputs.size(); callIdx < endIdx;234++callIdx) {235if (finalIdx == callIdx)236finalizeOne(inputs[finalIdx++]);237ConcatInputSection *isec = inputs[callIdx];238assert(isec->isFinal);239uint64_t isecVA = isec->getVA();240241// Assign addresses up-to the forward branch-range limit.242// Every call instruction needs a small number of bytes (on Arm64: 4),243// and each inserted thunk needs a slightly larger number of bytes244// (on Arm64: 12). If a section starts with a branch instruction and245// contains several branch instructions in succession, then the distance246// from the current position to the position where the thunks are inserted247// grows. So leave room for a bunch of thunks.248unsigned slop = 256 * thunkSize;249while (finalIdx < endIdx) {250uint64_t expectedNewSize =251alignToPowerOf2(addr + size, inputs[finalIdx]->align) +252inputs[finalIdx]->getSize();253if (expectedNewSize >= isecVA + forwardBranchRange - slop)254break;255finalizeOne(inputs[finalIdx++]);256}257258if (!isec->hasCallSites)259continue;260261if (finalIdx == endIdx && stubsInRangeVA == TargetInfo::outOfRangeVA) {262// When we have finalized all input sections, __stubs (destined263// to follow __text) comes within range of forward branches and264// we can estimate the threshold address after which we can265// reach any stub with a forward branch. Note that although it266// sits in the middle of a loop, this code executes only once.267// It is in the loop because we need to call it at the proper268// time: the earliest call site from which the end of __text269// (and start of __stubs) comes within range of a forward branch.270stubsInRangeVA = estimateStubsInRangeVA(callIdx);271}272// Process relocs by ascending address, i.e., ascending offset within isec273std::vector<Reloc> &relocs = isec->relocs;274// FIXME: This property does not hold for object files produced by ld64's275// `-r` mode.276assert(is_sorted(relocs,277[](Reloc &a, Reloc &b) { return a.offset > b.offset; }));278for (Reloc &r : reverse(relocs)) {279++relocCount;280if (!target->hasAttr(r.type, RelocAttrBits::BRANCH))281continue;282++callSiteCount;283// Calculate branch reachability boundaries284uint64_t callVA = isecVA + r.offset;285uint64_t lowVA =286backwardBranchRange < callVA ? callVA - backwardBranchRange : 0;287uint64_t highVA = callVA + forwardBranchRange;288// Calculate our call referent address289auto *funcSym = r.referent.get<Symbol *>();290ThunkInfo &thunkInfo = thunkMap[funcSym];291// The referent is not reachable, so we need to use a thunk ...292if (funcSym->isInStubs() && callVA >= stubsInRangeVA) {293assert(callVA != TargetInfo::outOfRangeVA);294// ... Oh, wait! We are close enough to the end that __stubs295// are now within range of a simple forward branch.296continue;297}298uint64_t funcVA = funcSym->resolveBranchVA();299++thunkInfo.callSitesUsed;300if (lowVA <= funcVA && funcVA <= highVA) {301// The referent is reachable with a simple call instruction.302continue;303}304++thunkInfo.thunkCallCount;305++thunkCallCount;306// If an existing thunk is reachable, use it ...307if (thunkInfo.sym) {308uint64_t thunkVA = thunkInfo.isec->getVA();309if (lowVA <= thunkVA && thunkVA <= highVA) {310r.referent = thunkInfo.sym;311continue;312}313}314// ... otherwise, create a new thunk.315if (addr + size > highVA) {316// There were too many consecutive branch instructions for `slop`317// above. If you hit this: For the current algorithm, just bumping up318// slop above and trying again is probably simplest. (See also PR51578319// comment 5).320fatal(Twine(__FUNCTION__) + ": FIXME: thunk range overrun");321}322thunkInfo.isec =323makeSyntheticInputSection(isec->getSegName(), isec->getName());324thunkInfo.isec->parent = this;325assert(thunkInfo.isec->live);326327StringRef thunkName = saver().save(funcSym->getName() + ".thunk." +328std::to_string(thunkInfo.sequence++));329if (!isa<Defined>(funcSym) || cast<Defined>(funcSym)->isExternal()) {330r.referent = thunkInfo.sym = symtab->addDefined(331thunkName, /*file=*/nullptr, thunkInfo.isec, /*value=*/0, thunkSize,332/*isWeakDef=*/false, /*isPrivateExtern=*/true,333/*isReferencedDynamically=*/false, /*noDeadStrip=*/false,334/*isWeakDefCanBeHidden=*/false);335} else {336r.referent = thunkInfo.sym = make<Defined>(337thunkName, /*file=*/nullptr, thunkInfo.isec, /*value=*/0, thunkSize,338/*isWeakDef=*/false, /*isExternal=*/false, /*isPrivateExtern=*/true,339/*includeInSymtab=*/true, /*isReferencedDynamically=*/false,340/*noDeadStrip=*/false, /*isWeakDefCanBeHidden=*/false);341}342thunkInfo.sym->used = true;343target->populateThunk(thunkInfo.isec, funcSym);344finalizeOne(thunkInfo.isec);345thunks.push_back(thunkInfo.isec);346++thunkCount;347}348}349350log("thunks for " + parent->name + "," + name +351": funcs = " + std::to_string(thunkMap.size()) +352", relocs = " + std::to_string(relocCount) +353", all calls = " + std::to_string(callSiteCount) +354", thunk calls = " + std::to_string(thunkCallCount) +355", thunks = " + std::to_string(thunkCount));356}357358void ConcatOutputSection::writeTo(uint8_t *buf) const {359for (ConcatInputSection *isec : inputs)360isec->writeTo(buf + isec->outSecOff);361}362363void TextOutputSection::writeTo(uint8_t *buf) const {364// Merge input sections from thunk & ordinary vectors365size_t i = 0, ie = inputs.size();366size_t t = 0, te = thunks.size();367while (i < ie || t < te) {368while (i < ie && (t == te || inputs[i]->empty() ||369inputs[i]->outSecOff < thunks[t]->outSecOff)) {370inputs[i]->writeTo(buf + inputs[i]->outSecOff);371++i;372}373while (t < te && (i == ie || thunks[t]->outSecOff < inputs[i]->outSecOff)) {374thunks[t]->writeTo(buf + thunks[t]->outSecOff);375++t;376}377}378}379380void ConcatOutputSection::finalizeFlags(InputSection *input) {381switch (sectionType(input->getFlags())) {382default /*type-unspec'ed*/:383// FIXME: Add additional logic here when supporting emitting obj files.384break;385case S_4BYTE_LITERALS:386case S_8BYTE_LITERALS:387case S_16BYTE_LITERALS:388case S_CSTRING_LITERALS:389case S_ZEROFILL:390case S_LAZY_SYMBOL_POINTERS:391case S_MOD_TERM_FUNC_POINTERS:392case S_THREAD_LOCAL_REGULAR:393case S_THREAD_LOCAL_ZEROFILL:394case S_THREAD_LOCAL_VARIABLES:395case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS:396case S_THREAD_LOCAL_VARIABLE_POINTERS:397case S_NON_LAZY_SYMBOL_POINTERS:398case S_SYMBOL_STUBS:399flags |= input->getFlags();400break;401}402}403404ConcatOutputSection *405ConcatOutputSection::getOrCreateForInput(const InputSection *isec) {406NamePair names = maybeRenameSection({isec->getSegName(), isec->getName()});407ConcatOutputSection *&osec = concatOutputSections[names];408if (!osec) {409if (isec->getSegName() == segment_names::text &&410isec->getName() != section_names::gccExceptTab &&411isec->getName() != section_names::ehFrame)412osec = make<TextOutputSection>(names.second);413else414osec = make<ConcatOutputSection>(names.second);415}416return osec;417}418419NamePair macho::maybeRenameSection(NamePair key) {420auto newNames = config->sectionRenameMap.find(key);421if (newNames != config->sectionRenameMap.end())422return newNames->second;423return key;424}425426427