brintos

brintos / llvm-project-archived public Read only

0
0
Text · 70.6 KiB · 218c9d3 Raw
1909 lines · cpp
1//===- LinkerScript.cpp ---------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This file contains the parser/evaluator of the linker script.10//11//===----------------------------------------------------------------------===//12 13#include "LinkerScript.h"14#include "Config.h"15#include "InputFiles.h"16#include "InputSection.h"17#include "OutputSections.h"18#include "SymbolTable.h"19#include "Symbols.h"20#include "SyntheticSections.h"21#include "Target.h"22#include "Writer.h"23#include "lld/Common/CommonLinkerContext.h"24#include "lld/Common/Strings.h"25#include "llvm/ADT/STLExtras.h"26#include "llvm/ADT/StringRef.h"27#include "llvm/BinaryFormat/ELF.h"28#include "llvm/Support/Casting.h"29#include "llvm/Support/ErrorHandling.h"30#include "llvm/Support/TimeProfiler.h"31#include <algorithm>32#include <cassert>33#include <cstddef>34#include <cstdint>35#include <limits>36#include <string>37 38using namespace llvm;39using namespace llvm::ELF;40using namespace llvm::object;41using namespace llvm::support::endian;42using namespace lld;43using namespace lld::elf;44 45static bool isSectionPrefix(StringRef prefix, StringRef name) {46  return name.consume_front(prefix) && (name.empty() || name[0] == '.');47}48 49StringRef LinkerScript::getOutputSectionName(const InputSectionBase *s) const {50  // This is for --emit-relocs and -r. If .text.foo is emitted as .text.bar, we51  // want to emit .rela.text.foo as .rela.text.bar for consistency (this is not52  // technically required, but not doing it is odd). This code guarantees that.53  if (auto *isec = dyn_cast<InputSection>(s)) {54    if (InputSectionBase *rel = isec->getRelocatedSection()) {55      OutputSection *out = rel->getOutputSection();56      if (!out) {57        assert(ctx.arg.relocatable && (rel->flags & SHF_LINK_ORDER));58        return s->name;59      }60      StringSaver &ss = ctx.saver;61      if (s->type == SHT_CREL)62        return ss.save(".crel" + out->name);63      if (s->type == SHT_RELA)64        return ss.save(".rela" + out->name);65      return ss.save(".rel" + out->name);66    }67  }68 69  if (ctx.arg.relocatable)70    return s->name;71 72  // A BssSection created for a common symbol is identified as "COMMON" in73  // linker scripts. It should go to .bss section.74  if (s->name == "COMMON")75    return ".bss";76 77  if (hasSectionsCommand)78    return s->name;79 80  // When no SECTIONS is specified, emulate GNU ld's internal linker scripts81  // by grouping sections with certain prefixes.82 83  // GNU ld places text sections with prefix ".text.hot.", ".text.unknown.",84  // ".text.unlikely.", ".text.startup." or ".text.exit." before others.85  // We provide an option -z keep-text-section-prefix to group such sections86  // into separate output sections. This is more flexible. See also87  // sortISDBySectionOrder().88  // ".text.unknown" means the hotness of the section is unknown. When89  // SampleFDO is used, if a function doesn't have sample, it could be very90  // cold or it could be a new function never being sampled. Those functions91  // will be kept in the ".text.unknown" section.92  // ".text.split." holds symbols which are split out from functions in other93  // input sections. For example, with -fsplit-machine-functions, placing the94  // cold parts in .text.split instead of .text.unlikely mitigates against poor95  // profile inaccuracy. Techniques such as hugepage remapping can make96  // conservative decisions at the section granularity.97  if (isSectionPrefix(".text", s->name)) {98    if (ctx.arg.zKeepTextSectionPrefix)99      for (StringRef v : {".text.hot", ".text.unknown", ".text.unlikely",100                          ".text.startup", ".text.exit", ".text.split"})101        if (isSectionPrefix(v.substr(5), s->name.substr(5)))102          return v;103    return ".text";104  }105 106  for (StringRef v : {".data.rel.ro", ".data",       ".rodata",107                      ".bss.rel.ro",  ".bss",        ".ldata",108                      ".lrodata",     ".lbss",       ".gcc_except_table",109                      ".init_array",  ".fini_array", ".tbss",110                      ".tdata",       ".ARM.exidx",  ".ARM.extab",111                      ".ctors",       ".dtors",      ".sbss",112                      ".sdata",       ".srodata"})113    if (isSectionPrefix(v, s->name))114      return v;115 116  return s->name;117}118 119uint64_t ExprValue::getValue() const {120  if (sec)121    return alignToPowerOf2(sec->getOutputSection()->addr + sec->getOffset(val),122                           alignment);123  return alignToPowerOf2(val, alignment);124}125 126uint64_t ExprValue::getSecAddr() const {127  return sec ? sec->getOutputSection()->addr + sec->getOffset(0) : 0;128}129 130uint64_t ExprValue::getSectionOffset() const {131  return getValue() - getSecAddr();132}133 134// std::unique_ptr<OutputSection> may be incomplete type.135LinkerScript::LinkerScript(Ctx &ctx) : ctx(ctx) {}136LinkerScript::~LinkerScript() {}137 138OutputDesc *LinkerScript::createOutputSection(StringRef name,139                                              StringRef location) {140  OutputDesc *&secRef = nameToOutputSection[CachedHashStringRef(name)];141  OutputDesc *sec;142  if (secRef && secRef->osec.location.empty()) {143    // There was a forward reference.144    sec = secRef;145  } else {146    descPool.emplace_back(147        std::make_unique<OutputDesc>(ctx, name, SHT_PROGBITS, 0));148    sec = descPool.back().get();149    if (!secRef)150      secRef = sec;151  }152  sec->osec.location = std::string(location);153  return sec;154}155 156OutputDesc *LinkerScript::getOrCreateOutputSection(StringRef name) {157  auto &secRef = nameToOutputSection[CachedHashStringRef(name)];158  if (!secRef) {159    secRef = descPool160                 .emplace_back(161                     std::make_unique<OutputDesc>(ctx, name, SHT_PROGBITS, 0))162                 .get();163  }164  return secRef;165}166 167// Expands the memory region by the specified size.168static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,169                               StringRef secName) {170  memRegion->curPos += size;171}172 173void LinkerScript::expandMemoryRegions(uint64_t size) {174  if (state->memRegion)175    expandMemoryRegion(state->memRegion, size, state->outSec->name);176  // Only expand the LMARegion if it is different from memRegion.177  if (state->lmaRegion && state->memRegion != state->lmaRegion)178    expandMemoryRegion(state->lmaRegion, size, state->outSec->name);179}180 181void LinkerScript::expandOutputSection(uint64_t size) {182  state->outSec->size += size;183  size_t regionSize = size;184  if (state->outSec->inOverlay) {185    // Expand the overlay if necessary, and expand the region by the186    // corresponding amount.187    if (state->outSec->size > state->overlaySize) {188      regionSize = state->outSec->size - state->overlaySize;189      state->overlaySize = state->outSec->size;190    } else {191      regionSize = 0;192    }193  }194  expandMemoryRegions(regionSize);195}196 197void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {198  uint64_t val = e().getValue();199  // If val is smaller and we are in an output section, record the error and200  // report it if this is the last assignAddresses iteration. dot may be smaller201  // if there is another assignAddresses iteration.202  if (val < dot && inSec) {203    recordError(loc + ": unable to move location counter (0x" +204                Twine::utohexstr(dot) + ") backward to 0x" +205                Twine::utohexstr(val) + " for section '" + state->outSec->name +206                "'");207  }208 209  // Update to location counter means update to section size.210  if (inSec)211    expandOutputSection(val - dot);212 213  dot = val;214}215 216// Used for handling linker symbol assignments, for both finalizing217// their values and doing early declarations. Returns true if symbol218// should be defined from linker script.219static bool shouldDefineSym(Ctx &ctx, SymbolAssignment *cmd) {220  if (cmd->name == ".")221    return false;222 223  return !cmd->provide || ctx.script->shouldAddProvideSym(cmd->name);224}225 226// Called by processSymbolAssignments() to assign definitions to227// linker-script-defined symbols.228void LinkerScript::addSymbol(SymbolAssignment *cmd) {229  if (!shouldDefineSym(ctx, cmd))230    return;231 232  // Define a symbol.233  ExprValue value = cmd->expression();234  SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;235  uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;236 237  // When this function is called, section addresses have not been238  // fixed yet. So, we may or may not know the value of the RHS239  // expression.240  //241  // For example, if an expression is `x = 42`, we know x is always 42.242  // However, if an expression is `x = .`, there's no way to know its243  // value at the moment.244  //245  // We want to set symbol values early if we can. This allows us to246  // use symbols as variables in linker scripts. Doing so allows us to247  // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.248  uint64_t symValue = value.sec ? 0 : value.getValue();249 250  Defined newSym(ctx, createInternalFile(ctx, cmd->location), cmd->name,251                 STB_GLOBAL, visibility, value.type, symValue, 0, sec);252 253  Symbol *sym = ctx.symtab->insert(cmd->name);254  sym->mergeProperties(newSym);255  newSym.overwrite(*sym);256  sym->isUsedInRegularObj = true;257  cmd->sym = cast<Defined>(sym);258}259 260// This function is called from LinkerScript::declareSymbols.261// It creates a placeholder symbol if needed.262void LinkerScript::declareSymbol(SymbolAssignment *cmd) {263  if (!shouldDefineSym(ctx, cmd))264    return;265 266  uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;267  Defined newSym(ctx, ctx.internalFile, cmd->name, STB_GLOBAL, visibility,268                 STT_NOTYPE, 0, 0, nullptr);269 270  // If the symbol is already defined, its order is 0 (with absence indicating271  // 0); otherwise it's assigned the order of the SymbolAssignment.272  Symbol *sym = ctx.symtab->insert(cmd->name);273  if (!sym->isDefined())274    ctx.scriptSymOrder.insert({sym, cmd->symOrder});275 276  // We can't calculate final value right now.277  sym->mergeProperties(newSym);278  newSym.overwrite(*sym);279 280  cmd->sym = cast<Defined>(sym);281  cmd->provide = false;282  sym->isUsedInRegularObj = true;283  sym->scriptDefined = true;284}285 286using SymbolAssignmentMap =287    DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;288 289// Collect section/value pairs of linker-script-defined symbols. This is used to290// check whether symbol values converge.291static SymbolAssignmentMap292getSymbolAssignmentValues(ArrayRef<SectionCommand *> sectionCommands) {293  SymbolAssignmentMap ret;294  for (SectionCommand *cmd : sectionCommands) {295    if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {296      if (assign->sym) // sym is nullptr for dot.297        ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,298                                                    assign->sym->value));299      continue;300    }301    if (isa<SectionClassDesc>(cmd))302      continue;303    for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)304      if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))305        if (assign->sym)306          ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,307                                                      assign->sym->value));308  }309  return ret;310}311 312// Returns the lexicographical smallest (for determinism) Defined whose313// section/value has changed.314static const Defined *315getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {316  const Defined *changed = nullptr;317  for (auto &it : oldValues) {318    const Defined *sym = it.first;319    if (std::make_pair(sym->section, sym->value) != it.second &&320        (!changed || sym->getName() < changed->getName()))321      changed = sym;322  }323  return changed;324}325 326// Process INSERT [AFTER|BEFORE] commands. For each command, we move the327// specified output section to the designated place.328void LinkerScript::processInsertCommands() {329  SmallVector<OutputDesc *, 0> moves;330  for (const InsertCommand &cmd : insertCommands) {331    if (ctx.arg.enableNonContiguousRegions)332      ErrAlways(ctx)333          << "INSERT cannot be used with --enable-non-contiguous-regions";334 335    for (StringRef name : cmd.names) {336      // If base is empty, it may have been discarded by337      // adjustOutputSections(). We do not handle such output sections.338      auto from = llvm::find_if(sectionCommands, [&](SectionCommand *subCmd) {339        return isa<OutputDesc>(subCmd) &&340               cast<OutputDesc>(subCmd)->osec.name == name;341      });342      if (from == sectionCommands.end())343        continue;344      moves.push_back(cast<OutputDesc>(*from));345      sectionCommands.erase(from);346    }347 348    auto insertPos =349        llvm::find_if(sectionCommands, [&cmd](SectionCommand *subCmd) {350          auto *to = dyn_cast<OutputDesc>(subCmd);351          return to != nullptr && to->osec.name == cmd.where;352        });353    if (insertPos == sectionCommands.end()) {354      ErrAlways(ctx) << "unable to insert " << cmd.names[0]355                     << (cmd.isAfter ? " after " : " before ") << cmd.where;356    } else {357      if (cmd.isAfter)358        ++insertPos;359      sectionCommands.insert(insertPos, moves.begin(), moves.end());360    }361    moves.clear();362  }363}364 365// Symbols defined in script should not be inlined by LTO. At the same time366// we don't know their final values until late stages of link. Here we scan367// over symbol assignment commands and create placeholder symbols if needed.368void LinkerScript::declareSymbols() {369  assert(!state);370  for (SectionCommand *cmd : sectionCommands) {371    if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {372      declareSymbol(assign);373      continue;374    }375    if (isa<SectionClassDesc>(cmd))376      continue;377 378    // If the output section directive has constraints,379    // we can't say for sure if it is going to be included or not.380    // Skip such sections for now. Improve the checks if we ever381    // need symbols from that sections to be declared early.382    const OutputSection &sec = cast<OutputDesc>(cmd)->osec;383    if (sec.constraint != ConstraintKind::NoConstraint)384      continue;385    for (SectionCommand *cmd : sec.commands)386      if (auto *assign = dyn_cast<SymbolAssignment>(cmd))387        declareSymbol(assign);388  }389}390 391// This function is called from assignAddresses, while we are392// fixing the output section addresses. This function is supposed393// to set the final value for a given symbol assignment.394void LinkerScript::assignSymbol(SymbolAssignment *cmd, bool inSec) {395  if (cmd->name == ".") {396    setDot(cmd->expression, cmd->location, inSec);397    return;398  }399 400  if (!cmd->sym)401    return;402 403  ExprValue v = cmd->expression();404  if (v.isAbsolute()) {405    cmd->sym->section = nullptr;406    cmd->sym->value = v.getValue();407  } else {408    cmd->sym->section = v.sec;409    cmd->sym->value = v.getSectionOffset();410  }411  cmd->sym->type = v.type;412}413 414bool InputSectionDescription::matchesFile(const InputFile &file) const {415  if (filePat.isTrivialMatchAll())416    return true;417 418  if (!matchesFileCache || matchesFileCache->first != &file) {419    if (matchType == MatchType::WholeArchive) {420      matchesFileCache.emplace(&file, filePat.match(file.archiveName));421    } else {422      if (matchType == MatchType::ArchivesExcluded && !file.archiveName.empty())423        matchesFileCache.emplace(&file, false);424      else425        matchesFileCache.emplace(&file, filePat.match(file.getNameForScript()));426    }427  }428 429  return matchesFileCache->second;430}431 432bool SectionPattern::excludesFile(const InputFile &file) const {433  if (excludedFilePat.empty())434    return false;435 436  if (!excludesFileCache || excludesFileCache->first != &file)437    excludesFileCache.emplace(&file,438                              excludedFilePat.match(file.getNameForScript()));439 440  return excludesFileCache->second;441}442 443bool LinkerScript::shouldKeep(InputSectionBase *s) {444  for (InputSectionDescription *id : keptSections)445    if (id->matchesFile(*s->file))446      for (SectionPattern &p : id->sectionPatterns)447        if (p.sectionPat.match(s->name) &&448            (s->flags & id->withFlags) == id->withFlags &&449            (s->flags & id->withoutFlags) == 0)450          return true;451  return false;452}453 454// A helper function for the SORT() command.455static bool matchConstraints(ArrayRef<InputSectionBase *> sections,456                             ConstraintKind kind) {457  if (kind == ConstraintKind::NoConstraint)458    return true;459 460  bool isRW = llvm::any_of(461      sections, [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; });462 463  return (isRW && kind == ConstraintKind::ReadWrite) ||464         (!isRW && kind == ConstraintKind::ReadOnly);465}466 467static void sortSections(MutableArrayRef<InputSectionBase *> vec,468                         SortSectionPolicy k) {469  auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) {470    // ">" is not a mistake. Sections with larger alignments are placed471    // before sections with smaller alignments in order to reduce the472    // amount of padding necessary. This is compatible with GNU.473    return a->addralign > b->addralign;474  };475  auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) {476    return a->name < b->name;477  };478  auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) {479    return getPriority(a->name) < getPriority(b->name);480  };481 482  switch (k) {483  case SortSectionPolicy::Default:484  case SortSectionPolicy::None:485    return;486  case SortSectionPolicy::Alignment:487    return llvm::stable_sort(vec, alignmentComparator);488  case SortSectionPolicy::Name:489    return llvm::stable_sort(vec, nameComparator);490  case SortSectionPolicy::Priority:491    return llvm::stable_sort(vec, priorityComparator);492  case SortSectionPolicy::Reverse:493    return std::reverse(vec.begin(), vec.end());494  }495}496 497// Sort sections as instructed by SORT-family commands and --sort-section498// option. Because SORT-family commands can be nested at most two depth499// (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command500// line option is respected even if a SORT command is given, the exact501// behavior we have here is a bit complicated. Here are the rules.502//503// 1. If two SORT commands are given, --sort-section is ignored.504// 2. If one SORT command is given, and if it is not SORT_NONE,505//    --sort-section is handled as an inner SORT command.506// 3. If one SORT command is given, and if it is SORT_NONE, don't sort.507// 4. If no SORT command is given, sort according to --sort-section.508static void sortInputSections(Ctx &ctx, MutableArrayRef<InputSectionBase *> vec,509                              SortSectionPolicy outer,510                              SortSectionPolicy inner) {511  if (outer == SortSectionPolicy::None)512    return;513 514  if (inner == SortSectionPolicy::Default)515    sortSections(vec, ctx.arg.sortSection);516  else517    sortSections(vec, inner);518  sortSections(vec, outer);519}520 521// Compute and remember which sections the InputSectionDescription matches.522SmallVector<InputSectionBase *, 0>523LinkerScript::computeInputSections(const InputSectionDescription *cmd,524                                   ArrayRef<InputSectionBase *> sections,525                                   const SectionBase &outCmd) {526  SmallVector<InputSectionBase *, 0> ret;527  DenseSet<InputSectionBase *> spills;528 529  // Returns whether an input section's flags match the input section530  // description's specifiers.531  auto flagsMatch = [cmd](InputSectionBase *sec) {532    return (sec->flags & cmd->withFlags) == cmd->withFlags &&533           (sec->flags & cmd->withoutFlags) == 0;534  };535 536  // Collects all sections that satisfy constraints of Cmd.537  if (cmd->classRef.empty()) {538    DenseSet<size_t> seen;539    size_t sizeAfterPrevSort = 0;540    SmallVector<size_t, 0> indexes;541    auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {542      llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));543      for (size_t i = begin; i != end; ++i)544        ret[i] = sections[indexes[i]];545      sortInputSections(546          ctx,547          MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),548          ctx.arg.sortSection, SortSectionPolicy::None);549    };550 551    for (const SectionPattern &pat : cmd->sectionPatterns) {552      size_t sizeBeforeCurrPat = ret.size();553 554      for (size_t i = 0, e = sections.size(); i != e; ++i) {555        // Skip if the section is dead or has been matched by a previous pattern556        // in this input section description.557        InputSectionBase *sec = sections[i];558        if (!sec->isLive() || seen.contains(i))559          continue;560 561        // For --emit-relocs we have to ignore entries like562        //   .rela.dyn : { *(.rela.data) }563        // which are common because they are in the default bfd script.564        // We do not ignore SHT_REL[A] linker-synthesized sections here because565        // want to support scripts that do custom layout for them.566        if (isa<InputSection>(sec) &&567            cast<InputSection>(sec)->getRelocatedSection())568          continue;569 570        // Check the name early to improve performance in the common case.571        if (!pat.sectionPat.match(sec->name))572          continue;573 574        if (!cmd->matchesFile(*sec->file) || pat.excludesFile(*sec->file) ||575            !flagsMatch(sec))576          continue;577 578        if (sec->parent) {579          // Skip if not allowing multiple matches.580          if (!ctx.arg.enableNonContiguousRegions)581            continue;582 583          // Disallow spilling into /DISCARD/; special handling would be needed584          // for this in address assignment, and the semantics are nebulous.585          if (outCmd.name == "/DISCARD/")586            continue;587 588          // Class definitions cannot contain spills, nor can a class definition589          // generate a spill in a subsequent match. Those behaviors belong to590          // class references and additional matches.591          if (!isa<SectionClass>(outCmd) && !isa<SectionClass>(sec->parent))592            spills.insert(sec);593        }594 595        ret.push_back(sec);596        indexes.push_back(i);597        seen.insert(i);598      }599 600      if (pat.sortOuter == SortSectionPolicy::Default)601        continue;602 603      // Matched sections are ordered by radix sort with the keys being (SORT*,604      // --sort-section, input order), where SORT* (if present) is most605      // significant.606      //607      // Matched sections between the previous SORT* and this SORT* are sorted608      // by (--sort-alignment, input order).609      sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);610      // Matched sections by this SORT* pattern are sorted using all 3 keys.611      // ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we612      // just sort by sortOuter and sortInner.613      sortInputSections(614          ctx,615          MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),616          pat.sortOuter, pat.sortInner);617      sizeAfterPrevSort = ret.size();618    }619 620    // Matched sections after the last SORT* are sorted by (--sort-alignment,621    // input order).622    sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());623  } else {624    SectionClassDesc *scd =625        sectionClasses.lookup(CachedHashStringRef(cmd->classRef));626    if (!scd) {627      Err(ctx) << "undefined section class '" << cmd->classRef << "'";628      return ret;629    }630    if (!scd->sc.assigned) {631      Err(ctx) << "section class '" << cmd->classRef << "' referenced by '"632               << outCmd.name << "' before class definition";633      return ret;634    }635 636    for (InputSectionDescription *isd : scd->sc.commands) {637      for (InputSectionBase *sec : isd->sectionBases) {638        if (!flagsMatch(sec))639          continue;640        bool isSpill = sec->parent && isa<OutputSection>(sec->parent);641        if (!sec->parent || (isSpill && outCmd.name == "/DISCARD/")) {642          Err(ctx) << "section '" << sec->name643                   << "' cannot spill from/to /DISCARD/";644          continue;645        }646        if (isSpill)647          spills.insert(sec);648        ret.push_back(sec);649      }650    }651  }652 653  // The flag --enable-non-contiguous-regions or the section CLASS syntax may654  // cause sections to match an InputSectionDescription in more than one655  // OutputSection. Matches after the first were collected in the spills set, so656  // replace these with potential spill sections.657  if (!spills.empty()) {658    for (InputSectionBase *&sec : ret) {659      if (!spills.contains(sec))660        continue;661 662      // Append the spill input section to the list for the input section,663      // creating it if necessary.664      PotentialSpillSection *pss = make<PotentialSpillSection>(665          *sec, const_cast<InputSectionDescription &>(*cmd));666      auto [it, inserted] =667          potentialSpillLists.try_emplace(sec, PotentialSpillList{pss, pss});668      if (!inserted) {669        PotentialSpillSection *&tail = it->second.tail;670        tail = tail->next = pss;671      }672      sec = pss;673    }674  }675 676  return ret;677}678 679void LinkerScript::discard(InputSectionBase &s) {680  if (&s == ctx.in.shStrTab.get())681    ErrAlways(ctx) << "discarding " << s.name << " section is not allowed";682 683  s.markDead();684  s.parent = nullptr;685  for (InputSection *sec : s.dependentSections)686    discard(*sec);687}688 689void LinkerScript::discardSynthetic(OutputSection &outCmd) {690  for (Partition &part : ctx.partitions) {691    if (!part.armExidx || !part.armExidx->isLive())692      continue;693    SmallVector<InputSectionBase *, 0> secs(694        part.armExidx->exidxSections.begin(),695        part.armExidx->exidxSections.end());696    for (SectionCommand *cmd : outCmd.commands)697      if (auto *isd = dyn_cast<InputSectionDescription>(cmd))698        for (InputSectionBase *s : computeInputSections(isd, secs, outCmd))699          discard(*s);700  }701}702 703SmallVector<InputSectionBase *, 0>704LinkerScript::createInputSectionList(OutputSection &outCmd) {705  SmallVector<InputSectionBase *, 0> ret;706 707  for (SectionCommand *cmd : outCmd.commands) {708    if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {709      isd->sectionBases = computeInputSections(isd, ctx.inputSections, outCmd);710      for (InputSectionBase *s : isd->sectionBases)711        s->parent = &outCmd;712      ret.insert(ret.end(), isd->sectionBases.begin(), isd->sectionBases.end());713    }714  }715  return ret;716}717 718// Create output sections described by SECTIONS commands.719void LinkerScript::processSectionCommands() {720  auto process = [this](OutputSection *osec) {721    SmallVector<InputSectionBase *, 0> v = createInputSectionList(*osec);722 723    // The output section name `/DISCARD/' is special.724    // Any input section assigned to it is discarded.725    if (osec->name == "/DISCARD/") {726      for (InputSectionBase *s : v)727        discard(*s);728      discardSynthetic(*osec);729      osec->commands.clear();730      return false;731    }732 733    // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive734    // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input735    // sections satisfy a given constraint. If not, a directive is handled736    // as if it wasn't present from the beginning.737    //738    // Because we'll iterate over SectionCommands many more times, the easy739    // way to "make it as if it wasn't present" is to make it empty.740    if (!matchConstraints(v, osec->constraint)) {741      for (InputSectionBase *s : v)742        s->parent = nullptr;743      osec->commands.clear();744      return false;745    }746 747    // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign748    // is given, input sections are aligned to that value, whether the749    // given value is larger or smaller than the original section alignment.750    if (osec->subalignExpr) {751      uint32_t subalign = osec->subalignExpr().getValue();752      for (InputSectionBase *s : v)753        s->addralign = subalign;754    }755 756    // Set the partition field the same way OutputSection::recordSection()757    // does. Partitions cannot be used with the SECTIONS command, so this is758    // always 1.759    osec->partition = 1;760    return true;761  };762 763  // Process OVERWRITE_SECTIONS first so that it can overwrite the main script764  // or orphans.765  if (ctx.arg.enableNonContiguousRegions && !overwriteSections.empty())766    ErrAlways(ctx) << "OVERWRITE_SECTIONS cannot be used with "767                      "--enable-non-contiguous-regions";768  DenseMap<CachedHashStringRef, OutputDesc *> map;769  size_t i = 0;770  for (OutputDesc *osd : overwriteSections) {771    OutputSection *osec = &osd->osec;772    if (process(osec) &&773        !map.try_emplace(CachedHashStringRef(osec->name), osd).second)774      Warn(ctx) << "OVERWRITE_SECTIONS specifies duplicate " << osec->name;775  }776  for (SectionCommand *&base : sectionCommands) {777    if (auto *osd = dyn_cast<OutputDesc>(base)) {778      OutputSection *osec = &osd->osec;779      if (OutputDesc *overwrite = map.lookup(CachedHashStringRef(osec->name))) {780        Log(ctx) << overwrite->osec.location << " overwrites " << osec->name;781        overwrite->osec.sectionIndex = i++;782        base = overwrite;783      } else if (process(osec)) {784        osec->sectionIndex = i++;785      }786    } else if (auto *sc = dyn_cast<SectionClassDesc>(base)) {787      for (InputSectionDescription *isd : sc->sc.commands) {788        isd->sectionBases =789            computeInputSections(isd, ctx.inputSections, sc->sc);790        for (InputSectionBase *s : isd->sectionBases) {791          // A section class containing a section with different parent isn't792          // necessarily an error due to --enable-non-contiguous-regions. Such793          // sections all become potential spills when the class is referenced.794          if (!s->parent)795            s->parent = &sc->sc;796        }797      }798      sc->sc.assigned = true;799    }800  }801 802  // Check that input sections cannot spill into or out of INSERT,803  // since the semantics are nebulous. This is also true for OVERWRITE_SECTIONS,804  // but no check is needed, since the order of processing ensures they cannot805  // legally reference classes.806  if (!potentialSpillLists.empty()) {807    DenseSet<StringRef> insertNames;808    for (InsertCommand &ic : insertCommands)809      insertNames.insert_range(ic.names);810    for (SectionCommand *&base : sectionCommands) {811      auto *osd = dyn_cast<OutputDesc>(base);812      if (!osd)813        continue;814      OutputSection *os = &osd->osec;815      if (!insertNames.contains(os->name))816        continue;817      for (SectionCommand *sc : os->commands) {818        auto *isd = dyn_cast<InputSectionDescription>(sc);819        if (!isd)820          continue;821        for (InputSectionBase *isec : isd->sectionBases)822          if (isa<PotentialSpillSection>(isec) ||823              potentialSpillLists.contains(isec))824            Err(ctx) << "section '" << isec->name825                     << "' cannot spill from/to INSERT section '" << os->name826                     << "'";827      }828    }829  }830 831  // If an OVERWRITE_SECTIONS specified output section is not in832  // sectionCommands, append it to the end. The section will be inserted by833  // orphan placement.834  for (OutputDesc *osd : overwriteSections)835    if (osd->osec.partition == 1 && osd->osec.sectionIndex == UINT32_MAX)836      sectionCommands.push_back(osd);837 838  // Input sections cannot have a section class parent past this point; they839  // must have been assigned to an output section.840  for (const auto &[_, sc] : sectionClasses) {841    for (InputSectionDescription *isd : sc->sc.commands) {842      for (InputSectionBase *sec : isd->sectionBases) {843        if (sec->parent && isa<SectionClass>(sec->parent)) {844          Err(ctx) << "section class '" << sec->parent->name845                   << "' is unreferenced";846          goto nextClass;847        }848      }849    }850  nextClass:;851  }852}853 854void LinkerScript::processSymbolAssignments() {855  // Dot outside an output section still represents a relative address, whose856  // sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section857  // that fills the void outside a section. It has an index of one, which is858  // indistinguishable from any other regular section index.859  aether = std::make_unique<OutputSection>(ctx, "", 0, SHF_ALLOC);860  aether->sectionIndex = 1;861 862  // `st` captures the local AddressState and makes it accessible deliberately.863  // This is needed as there are some cases where we cannot just thread the864  // current state through to a lambda function created by the script parser.865  AddressState st(*this);866  state = &st;867  st.outSec = aether.get();868 869  for (SectionCommand *cmd : sectionCommands) {870    if (auto *assign = dyn_cast<SymbolAssignment>(cmd))871      addSymbol(assign);872    else if (auto *osd = dyn_cast<OutputDesc>(cmd))873      for (SectionCommand *subCmd : osd->osec.commands)874        if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))875          addSymbol(assign);876  }877 878  state = nullptr;879}880 881static OutputSection *findByName(ArrayRef<SectionCommand *> vec,882                                 StringRef name) {883  for (SectionCommand *cmd : vec)884    if (auto *osd = dyn_cast<OutputDesc>(cmd))885      if (osd->osec.name == name)886        return &osd->osec;887  return nullptr;888}889 890static OutputDesc *createSection(Ctx &ctx, InputSectionBase *isec,891                                 StringRef outsecName) {892  OutputDesc *osd = ctx.script->createOutputSection(outsecName, "<internal>");893  osd->osec.recordSection(isec);894  return osd;895}896 897static OutputDesc *addInputSec(Ctx &ctx,898                               StringMap<TinyPtrVector<OutputSection *>> &map,899                               InputSectionBase *isec, StringRef outsecName) {900  // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r901  // option is given. A section with SHT_GROUP defines a "section group", and902  // its members have SHF_GROUP attribute. Usually these flags have already been903  // stripped by InputFiles.cpp as section groups are processed and uniquified.904  // However, for the -r option, we want to pass through all section groups905  // as-is because adding/removing members or merging them with other groups906  // change their semantics.907  if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))908    return createSection(ctx, isec, outsecName);909 910  // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have911  // relocation sections .rela.foo and .rela.bar for example. Most tools do912  // not allow multiple REL[A] sections for output section. Hence we913  // should combine these relocation sections into single output.914  // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any915  // other REL[A] sections created by linker itself.916  if (!isa<SyntheticSection>(isec) && isStaticRelSecType(isec->type)) {917    auto *sec = cast<InputSection>(isec);918    OutputSection *out = sec->getRelocatedSection()->getOutputSection();919 920    if (auto *relSec = out->relocationSection) {921      relSec->recordSection(sec);922      return nullptr;923    }924 925    OutputDesc *osd = createSection(ctx, isec, outsecName);926    out->relocationSection = &osd->osec;927    return osd;928  }929 930  //  The ELF spec just says931  // ----------------------------------------------------------------932  // In the first phase, input sections that match in name, type and933  // attribute flags should be concatenated into single sections.934  // ----------------------------------------------------------------935  //936  // However, it is clear that at least some flags have to be ignored for937  // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be938  // ignored. We should not have two output .text sections just because one was939  // in a group and another was not for example.940  //941  // It also seems that wording was a late addition and didn't get the942  // necessary scrutiny.943  //944  // Merging sections with different flags is expected by some users. One945  // reason is that if one file has946  //947  // int *const bar __attribute__((section(".foo"))) = (int *)0;948  //949  // gcc with -fPIC will produce a read only .foo section. But if another950  // file has951  //952  // int zed;953  // int *const bar __attribute__((section(".foo"))) = (int *)&zed;954  //955  // gcc with -fPIC will produce a read write section.956  //957  // Last but not least, when using linker script the merge rules are forced by958  // the script. Unfortunately, linker scripts are name based. This means that959  // expressions like *(.foo*) can refer to multiple input sections with960  // different flags. We cannot put them in different output sections or we961  // would produce wrong results for962  //963  // start = .; *(.foo.*) end = .; *(.bar)964  //965  // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to966  // another. The problem is that there is no way to layout those output967  // sections such that the .foo sections are the only thing between the start968  // and end symbols.969  //970  // Given the above issues, we instead merge sections by name and error on971  // incompatible types and flags.972  TinyPtrVector<OutputSection *> &v = map[outsecName];973  for (OutputSection *sec : v) {974    if (sec->partition != isec->partition)975      continue;976 977    if (ctx.arg.relocatable && (isec->flags & SHF_LINK_ORDER)) {978      // Merging two SHF_LINK_ORDER sections with different sh_link fields will979      // change their semantics, so we only merge them in -r links if they will980      // end up being linked to the same output section. The casts are fine981      // because everything in the map was created by the orphan placement code.982      auto *firstIsec = cast<InputSectionBase>(983          cast<InputSectionDescription>(sec->commands[0])->sectionBases[0]);984      OutputSection *firstIsecOut =985          (firstIsec->flags & SHF_LINK_ORDER)986              ? firstIsec->getLinkOrderDep()->getOutputSection()987              : nullptr;988      if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection())989        continue;990    }991 992    sec->recordSection(isec);993    return nullptr;994  }995 996  OutputDesc *osd = createSection(ctx, isec, outsecName);997  v.push_back(&osd->osec);998  return osd;999}1000 1001// Add sections that didn't match any sections command.1002void LinkerScript::addOrphanSections() {1003  StringMap<TinyPtrVector<OutputSection *>> map;1004  SmallVector<OutputDesc *, 0> v;1005 1006  auto add = [&](InputSectionBase *s) {1007    if (s->isLive() && !s->parent) {1008      orphanSections.push_back(s);1009 1010      StringRef name = getOutputSectionName(s);1011      if (ctx.arg.unique) {1012        v.push_back(createSection(ctx, s, name));1013      } else if (OutputSection *sec = findByName(sectionCommands, name)) {1014        sec->recordSection(s);1015      } else {1016        if (OutputDesc *osd = addInputSec(ctx, map, s, name))1017          v.push_back(osd);1018        assert(isa<MergeInputSection>(s) ||1019               s->getOutputSection()->sectionIndex == UINT32_MAX);1020      }1021    }1022  };1023 1024  size_t n = 0;1025  for (InputSectionBase *isec : ctx.inputSections) {1026    // Process InputSection and MergeInputSection.1027    if (LLVM_LIKELY(isa<InputSection>(isec)))1028      ctx.inputSections[n++] = isec;1029 1030    // In -r links, SHF_LINK_ORDER sections are added while adding their parent1031    // sections because we need to know the parent's output section before we1032    // can select an output section for the SHF_LINK_ORDER section.1033    if (ctx.arg.relocatable && (isec->flags & SHF_LINK_ORDER))1034      continue;1035 1036    if (auto *sec = dyn_cast<InputSection>(isec)) {1037      if (InputSectionBase *relocated = sec->getRelocatedSection()) {1038        // For --emit-relocs and -r, ensure the output section for .text.foo1039        // is created before the output section for .rela.text.foo.1040        add(relocated);1041        // EhInputSection sections are not added to ctx.inputSections. If we see1042        // .rela.eh_frame, ensure the output section for the synthetic1043        // EhFrameSection is created first.1044        if (auto *p = dyn_cast_or_null<InputSectionBase>(relocated->parent))1045          add(p);1046      }1047    }1048    add(isec);1049    if (ctx.arg.relocatable)1050      for (InputSectionBase *depSec : isec->dependentSections)1051        if (depSec->flags & SHF_LINK_ORDER)1052          add(depSec);1053  }1054  // Keep just InputSection.1055  ctx.inputSections.resize(n);1056 1057  // If no SECTIONS command was given, we should insert sections commands1058  // before others, so that we can handle scripts which refers them,1059  // for example: "foo = ABSOLUTE(ADDR(.text)));".1060  // When SECTIONS command is present we just add all orphans to the end.1061  if (hasSectionsCommand)1062    sectionCommands.insert(sectionCommands.end(), v.begin(), v.end());1063  else1064    sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end());1065}1066 1067void LinkerScript::diagnoseOrphanHandling() const {1068  llvm::TimeTraceScope timeScope("Diagnose orphan sections");1069  if (ctx.arg.orphanHandling == OrphanHandlingPolicy::Place ||1070      !hasSectionsCommand)1071    return;1072  for (const InputSectionBase *sec : orphanSections) {1073    // .relro_padding is inserted before DATA_SEGMENT_RELRO_END, if present,1074    // automatically. The section is not supposed to be specified by scripts.1075    if (sec == ctx.in.relroPadding.get())1076      continue;1077    // Input SHT_REL[A] retained by --emit-relocs are ignored by1078    // computeInputSections(). Don't warn/error.1079    if (isa<InputSection>(sec) &&1080        cast<InputSection>(sec)->getRelocatedSection())1081      continue;1082 1083    StringRef name = getOutputSectionName(sec);1084    if (ctx.arg.orphanHandling == OrphanHandlingPolicy::Error)1085      ErrAlways(ctx) << sec << " is being placed in '" << name << "'";1086    else1087      Warn(ctx) << sec << " is being placed in '" << name << "'";1088  }1089}1090 1091void LinkerScript::diagnoseMissingSGSectionAddress() const {1092  if (!ctx.arg.cmseImplib || !ctx.in.armCmseSGSection->isNeeded())1093    return;1094 1095  OutputSection *sec = findByName(sectionCommands, ".gnu.sgstubs");1096  if (sec && !sec->addrExpr && !ctx.arg.sectionStartMap.count(".gnu.sgstubs"))1097    ErrAlways(ctx) << "no address assigned to the veneers output section "1098                   << sec->name;1099}1100 1101// This function searches for a memory region to place the given output1102// section in. If found, a pointer to the appropriate memory region is1103// returned in the first member of the pair. Otherwise, a nullptr is returned.1104// The second member of the pair is a hint that should be passed to the1105// subsequent call of this method.1106std::pair<MemoryRegion *, MemoryRegion *>1107LinkerScript::findMemoryRegion(OutputSection *sec, MemoryRegion *hint) {1108  // Non-allocatable sections are not part of the process image.1109  if (!(sec->flags & SHF_ALLOC)) {1110    bool hasInputOrByteCommand =1111        sec->hasInputSections ||1112        llvm::any_of(sec->commands, [](SectionCommand *comm) {1113          return ByteCommand::classof(comm);1114        });1115    if (!sec->memoryRegionName.empty() && hasInputOrByteCommand)1116      Warn(ctx)1117          << "ignoring memory region assignment for non-allocatable section '"1118          << sec->name << "'";1119    return {nullptr, nullptr};1120  }1121 1122  // If a memory region name was specified in the output section command,1123  // then try to find that region first.1124  if (!sec->memoryRegionName.empty()) {1125    if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName))1126      return {m, m};1127    ErrAlways(ctx) << "memory region '" << sec->memoryRegionName1128                   << "' not declared";1129    return {nullptr, nullptr};1130  }1131 1132  // If at least one memory region is defined, all sections must1133  // belong to some memory region. Otherwise, we don't need to do1134  // anything for memory regions.1135  if (memoryRegions.empty())1136    return {nullptr, nullptr};1137 1138  // An orphan section should continue the previous memory region.1139  if (sec->sectionIndex == UINT32_MAX && hint)1140    return {hint, hint};1141 1142  // See if a region can be found by matching section flags.1143  for (auto &pair : memoryRegions) {1144    MemoryRegion *m = pair.second;1145    if (m->compatibleWith(sec->flags))1146      return {m, nullptr};1147  }1148 1149  // Otherwise, no suitable region was found.1150  ErrAlways(ctx) << "no memory region specified for section '" << sec->name1151                 << "'";1152  return {nullptr, nullptr};1153}1154 1155static OutputSection *findFirstSection(Ctx &ctx, PhdrEntry *load) {1156  for (OutputSection *sec : ctx.outputSections)1157    if (sec->ptLoad == load)1158      return sec;1159  return nullptr;1160}1161 1162// Assign addresses to an output section and offsets to its input sections and1163// symbol assignments. Return true if the output section's address has changed.1164bool LinkerScript::assignOffsets(OutputSection *sec) {1165  const bool isTbss = (sec->flags & SHF_TLS) && sec->type == SHT_NOBITS;1166  const bool sameMemRegion = state->memRegion == sec->memRegion;1167  const bool prevLMARegionIsDefault = state->lmaRegion == nullptr;1168  const uint64_t savedDot = dot;1169  bool addressChanged = false;1170  state->memRegion = sec->memRegion;1171  state->lmaRegion = sec->lmaRegion;1172 1173  if (!(sec->flags & SHF_ALLOC)) {1174    // Non-SHF_ALLOC sections have zero addresses.1175    dot = 0;1176  } else if (isTbss) {1177    // Allow consecutive SHF_TLS SHT_NOBITS output sections. The address range1178    // starts from the end address of the previous tbss section.1179    if (state->tbssAddr == 0)1180      state->tbssAddr = dot;1181    else1182      dot = state->tbssAddr;1183  } else {1184    if (state->memRegion)1185      dot = state->memRegion->curPos;1186    if (sec->addrExpr)1187      setDot(sec->addrExpr, sec->location, false);1188 1189    // If the address of the section has been moved forward by an explicit1190    // expression so that it now starts past the current curPos of the enclosing1191    // region, we need to expand the current region to account for the space1192    // between the previous section, if any, and the start of this section.1193    if (state->memRegion && state->memRegion->curPos < dot)1194      expandMemoryRegion(state->memRegion, dot - state->memRegion->curPos,1195                         sec->name);1196  }1197 1198  state->outSec = sec;1199  if (!(sec->addrExpr && hasSectionsCommand)) {1200    // ALIGN is respected. sec->alignment is the max of ALIGN and the maximum of1201    // input section alignments.1202    const uint64_t pos = dot;1203    dot = alignToPowerOf2(dot, sec->addralign);1204    expandMemoryRegions(dot - pos);1205  }1206  addressChanged = sec->addr != dot;1207  sec->addr = dot;1208 1209  // state->lmaOffset is LMA minus VMA. If LMA is explicitly specified via AT()1210  // or AT>, recompute state->lmaOffset; otherwise, if both previous/current LMA1211  // region is the default, and the two sections are in the same memory region,1212  // reuse previous lmaOffset; otherwise, reset lmaOffset to 0. This emulates1213  // heuristics described in1214  // https://sourceware.org/binutils/docs/ld/Output-Section-LMA.html1215  if (sec->lmaExpr) {1216    state->lmaOffset = sec->lmaExpr().getValue() - dot;1217  } else if (MemoryRegion *mr = sec->lmaRegion) {1218    uint64_t lmaStart = alignToPowerOf2(mr->curPos, sec->addralign);1219    if (mr->curPos < lmaStart)1220      expandMemoryRegion(mr, lmaStart - mr->curPos, sec->name);1221    state->lmaOffset = lmaStart - dot;1222  } else if (!sameMemRegion || !prevLMARegionIsDefault) {1223    state->lmaOffset = 0;1224  }1225 1226  // Propagate state->lmaOffset to the first "non-header" section.1227  if (PhdrEntry *l = sec->ptLoad)1228    if (sec == findFirstSection(ctx, l))1229      l->lmaOffset = state->lmaOffset;1230 1231  // We can call this method multiple times during the creation of1232  // thunks and want to start over calculation each time.1233  sec->size = 0;1234  if (sec->firstInOverlay)1235    state->overlaySize = 0;1236 1237  bool synthesizeAlign =1238      ctx.arg.relocatable && ctx.arg.relax && (sec->flags & SHF_EXECINSTR) &&1239      (ctx.arg.emachine == EM_LOONGARCH || ctx.arg.emachine == EM_RISCV);1240  // We visited SectionsCommands from processSectionCommands to1241  // layout sections. Now, we visit SectionsCommands again to fix1242  // section offsets.1243  for (SectionCommand *cmd : sec->commands) {1244    // This handles the assignments to symbol or to the dot.1245    if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {1246      assign->addr = dot;1247      assignSymbol(assign, true);1248      assign->size = dot - assign->addr;1249      continue;1250    }1251 1252    // Handle BYTE(), SHORT(), LONG(), or QUAD().1253    if (auto *data = dyn_cast<ByteCommand>(cmd)) {1254      data->offset = dot - sec->addr;1255      dot += data->size;1256      expandOutputSection(data->size);1257      continue;1258    }1259 1260    // Handle a single input section description command.1261    // It calculates and assigns the offsets for each section and also1262    // updates the output section size.1263 1264    auto &sections = cast<InputSectionDescription>(cmd)->sections;1265    for (InputSection *isec : sections) {1266      assert(isec->getParent() == sec);1267      if (isa<PotentialSpillSection>(isec))1268        continue;1269      const uint64_t pos = dot;1270      // If synthesized ALIGN may be needed, call maybeSynthesizeAlign and1271      // disable the default handling if the return value is true.1272      if (!(synthesizeAlign && ctx.target->synthesizeAlign(dot, isec)))1273        dot = alignToPowerOf2(dot, isec->addralign);1274      isec->outSecOff = dot - sec->addr;1275      dot += isec->getSize();1276 1277      // Update output section size after adding each section. This is so that1278      // SIZEOF works correctly in the case below:1279      // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }1280      expandOutputSection(dot - pos);1281    }1282  }1283 1284  // If .relro_padding is present, round up the end to a common-page-size1285  // boundary to protect the last page.1286  if (ctx.in.relroPadding && sec == ctx.in.relroPadding->getParent())1287    expandOutputSection(alignToPowerOf2(dot, ctx.arg.commonPageSize) - dot);1288 1289  if (synthesizeAlign) {1290    const uint64_t pos = dot;1291    ctx.target->synthesizeAlign(dot, nullptr);1292    expandOutputSection(dot - pos);1293  }1294 1295  // Non-SHF_ALLOC sections do not affect the addresses of other OutputSections1296  // as they are not part of the process image.1297  if (!(sec->flags & SHF_ALLOC)) {1298    dot = savedDot;1299  } else if (isTbss) {1300    // NOBITS TLS sections are similar. Additionally save the end address.1301    state->tbssAddr = dot;1302    dot = savedDot;1303  }1304  return addressChanged;1305}1306 1307static bool isDiscardable(const OutputSection &sec) {1308  if (sec.name == "/DISCARD/")1309    return true;1310 1311  // We do not want to remove OutputSections with expressions that reference1312  // symbols even if the OutputSection is empty. We want to ensure that the1313  // expressions can be evaluated and report an error if they cannot.1314  if (sec.expressionsUseSymbols)1315    return false;1316 1317  // OutputSections may be referenced by name in ADDR and LOADADDR expressions,1318  // as an empty Section can has a valid VMA and LMA we keep the OutputSection1319  // to maintain the integrity of the other Expression.1320  if (sec.usedInExpression)1321    return false;1322 1323  for (SectionCommand *cmd : sec.commands) {1324    if (auto assign = dyn_cast<SymbolAssignment>(cmd))1325      // Don't create empty output sections just for unreferenced PROVIDE1326      // symbols.1327      if (assign->name != "." && !assign->sym)1328        continue;1329 1330    if (!isa<InputSectionDescription>(*cmd))1331      return false;1332  }1333  return true;1334}1335 1336static void maybePropagatePhdrs(OutputSection &sec,1337                                SmallVector<StringRef, 0> &phdrs) {1338  if (sec.phdrs.empty()) {1339    // To match the bfd linker script behaviour, only propagate program1340    // headers to sections that are allocated.1341    if (sec.flags & SHF_ALLOC)1342      sec.phdrs = phdrs;1343  } else {1344    phdrs = sec.phdrs;1345  }1346}1347 1348void LinkerScript::adjustOutputSections() {1349  // If the output section contains only symbol assignments, create a1350  // corresponding output section. The issue is what to do with linker script1351  // like ".foo : { symbol = 42; }". One option would be to convert it to1352  // "symbol = 42;". That is, move the symbol out of the empty section1353  // description. That seems to be what bfd does for this simple case. The1354  // problem is that this is not completely general. bfd will give up and1355  // create a dummy section too if there is a ". = . + 1" inside the section1356  // for example.1357  // Given that we want to create the section, we have to worry what impact1358  // it will have on the link. For example, if we just create a section with1359  // 0 for flags, it would change which PT_LOADs are created.1360  // We could remember that particular section is dummy and ignore it in1361  // other parts of the linker, but unfortunately there are quite a few places1362  // that would need to change:1363  //   * The program header creation.1364  //   * The orphan section placement.1365  //   * The address assignment.1366  // The other option is to pick flags that minimize the impact the section1367  // will have on the rest of the linker. That is why we copy the flags from1368  // the previous sections. We copy just SHF_ALLOC and SHF_WRITE to keep the1369  // impact low. We do not propagate SHF_EXECINSTR as in some cases this can1370  // lead to executable writeable section.1371  uint64_t flags = SHF_ALLOC;1372 1373  SmallVector<StringRef, 0> defPhdrs;1374  bool seenRelro = false;1375  for (SectionCommand *&cmd : sectionCommands) {1376    if (!isa<OutputDesc>(cmd))1377      continue;1378    auto *sec = &cast<OutputDesc>(cmd)->osec;1379 1380    // Handle align (e.g. ".foo : ALIGN(16) { ... }").1381    if (sec->alignExpr)1382      sec->addralign =1383          std::max<uint32_t>(sec->addralign, sec->alignExpr().getValue());1384 1385    bool isEmpty = (getFirstInputSection(sec) == nullptr);1386    bool discardable = isEmpty && isDiscardable(*sec);1387    // If sec has at least one input section and not discarded, remember its1388    // flags to be inherited by subsequent output sections. (sec may contain1389    // just one empty synthetic section.)1390    if (sec->hasInputSections && !discardable)1391      flags = sec->flags;1392 1393    // We do not want to keep any special flags for output section1394    // in case it is empty.1395    if (isEmpty) {1396      sec->flags =1397          flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) | SHF_WRITE);1398      sec->sortRank = getSectionRank(ctx, *sec);1399    }1400 1401    // The code below may remove empty output sections. We should save the1402    // specified program headers (if exist) and propagate them to subsequent1403    // sections which do not specify program headers.1404    // An example of such a linker script is:1405    // SECTIONS { .empty : { *(.empty) } :rw1406    //            .foo : { *(.foo) } }1407    // Note: at this point the order of output sections has not been finalized,1408    // because orphans have not been inserted into their expected positions. We1409    // will handle them in adjustSectionsAfterSorting().1410    if (sec->sectionIndex != UINT32_MAX)1411      maybePropagatePhdrs(*sec, defPhdrs);1412 1413    // Discard .relro_padding if we have not seen one RELRO section. Note: when1414    // .tbss is the only RELRO section, there is no associated PT_LOAD segment1415    // (needsPtLoad), so we don't append .relro_padding in the case.1416    if (ctx.in.relroPadding && ctx.in.relroPadding->getParent() == sec &&1417        !seenRelro)1418      discardable = true;1419    if (discardable) {1420      sec->markDead();1421      cmd = nullptr;1422    } else {1423      seenRelro |=1424          sec->relro && !(sec->type == SHT_NOBITS && (sec->flags & SHF_TLS));1425    }1426  }1427 1428  // It is common practice to use very generic linker scripts. So for any1429  // given run some of the output sections in the script will be empty.1430  // We could create corresponding empty output sections, but that would1431  // clutter the output.1432  // We instead remove trivially empty sections. The bfd linker seems even1433  // more aggressive at removing them.1434  llvm::erase_if(sectionCommands, [&](SectionCommand *cmd) { return !cmd; });1435}1436 1437void LinkerScript::adjustSectionsAfterSorting() {1438  // Try and find an appropriate memory region to assign offsets in.1439  MemoryRegion *hint = nullptr;1440  for (SectionCommand *cmd : sectionCommands) {1441    if (auto *osd = dyn_cast<OutputDesc>(cmd)) {1442      OutputSection *sec = &osd->osec;1443      if (!sec->lmaRegionName.empty()) {1444        if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName))1445          sec->lmaRegion = m;1446        else1447          ErrAlways(ctx) << "memory region '" << sec->lmaRegionName1448                         << "' not declared";1449      }1450      std::tie(sec->memRegion, hint) = findMemoryRegion(sec, hint);1451    }1452  }1453 1454  // If output section command doesn't specify any segments,1455  // and we haven't previously assigned any section to segment,1456  // then we simply assign section to the very first load segment.1457  // Below is an example of such linker script:1458  // PHDRS { seg PT_LOAD; }1459  // SECTIONS { .aaa : { *(.aaa) } }1460  SmallVector<StringRef, 0> defPhdrs;1461  auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) {1462    return cmd.type == PT_LOAD;1463  });1464  if (firstPtLoad != phdrsCommands.end())1465    defPhdrs.push_back(firstPtLoad->name);1466 1467  // Walk the commands and propagate the program headers to commands that don't1468  // explicitly specify them.1469  for (SectionCommand *cmd : sectionCommands)1470    if (auto *osd = dyn_cast<OutputDesc>(cmd))1471      maybePropagatePhdrs(osd->osec, defPhdrs);1472}1473 1474// When the SECTIONS command is used, try to find an address for the file and1475// program headers output sections, which can be added to the first PT_LOAD1476// segment when program headers are created.1477//1478// We check if the headers fit below the first allocated section. If there isn't1479// enough space for these sections, we'll remove them from the PT_LOAD segment,1480// and we'll also remove the PT_PHDR segment.1481void LinkerScript::allocateHeaders(1482    SmallVector<std::unique_ptr<PhdrEntry>, 0> &phdrs) {1483  uint64_t min = std::numeric_limits<uint64_t>::max();1484  for (OutputSection *sec : ctx.outputSections)1485    if (sec->flags & SHF_ALLOC)1486      min = std::min<uint64_t>(min, sec->addr);1487 1488  auto it = llvm::find_if(phdrs, [](auto &e) { return e->p_type == PT_LOAD; });1489  if (it == phdrs.end())1490    return;1491  PhdrEntry *firstPTLoad = it->get();1492 1493  bool hasExplicitHeaders =1494      llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) {1495        return cmd.hasPhdrs || cmd.hasFilehdr;1496      });1497  bool paged = !ctx.arg.omagic && !ctx.arg.nmagic;1498  uint64_t headerSize = getHeaderSize(ctx);1499 1500  uint64_t base = 0;1501  // If SECTIONS is present and the linkerscript is not explicit about program1502  // headers, only allocate program headers if that would not add a page.1503  if (hasSectionsCommand && !hasExplicitHeaders)1504    base = alignDown(min, ctx.arg.maxPageSize);1505  if ((paged || hasExplicitHeaders) && headerSize <= min - base) {1506    min = alignDown(min - headerSize, ctx.arg.maxPageSize);1507    ctx.out.elfHeader->addr = min;1508    ctx.out.programHeaders->addr = min + ctx.out.elfHeader->size;1509    return;1510  }1511 1512  // Error if we were explicitly asked to allocate headers.1513  if (hasExplicitHeaders)1514    ErrAlways(ctx) << "could not allocate headers";1515 1516  ctx.out.elfHeader->ptLoad = nullptr;1517  ctx.out.programHeaders->ptLoad = nullptr;1518  firstPTLoad->firstSec = findFirstSection(ctx, firstPTLoad);1519 1520  llvm::erase_if(phdrs, [](auto &e) { return e->p_type == PT_PHDR; });1521}1522 1523LinkerScript::AddressState::AddressState(const LinkerScript &script) {1524  for (auto &mri : script.memoryRegions) {1525    MemoryRegion *mr = mri.second;1526    mr->curPos = (mr->origin)().getValue();1527  }1528}1529 1530// Here we assign addresses as instructed by linker script SECTIONS1531// sub-commands. Doing that allows us to use final VA values, so here1532// we also handle rest commands like symbol assignments and ASSERTs.1533// Return an output section that has changed its address or null, and a symbol1534// that has changed its section or value (or nullptr if no symbol has changed).1535std::pair<const OutputSection *, const Defined *>1536LinkerScript::assignAddresses() {1537  if (hasSectionsCommand) {1538    // With a linker script, assignment of addresses to headers is covered by1539    // allocateHeaders().1540    dot = ctx.arg.imageBase.value_or(0);1541  } else {1542    // Assign addresses to headers right now.1543    dot = ctx.target->getImageBase();1544    ctx.out.elfHeader->addr = dot;1545    ctx.out.programHeaders->addr = dot + ctx.out.elfHeader->size;1546    dot += getHeaderSize(ctx);1547  }1548 1549  OutputSection *changedOsec = nullptr;1550  AddressState st(*this);1551  state = &st;1552  errorOnMissingSection = true;1553  st.outSec = aether.get();1554  recordedErrors.clear();1555 1556  SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);1557  for (SectionCommand *cmd : sectionCommands) {1558    if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {1559      assign->addr = dot;1560      assignSymbol(assign, false);1561      assign->size = dot - assign->addr;1562      continue;1563    }1564    if (isa<SectionClassDesc>(cmd))1565      continue;1566    if (assignOffsets(&cast<OutputDesc>(cmd)->osec) && !changedOsec)1567      changedOsec = &cast<OutputDesc>(cmd)->osec;1568  }1569 1570  state = nullptr;1571  return {changedOsec, getChangedSymbolAssignment(oldValues)};1572}1573 1574static bool hasRegionOverflowed(MemoryRegion *mr) {1575  if (!mr)1576    return false;1577  return mr->curPos - mr->getOrigin() > mr->getLength();1578}1579 1580// Spill input sections in reverse order of address assignment to (potentially)1581// bring memory regions out of overflow. The size savings of a spill can only be1582// estimated, since general linker script arithmetic may occur afterwards.1583// Under-estimates may cause unnecessary spills, but over-estimates can always1584// be corrected on the next pass.1585bool LinkerScript::spillSections() {1586  if (potentialSpillLists.empty())1587    return false;1588 1589  DenseSet<PotentialSpillSection *> skippedSpills;1590 1591  bool spilled = false;1592  for (SectionCommand *cmd : reverse(sectionCommands)) {1593    auto *osd = dyn_cast<OutputDesc>(cmd);1594    if (!osd)1595      continue;1596    OutputSection *osec = &osd->osec;1597    if (!osec->memRegion)1598      continue;1599 1600    // Input sections that have replaced a potential spill and should be removed1601    // from their input section description.1602    DenseSet<InputSection *> spilledInputSections;1603 1604    for (SectionCommand *cmd : reverse(osec->commands)) {1605      if (!hasRegionOverflowed(osec->memRegion) &&1606          !hasRegionOverflowed(osec->lmaRegion))1607        break;1608 1609      auto *isd = dyn_cast<InputSectionDescription>(cmd);1610      if (!isd)1611        continue;1612      for (InputSection *isec : reverse(isd->sections)) {1613        // Potential spill locations cannot be spilled.1614        if (isa<PotentialSpillSection>(isec))1615          continue;1616 1617        auto it = potentialSpillLists.find(isec);1618        if (it == potentialSpillLists.end())1619          break;1620 1621        // Consume spills until finding one that might help, then consume it.1622        auto canSpillHelp = [&](PotentialSpillSection *spill) {1623          // Spills to the same region that overflowed cannot help.1624          if (hasRegionOverflowed(osec->memRegion) &&1625              spill->getParent()->memRegion == osec->memRegion)1626            return false;1627          if (hasRegionOverflowed(osec->lmaRegion) &&1628              spill->getParent()->lmaRegion == osec->lmaRegion)1629            return false;1630          return true;1631        };1632        PotentialSpillList &list = it->second;1633        PotentialSpillSection *spill;1634        for (spill = list.head; spill; spill = spill->next) {1635          if (list.head->next)1636            list.head = spill->next;1637          else1638            potentialSpillLists.erase(isec);1639          if (canSpillHelp(spill))1640            break;1641          skippedSpills.insert(spill);1642        }1643        if (!spill)1644          continue;1645 1646        // Replace the next spill location with the spilled section and adjust1647        // its properties to match the new location. Note that the alignment of1648        // the spill section may have diverged from the original due to e.g. a1649        // SUBALIGN. Correct assignment requires the spill's alignment to be1650        // used, not the original.1651        spilledInputSections.insert(isec);1652        *llvm::find(spill->isd->sections, spill) = isec;1653        isec->parent = spill->parent;1654        isec->addralign = spill->addralign;1655 1656        // Record the (potential) reduction in the region's end position.1657        osec->memRegion->curPos -= isec->getSize();1658        if (osec->lmaRegion)1659          osec->lmaRegion->curPos -= isec->getSize();1660 1661        // Spilling continues until the end position no longer overflows the1662        // region. Then, another round of address assignment will either confirm1663        // the spill's success or lead to yet more spilling.1664        if (!hasRegionOverflowed(osec->memRegion) &&1665            !hasRegionOverflowed(osec->lmaRegion))1666          break;1667      }1668 1669      // Remove any spilled input sections to complete their move.1670      if (!spilledInputSections.empty()) {1671        spilled = true;1672        llvm::erase_if(isd->sections, [&](InputSection *isec) {1673          return spilledInputSections.contains(isec);1674        });1675      }1676    }1677  }1678 1679  // Clean up any skipped spills.1680  DenseSet<InputSectionDescription *> isds;1681  for (PotentialSpillSection *s : skippedSpills)1682    isds.insert(s->isd);1683  for (InputSectionDescription *isd : isds)1684    llvm::erase_if(isd->sections, [&](InputSection *s) {1685      return skippedSpills.contains(dyn_cast<PotentialSpillSection>(s));1686    });1687 1688  return spilled;1689}1690 1691// Erase any potential spill sections that were not used.1692void LinkerScript::erasePotentialSpillSections() {1693  if (potentialSpillLists.empty())1694    return;1695 1696  // Collect the set of input section descriptions that contain potential1697  // spills.1698  DenseSet<InputSectionDescription *> isds;1699  for (const auto &[_, list] : potentialSpillLists)1700    for (PotentialSpillSection *s = list.head; s; s = s->next)1701      isds.insert(s->isd);1702 1703  for (InputSectionDescription *isd : isds)1704    llvm::erase_if(isd->sections, [](InputSection *s) {1705      return isa<PotentialSpillSection>(s);1706    });1707 1708  potentialSpillLists.clear();1709}1710 1711// Creates program headers as instructed by PHDRS linker script command.1712SmallVector<std::unique_ptr<PhdrEntry>, 0> LinkerScript::createPhdrs() {1713  SmallVector<std::unique_ptr<PhdrEntry>, 0> ret;1714 1715  // Process PHDRS and FILEHDR keywords because they are not1716  // real output sections and cannot be added in the following loop.1717  for (const PhdrsCommand &cmd : phdrsCommands) {1718    auto phdr =1719        std::make_unique<PhdrEntry>(ctx, cmd.type, cmd.flags.value_or(PF_R));1720 1721    if (cmd.hasFilehdr)1722      phdr->add(ctx.out.elfHeader.get());1723    if (cmd.hasPhdrs)1724      phdr->add(ctx.out.programHeaders.get());1725 1726    if (cmd.lmaExpr) {1727      phdr->p_paddr = cmd.lmaExpr().getValue();1728      phdr->hasLMA = true;1729    }1730    ret.push_back(std::move(phdr));1731  }1732 1733  // Add output sections to program headers.1734  for (OutputSection *sec : ctx.outputSections) {1735    // Assign headers specified by linker script1736    for (size_t id : getPhdrIndices(sec)) {1737      ret[id]->add(sec);1738      if (!phdrsCommands[id].flags)1739        ret[id]->p_flags |= sec->getPhdrFlags();1740    }1741  }1742  return ret;1743}1744 1745// Returns true if we should emit an .interp section.1746//1747// We usually do. But if PHDRS commands are given, and1748// no PT_INTERP is there, there's no place to emit an1749// .interp, so we don't do that in that case.1750bool LinkerScript::needsInterpSection() {1751  if (phdrsCommands.empty())1752    return true;1753  for (PhdrsCommand &cmd : phdrsCommands)1754    if (cmd.type == PT_INTERP)1755      return true;1756  return false;1757}1758 1759ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {1760  if (name == ".") {1761    if (state)1762      return {state->outSec, false, dot - state->outSec->addr, loc};1763    ErrAlways(ctx) << loc << ": unable to get location counter value";1764    return 0;1765  }1766 1767  if (Symbol *sym = ctx.symtab->find(name)) {1768    if (auto *ds = dyn_cast<Defined>(sym)) {1769      ExprValue v{ds->section, false, ds->value, loc};1770      // Retain the original st_type, so that the alias will get the same1771      // behavior in relocation processing. Any operation will reset st_type to1772      // STT_NOTYPE.1773      v.type = ds->type;1774      return v;1775    }1776    if (isa<SharedSymbol>(sym))1777      if (!errorOnMissingSection)1778        return {nullptr, false, 0, loc};1779  }1780 1781  ErrAlways(ctx) << loc << ": symbol not found: " << name;1782  return 0;1783}1784 1785// Returns the index of the segment named Name.1786static std::optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,1787                                          StringRef name) {1788  for (size_t i = 0; i < vec.size(); ++i)1789    if (vec[i].name == name)1790      return i;1791  return std::nullopt;1792}1793 1794// Returns indices of ELF headers containing specific section. Each index is a1795// zero based number of ELF header listed within PHDRS {} script block.1796SmallVector<size_t, 0> LinkerScript::getPhdrIndices(OutputSection *cmd) {1797  SmallVector<size_t, 0> ret;1798 1799  for (StringRef s : cmd->phdrs) {1800    if (std::optional<size_t> idx = getPhdrIndex(phdrsCommands, s))1801      ret.push_back(*idx);1802    else if (s != "NONE")1803      ErrAlways(ctx) << cmd->location << ": program header '" << s1804                     << "' is not listed in PHDRS";1805  }1806  return ret;1807}1808 1809void LinkerScript::printMemoryUsage(raw_ostream& os) {1810  auto printSize = [&](uint64_t size) {1811    if ((size & 0x3fffffff) == 0)1812      os << format_decimal(size >> 30, 10) << " GB";1813    else if ((size & 0xfffff) == 0)1814      os << format_decimal(size >> 20, 10) << " MB";1815    else if ((size & 0x3ff) == 0)1816      os << format_decimal(size >> 10, 10) << " KB";1817    else1818      os << " " << format_decimal(size, 10) << " B";1819  };1820  os << "Memory region         Used Size  Region Size  %age Used\n";1821  for (auto &pair : memoryRegions) {1822    MemoryRegion *m = pair.second;1823    uint64_t usedLength = m->curPos - m->getOrigin();1824    os << right_justify(m->name, 16) << ": ";1825    printSize(usedLength);1826    uint64_t length = m->getLength();1827    if (length != 0) {1828      printSize(length);1829      double percent = usedLength * 100.0 / length;1830      os << "    " << format("%6.2f%%", percent);1831    }1832    os << '\n';1833  }1834}1835 1836void LinkerScript::recordError(const Twine &msg) {1837  auto &str = recordedErrors.emplace_back();1838  msg.toVector(str);1839}1840 1841static void checkMemoryRegion(Ctx &ctx, const MemoryRegion *region,1842                              const OutputSection *osec, uint64_t addr) {1843  uint64_t osecEnd = addr + osec->size;1844  uint64_t regionEnd = region->getOrigin() + region->getLength();1845  if (osecEnd > regionEnd) {1846    ErrAlways(ctx) << "section '" << osec->name << "' will not fit in region '"1847                   << region->name << "': overflowed by "1848                   << (osecEnd - regionEnd) << " bytes";1849  }1850}1851 1852void LinkerScript::checkFinalScriptConditions() const {1853  for (StringRef err : recordedErrors)1854    Err(ctx) << err;1855  for (const OutputSection *sec : ctx.outputSections) {1856    if (const MemoryRegion *memoryRegion = sec->memRegion)1857      checkMemoryRegion(ctx, memoryRegion, sec, sec->addr);1858    if (const MemoryRegion *lmaRegion = sec->lmaRegion)1859      checkMemoryRegion(ctx, lmaRegion, sec, sec->getLMA());1860  }1861}1862 1863void LinkerScript::addScriptReferencedSymbolsToSymTable() {1864  // Some symbols (such as __ehdr_start) are defined lazily only when there1865  // are undefined symbols for them, so we add these to trigger that logic.1866  auto reference = [&ctx = ctx](StringRef name) {1867    Symbol *sym = ctx.symtab->addUnusedUndefined(name);1868    sym->isUsedInRegularObj = true;1869    sym->referenced = true;1870  };1871  for (StringRef name : referencedSymbols)1872    reference(name);1873 1874  // Keeps track of references from which PROVIDE symbols have been added to the1875  // symbol table.1876  DenseSet<StringRef> added;1877  SmallVector<const SmallVector<StringRef, 0> *, 0> symRefsVec;1878  for (const auto &[name, symRefs] : provideMap)1879    if (shouldAddProvideSym(name) && added.insert(name).second)1880      symRefsVec.push_back(&symRefs);1881  while (symRefsVec.size()) {1882    for (StringRef name : *symRefsVec.pop_back_val()) {1883      reference(name);1884      // Prevent the symbol from being discarded by --gc-sections.1885      referencedSymbols.push_back(name);1886      auto it = provideMap.find(name);1887      if (it != provideMap.end() && shouldAddProvideSym(name) &&1888          added.insert(name).second) {1889        symRefsVec.push_back(&it->second);1890      }1891    }1892  }1893}1894 1895bool LinkerScript::shouldAddProvideSym(StringRef symName) {1896  // This function is called before and after garbage collection. To prevent1897  // undefined references from the RHS, the result of this function for a1898  // symbol must be the same for each call. We use unusedProvideSyms to not1899  // change the return value of a demoted symbol.1900  Symbol *sym = ctx.symtab->find(symName);1901  if (!sym)1902    return false;1903  if (sym->isDefined() || sym->isCommon()) {1904    unusedProvideSyms.insert(sym);1905    return false;1906  }1907  return !unusedProvideSyms.count(sym);1908}1909