xref: /freebsd/contrib/llvm-project/lld/ELF/LinkerScript.cpp (revision 52418fc2be8efa5172b90a3a9e617017173612c4)
10b57cec5SDimitry Andric //===- LinkerScript.cpp ---------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains the parser/evaluator of the linker script.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "LinkerScript.h"
140b57cec5SDimitry Andric #include "Config.h"
1581ad6265SDimitry Andric #include "InputFiles.h"
160b57cec5SDimitry Andric #include "InputSection.h"
170b57cec5SDimitry Andric #include "OutputSections.h"
180b57cec5SDimitry Andric #include "SymbolTable.h"
190b57cec5SDimitry Andric #include "Symbols.h"
200b57cec5SDimitry Andric #include "SyntheticSections.h"
210b57cec5SDimitry Andric #include "Target.h"
220b57cec5SDimitry Andric #include "Writer.h"
2304eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
240b57cec5SDimitry Andric #include "lld/Common/Strings.h"
250b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
260b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
270b57cec5SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
280b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
290b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
300b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
31e8d8bef9SDimitry Andric #include "llvm/Support/TimeProfiler.h"
320b57cec5SDimitry Andric #include <algorithm>
330b57cec5SDimitry Andric #include <cassert>
340b57cec5SDimitry Andric #include <cstddef>
350b57cec5SDimitry Andric #include <cstdint>
360b57cec5SDimitry Andric #include <limits>
370b57cec5SDimitry Andric #include <string>
380b57cec5SDimitry Andric #include <vector>
390b57cec5SDimitry Andric 
400b57cec5SDimitry Andric using namespace llvm;
410b57cec5SDimitry Andric using namespace llvm::ELF;
420b57cec5SDimitry Andric using namespace llvm::object;
430b57cec5SDimitry Andric using namespace llvm::support::endian;
445ffd83dbSDimitry Andric using namespace lld;
455ffd83dbSDimitry Andric using namespace lld::elf;
460b57cec5SDimitry Andric 
470fca6ea1SDimitry Andric ScriptWrapper elf::script;
480b57cec5SDimitry Andric 
isSectionPrefix(StringRef prefix,StringRef name)494824e7fdSDimitry Andric static bool isSectionPrefix(StringRef prefix, StringRef name) {
500eae32dcSDimitry Andric   return name.consume_front(prefix) && (name.empty() || name[0] == '.');
514824e7fdSDimitry Andric }
524824e7fdSDimitry Andric 
getOutputSectionName(const InputSectionBase * s)534824e7fdSDimitry Andric static StringRef getOutputSectionName(const InputSectionBase *s) {
545f757f3fSDimitry Andric   // This is for --emit-relocs and -r. If .text.foo is emitted as .text.bar, we
555f757f3fSDimitry Andric   // want to emit .rela.text.foo as .rela.text.bar for consistency (this is not
564824e7fdSDimitry Andric   // technically required, but not doing it is odd). This code guarantees that.
574824e7fdSDimitry Andric   if (auto *isec = dyn_cast<InputSection>(s)) {
584824e7fdSDimitry Andric     if (InputSectionBase *rel = isec->getRelocatedSection()) {
594824e7fdSDimitry Andric       OutputSection *out = rel->getOutputSection();
601db9f3b2SDimitry Andric       if (!out) {
611db9f3b2SDimitry Andric         assert(config->relocatable && (rel->flags & SHF_LINK_ORDER));
621db9f3b2SDimitry Andric         return s->name;
631db9f3b2SDimitry Andric       }
64*52418fc2SDimitry Andric       if (s->type == SHT_CREL)
65*52418fc2SDimitry Andric         return saver().save(".crel" + out->name);
664824e7fdSDimitry Andric       if (s->type == SHT_RELA)
6704eeddc0SDimitry Andric         return saver().save(".rela" + out->name);
6804eeddc0SDimitry Andric       return saver().save(".rel" + out->name);
694824e7fdSDimitry Andric     }
704824e7fdSDimitry Andric   }
714824e7fdSDimitry Andric 
725f757f3fSDimitry Andric   if (config->relocatable)
735f757f3fSDimitry Andric     return s->name;
745f757f3fSDimitry Andric 
754824e7fdSDimitry Andric   // A BssSection created for a common symbol is identified as "COMMON" in
764824e7fdSDimitry Andric   // linker scripts. It should go to .bss section.
774824e7fdSDimitry Andric   if (s->name == "COMMON")
784824e7fdSDimitry Andric     return ".bss";
794824e7fdSDimitry Andric 
804824e7fdSDimitry Andric   if (script->hasSectionsCommand)
814824e7fdSDimitry Andric     return s->name;
824824e7fdSDimitry Andric 
834824e7fdSDimitry Andric   // When no SECTIONS is specified, emulate GNU ld's internal linker scripts
844824e7fdSDimitry Andric   // by grouping sections with certain prefixes.
854824e7fdSDimitry Andric 
864824e7fdSDimitry Andric   // GNU ld places text sections with prefix ".text.hot.", ".text.unknown.",
874824e7fdSDimitry Andric   // ".text.unlikely.", ".text.startup." or ".text.exit." before others.
884824e7fdSDimitry Andric   // We provide an option -z keep-text-section-prefix to group such sections
894824e7fdSDimitry Andric   // into separate output sections. This is more flexible. See also
904824e7fdSDimitry Andric   // sortISDBySectionOrder().
914824e7fdSDimitry Andric   // ".text.unknown" means the hotness of the section is unknown. When
924824e7fdSDimitry Andric   // SampleFDO is used, if a function doesn't have sample, it could be very
934824e7fdSDimitry Andric   // cold or it could be a new function never being sampled. Those functions
944824e7fdSDimitry Andric   // will be kept in the ".text.unknown" section.
954824e7fdSDimitry Andric   // ".text.split." holds symbols which are split out from functions in other
964824e7fdSDimitry Andric   // input sections. For example, with -fsplit-machine-functions, placing the
974824e7fdSDimitry Andric   // cold parts in .text.split instead of .text.unlikely mitigates against poor
984824e7fdSDimitry Andric   // profile inaccuracy. Techniques such as hugepage remapping can make
994824e7fdSDimitry Andric   // conservative decisions at the section granularity.
1000eae32dcSDimitry Andric   if (isSectionPrefix(".text", s->name)) {
1014824e7fdSDimitry Andric     if (config->zKeepTextSectionPrefix)
1020eae32dcSDimitry Andric       for (StringRef v : {".text.hot", ".text.unknown", ".text.unlikely",
1030eae32dcSDimitry Andric                           ".text.startup", ".text.exit", ".text.split"})
1040eae32dcSDimitry Andric         if (isSectionPrefix(v.substr(5), s->name.substr(5)))
1050eae32dcSDimitry Andric           return v;
1060eae32dcSDimitry Andric     return ".text";
1070eae32dcSDimitry Andric   }
1084824e7fdSDimitry Andric 
1094824e7fdSDimitry Andric   for (StringRef v :
11006c3fb27SDimitry Andric        {".data.rel.ro", ".data", ".rodata", ".bss.rel.ro", ".bss", ".ldata",
11106c3fb27SDimitry Andric         ".lrodata", ".lbss", ".gcc_except_table", ".init_array", ".fini_array",
11206c3fb27SDimitry Andric         ".tbss", ".tdata", ".ARM.exidx", ".ARM.extab", ".ctors", ".dtors"})
1134824e7fdSDimitry Andric     if (isSectionPrefix(v, s->name))
1140eae32dcSDimitry Andric       return v;
1154824e7fdSDimitry Andric 
1164824e7fdSDimitry Andric   return s->name;
1170b57cec5SDimitry Andric }
1180b57cec5SDimitry Andric 
getValue() const1190b57cec5SDimitry Andric uint64_t ExprValue::getValue() const {
1200b57cec5SDimitry Andric   if (sec)
121972a253aSDimitry Andric     return alignToPowerOf2(sec->getOutputSection()->addr + sec->getOffset(val),
1220b57cec5SDimitry Andric                            alignment);
123972a253aSDimitry Andric   return alignToPowerOf2(val, alignment);
1240b57cec5SDimitry Andric }
1250b57cec5SDimitry Andric 
getSecAddr() const1260b57cec5SDimitry Andric uint64_t ExprValue::getSecAddr() const {
1274824e7fdSDimitry Andric   return sec ? sec->getOutputSection()->addr + sec->getOffset(0) : 0;
1280b57cec5SDimitry Andric }
1290b57cec5SDimitry Andric 
getSectionOffset() const1300b57cec5SDimitry Andric uint64_t ExprValue::getSectionOffset() const {
1310b57cec5SDimitry Andric   return getValue() - getSecAddr();
1320b57cec5SDimitry Andric }
1330b57cec5SDimitry Andric 
createOutputSection(StringRef name,StringRef location)13481ad6265SDimitry Andric OutputDesc *LinkerScript::createOutputSection(StringRef name,
1350b57cec5SDimitry Andric                                               StringRef location) {
13681ad6265SDimitry Andric   OutputDesc *&secRef = nameToOutputSection[CachedHashStringRef(name)];
13781ad6265SDimitry Andric   OutputDesc *sec;
13881ad6265SDimitry Andric   if (secRef && secRef->osec.location.empty()) {
1390b57cec5SDimitry Andric     // There was a forward reference.
1400b57cec5SDimitry Andric     sec = secRef;
1410b57cec5SDimitry Andric   } else {
14281ad6265SDimitry Andric     sec = make<OutputDesc>(name, SHT_PROGBITS, 0);
1430b57cec5SDimitry Andric     if (!secRef)
1440b57cec5SDimitry Andric       secRef = sec;
1450b57cec5SDimitry Andric   }
14681ad6265SDimitry Andric   sec->osec.location = std::string(location);
1470b57cec5SDimitry Andric   return sec;
1480b57cec5SDimitry Andric }
1490b57cec5SDimitry Andric 
getOrCreateOutputSection(StringRef name)15081ad6265SDimitry Andric OutputDesc *LinkerScript::getOrCreateOutputSection(StringRef name) {
15181ad6265SDimitry Andric   OutputDesc *&cmdRef = nameToOutputSection[CachedHashStringRef(name)];
1520b57cec5SDimitry Andric   if (!cmdRef)
15381ad6265SDimitry Andric     cmdRef = make<OutputDesc>(name, SHT_PROGBITS, 0);
1540b57cec5SDimitry Andric   return cmdRef;
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric // Expands the memory region by the specified size.
expandMemoryRegion(MemoryRegion * memRegion,uint64_t size,StringRef secName)1580b57cec5SDimitry Andric static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,
1594824e7fdSDimitry Andric                                StringRef secName) {
1600b57cec5SDimitry Andric   memRegion->curPos += size;
1610b57cec5SDimitry Andric }
1620b57cec5SDimitry Andric 
expandMemoryRegions(uint64_t size)1630b57cec5SDimitry Andric void LinkerScript::expandMemoryRegions(uint64_t size) {
164bdd1243dSDimitry Andric   if (state->memRegion)
165bdd1243dSDimitry Andric     expandMemoryRegion(state->memRegion, size, state->outSec->name);
1660b57cec5SDimitry Andric   // Only expand the LMARegion if it is different from memRegion.
167bdd1243dSDimitry Andric   if (state->lmaRegion && state->memRegion != state->lmaRegion)
168bdd1243dSDimitry Andric     expandMemoryRegion(state->lmaRegion, size, state->outSec->name);
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric 
expandOutputSection(uint64_t size)1710b57cec5SDimitry Andric void LinkerScript::expandOutputSection(uint64_t size) {
172bdd1243dSDimitry Andric   state->outSec->size += size;
1730b57cec5SDimitry Andric   expandMemoryRegions(size);
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric 
setDot(Expr e,const Twine & loc,bool inSec)1760b57cec5SDimitry Andric void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {
1770b57cec5SDimitry Andric   uint64_t val = e().getValue();
1785f757f3fSDimitry Andric   // If val is smaller and we are in an output section, record the error and
1795f757f3fSDimitry Andric   // report it if this is the last assignAddresses iteration. dot may be smaller
1805f757f3fSDimitry Andric   // if there is another assignAddresses iteration.
1815f757f3fSDimitry Andric   if (val < dot && inSec) {
1820fca6ea1SDimitry Andric     recordError(loc + ": unable to move location counter (0x" +
1830fca6ea1SDimitry Andric                 Twine::utohexstr(dot) + ") backward to 0x" +
1840fca6ea1SDimitry Andric                 Twine::utohexstr(val) + " for section '" + state->outSec->name +
1850fca6ea1SDimitry Andric                 "'");
1865f757f3fSDimitry Andric   }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric   // Update to location counter means update to section size.
1890b57cec5SDimitry Andric   if (inSec)
1900b57cec5SDimitry Andric     expandOutputSection(val - dot);
1910b57cec5SDimitry Andric 
1920b57cec5SDimitry Andric   dot = val;
1930b57cec5SDimitry Andric }
1940b57cec5SDimitry Andric 
1950b57cec5SDimitry Andric // Used for handling linker symbol assignments, for both finalizing
1960b57cec5SDimitry Andric // their values and doing early declarations. Returns true if symbol
1970b57cec5SDimitry Andric // should be defined from linker script.
shouldDefineSym(SymbolAssignment * cmd)1980b57cec5SDimitry Andric static bool shouldDefineSym(SymbolAssignment *cmd) {
1990b57cec5SDimitry Andric   if (cmd->name == ".")
2000b57cec5SDimitry Andric     return false;
2010b57cec5SDimitry Andric 
2020fca6ea1SDimitry Andric   return !cmd->provide || LinkerScript::shouldAddProvideSym(cmd->name);
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric 
20585868e8aSDimitry Andric // Called by processSymbolAssignments() to assign definitions to
20685868e8aSDimitry Andric // linker-script-defined symbols.
addSymbol(SymbolAssignment * cmd)2070b57cec5SDimitry Andric void LinkerScript::addSymbol(SymbolAssignment *cmd) {
2080b57cec5SDimitry Andric   if (!shouldDefineSym(cmd))
2090b57cec5SDimitry Andric     return;
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric   // Define a symbol.
2120b57cec5SDimitry Andric   ExprValue value = cmd->expression();
2130b57cec5SDimitry Andric   SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;
2140b57cec5SDimitry Andric   uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
2150b57cec5SDimitry Andric 
2160b57cec5SDimitry Andric   // When this function is called, section addresses have not been
2170b57cec5SDimitry Andric   // fixed yet. So, we may or may not know the value of the RHS
2180b57cec5SDimitry Andric   // expression.
2190b57cec5SDimitry Andric   //
2200b57cec5SDimitry Andric   // For example, if an expression is `x = 42`, we know x is always 42.
2210b57cec5SDimitry Andric   // However, if an expression is `x = .`, there's no way to know its
2220b57cec5SDimitry Andric   // value at the moment.
2230b57cec5SDimitry Andric   //
2240b57cec5SDimitry Andric   // We want to set symbol values early if we can. This allows us to
2250b57cec5SDimitry Andric   // use symbols as variables in linker scripts. Doing so allows us to
2260b57cec5SDimitry Andric   // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
2270b57cec5SDimitry Andric   uint64_t symValue = value.sec ? 0 : value.getValue();
2280b57cec5SDimitry Andric 
2297a6dacacSDimitry Andric   Defined newSym(createInternalFile(cmd->location), cmd->name, STB_GLOBAL,
2307a6dacacSDimitry Andric                  visibility, value.type, symValue, 0, sec);
2310b57cec5SDimitry Andric 
232bdd1243dSDimitry Andric   Symbol *sym = symtab.insert(cmd->name);
23385868e8aSDimitry Andric   sym->mergeProperties(newSym);
234bdd1243dSDimitry Andric   newSym.overwrite(*sym);
23581ad6265SDimitry Andric   sym->isUsedInRegularObj = true;
2360b57cec5SDimitry Andric   cmd->sym = cast<Defined>(sym);
2370b57cec5SDimitry Andric }
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric // This function is called from LinkerScript::declareSymbols.
2400b57cec5SDimitry Andric // It creates a placeholder symbol if needed.
declareSymbol(SymbolAssignment * cmd)2410b57cec5SDimitry Andric static void declareSymbol(SymbolAssignment *cmd) {
2420b57cec5SDimitry Andric   if (!shouldDefineSym(cmd))
2430b57cec5SDimitry Andric     return;
2440b57cec5SDimitry Andric 
2450b57cec5SDimitry Andric   uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
2467a6dacacSDimitry Andric   Defined newSym(ctx.internalFile, cmd->name, STB_GLOBAL, visibility,
2477a6dacacSDimitry Andric                  STT_NOTYPE, 0, 0, nullptr);
2480b57cec5SDimitry Andric 
2495f757f3fSDimitry Andric   // If the symbol is already defined, its order is 0 (with absence indicating
2505f757f3fSDimitry Andric   // 0); otherwise it's assigned the order of the SymbolAssignment.
251bdd1243dSDimitry Andric   Symbol *sym = symtab.insert(cmd->name);
2525f757f3fSDimitry Andric   if (!sym->isDefined())
2535f757f3fSDimitry Andric     ctx.scriptSymOrder.insert({sym, cmd->symOrder});
2545f757f3fSDimitry Andric 
2555f757f3fSDimitry Andric   // We can't calculate final value right now.
25685868e8aSDimitry Andric   sym->mergeProperties(newSym);
257bdd1243dSDimitry Andric   newSym.overwrite(*sym);
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric   cmd->sym = cast<Defined>(sym);
2600b57cec5SDimitry Andric   cmd->provide = false;
26181ad6265SDimitry Andric   sym->isUsedInRegularObj = true;
2620b57cec5SDimitry Andric   sym->scriptDefined = true;
2630b57cec5SDimitry Andric }
2640b57cec5SDimitry Andric 
26585868e8aSDimitry Andric using SymbolAssignmentMap =
26685868e8aSDimitry Andric     DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;
26785868e8aSDimitry Andric 
26885868e8aSDimitry Andric // Collect section/value pairs of linker-script-defined symbols. This is used to
26985868e8aSDimitry Andric // check whether symbol values converge.
27004eeddc0SDimitry Andric static SymbolAssignmentMap
getSymbolAssignmentValues(ArrayRef<SectionCommand * > sectionCommands)27104eeddc0SDimitry Andric getSymbolAssignmentValues(ArrayRef<SectionCommand *> sectionCommands) {
27285868e8aSDimitry Andric   SymbolAssignmentMap ret;
2734824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands) {
2744824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
2754824e7fdSDimitry Andric       if (assign->sym) // sym is nullptr for dot.
2764824e7fdSDimitry Andric         ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
2774824e7fdSDimitry Andric                                                     assign->sym->value));
27885868e8aSDimitry Andric       continue;
27985868e8aSDimitry Andric     }
28081ad6265SDimitry Andric     for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)
2814824e7fdSDimitry Andric       if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
2824824e7fdSDimitry Andric         if (assign->sym)
2834824e7fdSDimitry Andric           ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
2844824e7fdSDimitry Andric                                                       assign->sym->value));
28585868e8aSDimitry Andric   }
28685868e8aSDimitry Andric   return ret;
28785868e8aSDimitry Andric }
28885868e8aSDimitry Andric 
28985868e8aSDimitry Andric // Returns the lexicographical smallest (for determinism) Defined whose
29085868e8aSDimitry Andric // section/value has changed.
29185868e8aSDimitry Andric static const Defined *
getChangedSymbolAssignment(const SymbolAssignmentMap & oldValues)29285868e8aSDimitry Andric getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {
29385868e8aSDimitry Andric   const Defined *changed = nullptr;
29485868e8aSDimitry Andric   for (auto &it : oldValues) {
29585868e8aSDimitry Andric     const Defined *sym = it.first;
29685868e8aSDimitry Andric     if (std::make_pair(sym->section, sym->value) != it.second &&
29785868e8aSDimitry Andric         (!changed || sym->getName() < changed->getName()))
29885868e8aSDimitry Andric       changed = sym;
29985868e8aSDimitry Andric   }
30085868e8aSDimitry Andric   return changed;
30185868e8aSDimitry Andric }
30285868e8aSDimitry Andric 
3035ffd83dbSDimitry Andric // Process INSERT [AFTER|BEFORE] commands. For each command, we move the
3045ffd83dbSDimitry Andric // specified output section to the designated place.
processInsertCommands()3050b57cec5SDimitry Andric void LinkerScript::processInsertCommands() {
30681ad6265SDimitry Andric   SmallVector<OutputDesc *, 0> moves;
3075ffd83dbSDimitry Andric   for (const InsertCommand &cmd : insertCommands) {
3080fca6ea1SDimitry Andric     if (config->enableNonContiguousRegions)
3090fca6ea1SDimitry Andric       error("INSERT cannot be used with --enable-non-contiguous-regions");
3100fca6ea1SDimitry Andric 
311fe6060f1SDimitry Andric     for (StringRef name : cmd.names) {
312fe6060f1SDimitry Andric       // If base is empty, it may have been discarded by
3131fd87a68SDimitry Andric       // adjustOutputSections(). We do not handle such output sections.
3144824e7fdSDimitry Andric       auto from = llvm::find_if(sectionCommands, [&](SectionCommand *subCmd) {
31581ad6265SDimitry Andric         return isa<OutputDesc>(subCmd) &&
31681ad6265SDimitry Andric                cast<OutputDesc>(subCmd)->osec.name == name;
317fe6060f1SDimitry Andric       });
3185ffd83dbSDimitry Andric       if (from == sectionCommands.end())
3190b57cec5SDimitry Andric         continue;
32081ad6265SDimitry Andric       moves.push_back(cast<OutputDesc>(*from));
3215ffd83dbSDimitry Andric       sectionCommands.erase(from);
322fe6060f1SDimitry Andric     }
3230b57cec5SDimitry Andric 
3244824e7fdSDimitry Andric     auto insertPos =
3254824e7fdSDimitry Andric         llvm::find_if(sectionCommands, [&cmd](SectionCommand *subCmd) {
32681ad6265SDimitry Andric           auto *to = dyn_cast<OutputDesc>(subCmd);
32781ad6265SDimitry Andric           return to != nullptr && to->osec.name == cmd.where;
3285ffd83dbSDimitry Andric         });
3295ffd83dbSDimitry Andric     if (insertPos == sectionCommands.end()) {
330fe6060f1SDimitry Andric       error("unable to insert " + cmd.names[0] +
3315ffd83dbSDimitry Andric             (cmd.isAfter ? " after " : " before ") + cmd.where);
3325ffd83dbSDimitry Andric     } else {
3335ffd83dbSDimitry Andric       if (cmd.isAfter)
3345ffd83dbSDimitry Andric         ++insertPos;
335fe6060f1SDimitry Andric       sectionCommands.insert(insertPos, moves.begin(), moves.end());
3365ffd83dbSDimitry Andric     }
337fe6060f1SDimitry Andric     moves.clear();
3385ffd83dbSDimitry Andric   }
3390b57cec5SDimitry Andric }
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric // Symbols defined in script should not be inlined by LTO. At the same time
3420b57cec5SDimitry Andric // we don't know their final values until late stages of link. Here we scan
3430b57cec5SDimitry Andric // over symbol assignment commands and create placeholder symbols if needed.
declareSymbols()3440b57cec5SDimitry Andric void LinkerScript::declareSymbols() {
345bdd1243dSDimitry Andric   assert(!state);
3464824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands) {
3474824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
3484824e7fdSDimitry Andric       declareSymbol(assign);
3490b57cec5SDimitry Andric       continue;
3500b57cec5SDimitry Andric     }
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric     // If the output section directive has constraints,
3530b57cec5SDimitry Andric     // we can't say for sure if it is going to be included or not.
3540b57cec5SDimitry Andric     // Skip such sections for now. Improve the checks if we ever
3550b57cec5SDimitry Andric     // need symbols from that sections to be declared early.
35681ad6265SDimitry Andric     const OutputSection &sec = cast<OutputDesc>(cmd)->osec;
35781ad6265SDimitry Andric     if (sec.constraint != ConstraintKind::NoConstraint)
3580b57cec5SDimitry Andric       continue;
35981ad6265SDimitry Andric     for (SectionCommand *cmd : sec.commands)
3604824e7fdSDimitry Andric       if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
3614824e7fdSDimitry Andric         declareSymbol(assign);
3620b57cec5SDimitry Andric   }
3630b57cec5SDimitry Andric }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric // This function is called from assignAddresses, while we are
3660b57cec5SDimitry Andric // fixing the output section addresses. This function is supposed
3670b57cec5SDimitry Andric // to set the final value for a given symbol assignment.
assignSymbol(SymbolAssignment * cmd,bool inSec)3680b57cec5SDimitry Andric void LinkerScript::assignSymbol(SymbolAssignment *cmd, bool inSec) {
3690b57cec5SDimitry Andric   if (cmd->name == ".") {
3700b57cec5SDimitry Andric     setDot(cmd->expression, cmd->location, inSec);
3710b57cec5SDimitry Andric     return;
3720b57cec5SDimitry Andric   }
3730b57cec5SDimitry Andric 
3740b57cec5SDimitry Andric   if (!cmd->sym)
3750b57cec5SDimitry Andric     return;
3760b57cec5SDimitry Andric 
3770b57cec5SDimitry Andric   ExprValue v = cmd->expression();
3780b57cec5SDimitry Andric   if (v.isAbsolute()) {
3790b57cec5SDimitry Andric     cmd->sym->section = nullptr;
3800b57cec5SDimitry Andric     cmd->sym->value = v.getValue();
3810b57cec5SDimitry Andric   } else {
3820b57cec5SDimitry Andric     cmd->sym->section = v.sec;
3830b57cec5SDimitry Andric     cmd->sym->value = v.getSectionOffset();
3840b57cec5SDimitry Andric   }
38516d6b3b3SDimitry Andric   cmd->sym->type = v.type;
3860b57cec5SDimitry Andric }
3870b57cec5SDimitry Andric 
getFilename(const InputFile * file)388e8d8bef9SDimitry Andric static inline StringRef getFilename(const InputFile *file) {
389e8d8bef9SDimitry Andric   return file ? file->getNameForScript() : StringRef();
390e8d8bef9SDimitry Andric }
391e8d8bef9SDimitry Andric 
matchesFile(const InputFile * file) const392e8d8bef9SDimitry Andric bool InputSectionDescription::matchesFile(const InputFile *file) const {
393e8d8bef9SDimitry Andric   if (filePat.isTrivialMatchAll())
394e8d8bef9SDimitry Andric     return true;
395e8d8bef9SDimitry Andric 
396e8d8bef9SDimitry Andric   if (!matchesFileCache || matchesFileCache->first != file)
397e8d8bef9SDimitry Andric     matchesFileCache.emplace(file, filePat.match(getFilename(file)));
398e8d8bef9SDimitry Andric 
399e8d8bef9SDimitry Andric   return matchesFileCache->second;
400e8d8bef9SDimitry Andric }
401e8d8bef9SDimitry Andric 
excludesFile(const InputFile * file) const402e8d8bef9SDimitry Andric bool SectionPattern::excludesFile(const InputFile *file) const {
403e8d8bef9SDimitry Andric   if (excludedFilePat.empty())
404e8d8bef9SDimitry Andric     return false;
405e8d8bef9SDimitry Andric 
406e8d8bef9SDimitry Andric   if (!excludesFileCache || excludesFileCache->first != file)
407e8d8bef9SDimitry Andric     excludesFileCache.emplace(file, excludedFilePat.match(getFilename(file)));
408e8d8bef9SDimitry Andric 
409e8d8bef9SDimitry Andric   return excludesFileCache->second;
4100b57cec5SDimitry Andric }
4110b57cec5SDimitry Andric 
shouldKeep(InputSectionBase * s)4120b57cec5SDimitry Andric bool LinkerScript::shouldKeep(InputSectionBase *s) {
4130b57cec5SDimitry Andric   for (InputSectionDescription *id : keptSections)
414e8d8bef9SDimitry Andric     if (id->matchesFile(s->file))
4150b57cec5SDimitry Andric       for (SectionPattern &p : id->sectionPatterns)
4165ffd83dbSDimitry Andric         if (p.sectionPat.match(s->name) &&
4175ffd83dbSDimitry Andric             (s->flags & id->withFlags) == id->withFlags &&
4185ffd83dbSDimitry Andric             (s->flags & id->withoutFlags) == 0)
4190b57cec5SDimitry Andric           return true;
4200b57cec5SDimitry Andric   return false;
4210b57cec5SDimitry Andric }
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric // A helper function for the SORT() command.
matchConstraints(ArrayRef<InputSectionBase * > sections,ConstraintKind kind)42485868e8aSDimitry Andric static bool matchConstraints(ArrayRef<InputSectionBase *> sections,
4250b57cec5SDimitry Andric                              ConstraintKind kind) {
4260b57cec5SDimitry Andric   if (kind == ConstraintKind::NoConstraint)
4270b57cec5SDimitry Andric     return true;
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric   bool isRW = llvm::any_of(
43085868e8aSDimitry Andric       sections, [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; });
4310b57cec5SDimitry Andric 
4320b57cec5SDimitry Andric   return (isRW && kind == ConstraintKind::ReadWrite) ||
4330b57cec5SDimitry Andric          (!isRW && kind == ConstraintKind::ReadOnly);
4340b57cec5SDimitry Andric }
4350b57cec5SDimitry Andric 
sortSections(MutableArrayRef<InputSectionBase * > vec,SortSectionPolicy k)43685868e8aSDimitry Andric static void sortSections(MutableArrayRef<InputSectionBase *> vec,
4370b57cec5SDimitry Andric                          SortSectionPolicy k) {
43885868e8aSDimitry Andric   auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) {
43985868e8aSDimitry Andric     // ">" is not a mistake. Sections with larger alignments are placed
44085868e8aSDimitry Andric     // before sections with smaller alignments in order to reduce the
44185868e8aSDimitry Andric     // amount of padding necessary. This is compatible with GNU.
442bdd1243dSDimitry Andric     return a->addralign > b->addralign;
44385868e8aSDimitry Andric   };
44485868e8aSDimitry Andric   auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) {
44585868e8aSDimitry Andric     return a->name < b->name;
44685868e8aSDimitry Andric   };
44785868e8aSDimitry Andric   auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) {
44885868e8aSDimitry Andric     return getPriority(a->name) < getPriority(b->name);
44985868e8aSDimitry Andric   };
45085868e8aSDimitry Andric 
45185868e8aSDimitry Andric   switch (k) {
45285868e8aSDimitry Andric   case SortSectionPolicy::Default:
45385868e8aSDimitry Andric   case SortSectionPolicy::None:
45485868e8aSDimitry Andric     return;
45585868e8aSDimitry Andric   case SortSectionPolicy::Alignment:
45685868e8aSDimitry Andric     return llvm::stable_sort(vec, alignmentComparator);
45785868e8aSDimitry Andric   case SortSectionPolicy::Name:
45885868e8aSDimitry Andric     return llvm::stable_sort(vec, nameComparator);
45985868e8aSDimitry Andric   case SortSectionPolicy::Priority:
46085868e8aSDimitry Andric     return llvm::stable_sort(vec, priorityComparator);
46106c3fb27SDimitry Andric   case SortSectionPolicy::Reverse:
46206c3fb27SDimitry Andric     return std::reverse(vec.begin(), vec.end());
46385868e8aSDimitry Andric   }
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric // Sort sections as instructed by SORT-family commands and --sort-section
4670b57cec5SDimitry Andric // option. Because SORT-family commands can be nested at most two depth
4680b57cec5SDimitry Andric // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
4690b57cec5SDimitry Andric // line option is respected even if a SORT command is given, the exact
4700b57cec5SDimitry Andric // behavior we have here is a bit complicated. Here are the rules.
4710b57cec5SDimitry Andric //
4720b57cec5SDimitry Andric // 1. If two SORT commands are given, --sort-section is ignored.
4730b57cec5SDimitry Andric // 2. If one SORT command is given, and if it is not SORT_NONE,
4740b57cec5SDimitry Andric //    --sort-section is handled as an inner SORT command.
4750b57cec5SDimitry Andric // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
4760b57cec5SDimitry Andric // 4. If no SORT command is given, sort according to --sort-section.
sortInputSections(MutableArrayRef<InputSectionBase * > vec,SortSectionPolicy outer,SortSectionPolicy inner)47785868e8aSDimitry Andric static void sortInputSections(MutableArrayRef<InputSectionBase *> vec,
478e8d8bef9SDimitry Andric                               SortSectionPolicy outer,
479e8d8bef9SDimitry Andric                               SortSectionPolicy inner) {
480e8d8bef9SDimitry Andric   if (outer == SortSectionPolicy::None)
4810b57cec5SDimitry Andric     return;
4820b57cec5SDimitry Andric 
483e8d8bef9SDimitry Andric   if (inner == SortSectionPolicy::Default)
4840b57cec5SDimitry Andric     sortSections(vec, config->sortSection);
4850b57cec5SDimitry Andric   else
486e8d8bef9SDimitry Andric     sortSections(vec, inner);
487e8d8bef9SDimitry Andric   sortSections(vec, outer);
4880b57cec5SDimitry Andric }
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric // Compute and remember which sections the InputSectionDescription matches.
49104eeddc0SDimitry Andric SmallVector<InputSectionBase *, 0>
computeInputSections(const InputSectionDescription * cmd,ArrayRef<InputSectionBase * > sections,const OutputSection & outCmd)4925ffd83dbSDimitry Andric LinkerScript::computeInputSections(const InputSectionDescription *cmd,
4930fca6ea1SDimitry Andric                                    ArrayRef<InputSectionBase *> sections,
4940fca6ea1SDimitry Andric                                    const OutputSection &outCmd) {
49504eeddc0SDimitry Andric   SmallVector<InputSectionBase *, 0> ret;
49604eeddc0SDimitry Andric   SmallVector<size_t, 0> indexes;
497e8d8bef9SDimitry Andric   DenseSet<size_t> seen;
4980fca6ea1SDimitry Andric   DenseSet<InputSectionBase *> spills;
499e8d8bef9SDimitry Andric   auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {
500e8d8bef9SDimitry Andric     llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));
501e8d8bef9SDimitry Andric     for (size_t i = begin; i != end; ++i)
502e8d8bef9SDimitry Andric       ret[i] = sections[indexes[i]];
503e8d8bef9SDimitry Andric     sortInputSections(
504e8d8bef9SDimitry Andric         MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),
505e8d8bef9SDimitry Andric         config->sortSection, SortSectionPolicy::None);
506e8d8bef9SDimitry Andric   };
5070b57cec5SDimitry Andric 
5080b57cec5SDimitry Andric   // Collects all sections that satisfy constraints of Cmd.
509e8d8bef9SDimitry Andric   size_t sizeAfterPrevSort = 0;
5100b57cec5SDimitry Andric   for (const SectionPattern &pat : cmd->sectionPatterns) {
511e8d8bef9SDimitry Andric     size_t sizeBeforeCurrPat = ret.size();
5120b57cec5SDimitry Andric 
513e8d8bef9SDimitry Andric     for (size_t i = 0, e = sections.size(); i != e; ++i) {
5140fca6ea1SDimitry Andric       // Skip if the section is dead or has been matched by a previous pattern
5150fca6ea1SDimitry Andric       // in this input section description.
516e8d8bef9SDimitry Andric       InputSectionBase *sec = sections[i];
5170fca6ea1SDimitry Andric       if (!sec->isLive() || seen.contains(i))
5180b57cec5SDimitry Andric         continue;
5190b57cec5SDimitry Andric 
520349cc55cSDimitry Andric       // For --emit-relocs we have to ignore entries like
5210b57cec5SDimitry Andric       //   .rela.dyn : { *(.rela.data) }
5220b57cec5SDimitry Andric       // which are common because they are in the default bfd script.
5230b57cec5SDimitry Andric       // We do not ignore SHT_REL[A] linker-synthesized sections here because
5240b57cec5SDimitry Andric       // want to support scripts that do custom layout for them.
52585868e8aSDimitry Andric       if (isa<InputSection>(sec) &&
52685868e8aSDimitry Andric           cast<InputSection>(sec)->getRelocatedSection())
5270b57cec5SDimitry Andric         continue;
5280b57cec5SDimitry Andric 
5295ffd83dbSDimitry Andric       // Check the name early to improve performance in the common case.
5305ffd83dbSDimitry Andric       if (!pat.sectionPat.match(sec->name))
5315ffd83dbSDimitry Andric         continue;
5325ffd83dbSDimitry Andric 
533e8d8bef9SDimitry Andric       if (!cmd->matchesFile(sec->file) || pat.excludesFile(sec->file) ||
5345ffd83dbSDimitry Andric           (sec->flags & cmd->withFlags) != cmd->withFlags ||
5355ffd83dbSDimitry Andric           (sec->flags & cmd->withoutFlags) != 0)
5360b57cec5SDimitry Andric         continue;
5370b57cec5SDimitry Andric 
5380fca6ea1SDimitry Andric       if (sec->parent) {
5390fca6ea1SDimitry Andric         // Skip if not allowing multiple matches.
5400fca6ea1SDimitry Andric         if (!config->enableNonContiguousRegions)
5410fca6ea1SDimitry Andric           continue;
5420fca6ea1SDimitry Andric 
5430fca6ea1SDimitry Andric         // Disallow spilling into /DISCARD/; special handling would be needed
5440fca6ea1SDimitry Andric         // for this in address assignment, and the semantics are nebulous.
5450fca6ea1SDimitry Andric         if (outCmd.name == "/DISCARD/")
5460fca6ea1SDimitry Andric           continue;
5470fca6ea1SDimitry Andric 
5480fca6ea1SDimitry Andric         // Skip if the section's first match was /DISCARD/; such sections are
5490fca6ea1SDimitry Andric         // always discarded.
5500fca6ea1SDimitry Andric         if (sec->parent->name == "/DISCARD/")
5510fca6ea1SDimitry Andric           continue;
5520fca6ea1SDimitry Andric 
5530fca6ea1SDimitry Andric         // Skip if the section was already matched by a different input section
5540fca6ea1SDimitry Andric         // description within this output section.
5550fca6ea1SDimitry Andric         if (sec->parent == &outCmd)
5560fca6ea1SDimitry Andric           continue;
5570fca6ea1SDimitry Andric 
5580fca6ea1SDimitry Andric         spills.insert(sec);
5590fca6ea1SDimitry Andric       }
5600fca6ea1SDimitry Andric 
56185868e8aSDimitry Andric       ret.push_back(sec);
562e8d8bef9SDimitry Andric       indexes.push_back(i);
563e8d8bef9SDimitry Andric       seen.insert(i);
5640b57cec5SDimitry Andric     }
5650b57cec5SDimitry Andric 
566e8d8bef9SDimitry Andric     if (pat.sortOuter == SortSectionPolicy::Default)
567e8d8bef9SDimitry Andric       continue;
568e8d8bef9SDimitry Andric 
569e8d8bef9SDimitry Andric     // Matched sections are ordered by radix sort with the keys being (SORT*,
570e8d8bef9SDimitry Andric     // --sort-section, input order), where SORT* (if present) is most
571e8d8bef9SDimitry Andric     // significant.
572e8d8bef9SDimitry Andric     //
573e8d8bef9SDimitry Andric     // Matched sections between the previous SORT* and this SORT* are sorted by
574e8d8bef9SDimitry Andric     // (--sort-alignment, input order).
575e8d8bef9SDimitry Andric     sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);
576e8d8bef9SDimitry Andric     // Matched sections by this SORT* pattern are sorted using all 3 keys.
577e8d8bef9SDimitry Andric     // ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we
578e8d8bef9SDimitry Andric     // just sort by sortOuter and sortInner.
57985868e8aSDimitry Andric     sortInputSections(
580e8d8bef9SDimitry Andric         MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),
581e8d8bef9SDimitry Andric         pat.sortOuter, pat.sortInner);
582e8d8bef9SDimitry Andric     sizeAfterPrevSort = ret.size();
5830b57cec5SDimitry Andric   }
584e8d8bef9SDimitry Andric   // Matched sections after the last SORT* are sorted by (--sort-alignment,
585e8d8bef9SDimitry Andric   // input order).
586e8d8bef9SDimitry Andric   sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());
5870fca6ea1SDimitry Andric 
5880fca6ea1SDimitry Andric   // The flag --enable-non-contiguous-regions may cause sections to match an
5890fca6ea1SDimitry Andric   // InputSectionDescription in more than one OutputSection. Matches after the
5900fca6ea1SDimitry Andric   // first were collected in the spills set, so replace these with potential
5910fca6ea1SDimitry Andric   // spill sections.
5920fca6ea1SDimitry Andric   if (!spills.empty()) {
5930fca6ea1SDimitry Andric     for (InputSectionBase *&sec : ret) {
5940fca6ea1SDimitry Andric       if (!spills.contains(sec))
5950fca6ea1SDimitry Andric         continue;
5960fca6ea1SDimitry Andric 
5970fca6ea1SDimitry Andric       // Append the spill input section to the list for the input section,
5980fca6ea1SDimitry Andric       // creating it if necessary.
5990fca6ea1SDimitry Andric       PotentialSpillSection *pss = make<PotentialSpillSection>(
6000fca6ea1SDimitry Andric           *sec, const_cast<InputSectionDescription &>(*cmd));
6010fca6ea1SDimitry Andric       auto [it, inserted] =
6020fca6ea1SDimitry Andric           potentialSpillLists.try_emplace(sec, PotentialSpillList{pss, pss});
6030fca6ea1SDimitry Andric       if (!inserted) {
6040fca6ea1SDimitry Andric         PotentialSpillSection *&tail = it->second.tail;
6050fca6ea1SDimitry Andric         tail = tail->next = pss;
6060fca6ea1SDimitry Andric       }
6070fca6ea1SDimitry Andric       sec = pss;
6080fca6ea1SDimitry Andric     }
6090fca6ea1SDimitry Andric   }
6100fca6ea1SDimitry Andric 
6110b57cec5SDimitry Andric   return ret;
6120b57cec5SDimitry Andric }
6130b57cec5SDimitry Andric 
discard(InputSectionBase & s)6140eae32dcSDimitry Andric void LinkerScript::discard(InputSectionBase &s) {
61504eeddc0SDimitry Andric   if (&s == in.shStrTab.get())
6160eae32dcSDimitry Andric     error("discarding " + s.name + " section is not allowed");
6170b57cec5SDimitry Andric 
6180eae32dcSDimitry Andric   s.markDead();
6190eae32dcSDimitry Andric   s.parent = nullptr;
6200eae32dcSDimitry Andric   for (InputSection *sec : s.dependentSections)
6210eae32dcSDimitry Andric     discard(*sec);
6220b57cec5SDimitry Andric }
6230b57cec5SDimitry Andric 
discardSynthetic(OutputSection & outCmd)6245ffd83dbSDimitry Andric void LinkerScript::discardSynthetic(OutputSection &outCmd) {
6255ffd83dbSDimitry Andric   for (Partition &part : partitions) {
6265ffd83dbSDimitry Andric     if (!part.armExidx || !part.armExidx->isLive())
6275ffd83dbSDimitry Andric       continue;
62804eeddc0SDimitry Andric     SmallVector<InputSectionBase *, 0> secs(
62904eeddc0SDimitry Andric         part.armExidx->exidxSections.begin(),
6305ffd83dbSDimitry Andric         part.armExidx->exidxSections.end());
6314824e7fdSDimitry Andric     for (SectionCommand *cmd : outCmd.commands)
63204eeddc0SDimitry Andric       if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
6330fca6ea1SDimitry Andric         for (InputSectionBase *s : computeInputSections(isd, secs, outCmd))
6340eae32dcSDimitry Andric           discard(*s);
6355ffd83dbSDimitry Andric   }
6365ffd83dbSDimitry Andric }
6375ffd83dbSDimitry Andric 
63804eeddc0SDimitry Andric SmallVector<InputSectionBase *, 0>
createInputSectionList(OutputSection & outCmd)6390b57cec5SDimitry Andric LinkerScript::createInputSectionList(OutputSection &outCmd) {
64004eeddc0SDimitry Andric   SmallVector<InputSectionBase *, 0> ret;
6410b57cec5SDimitry Andric 
6424824e7fdSDimitry Andric   for (SectionCommand *cmd : outCmd.commands) {
6434824e7fdSDimitry Andric     if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {
6440fca6ea1SDimitry Andric       isd->sectionBases = computeInputSections(isd, ctx.inputSections, outCmd);
6454824e7fdSDimitry Andric       for (InputSectionBase *s : isd->sectionBases)
64685868e8aSDimitry Andric         s->parent = &outCmd;
6474824e7fdSDimitry Andric       ret.insert(ret.end(), isd->sectionBases.begin(), isd->sectionBases.end());
6480b57cec5SDimitry Andric     }
6490b57cec5SDimitry Andric   }
6500b57cec5SDimitry Andric   return ret;
6510b57cec5SDimitry Andric }
6520b57cec5SDimitry Andric 
65385868e8aSDimitry Andric // Create output sections described by SECTIONS commands.
processSectionCommands()6540b57cec5SDimitry Andric void LinkerScript::processSectionCommands() {
655fe6060f1SDimitry Andric   auto process = [this](OutputSection *osec) {
65604eeddc0SDimitry Andric     SmallVector<InputSectionBase *, 0> v = createInputSectionList(*osec);
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric     // The output section name `/DISCARD/' is special.
6590b57cec5SDimitry Andric     // Any input section assigned to it is discarded.
660fe6060f1SDimitry Andric     if (osec->name == "/DISCARD/") {
66185868e8aSDimitry Andric       for (InputSectionBase *s : v)
6620eae32dcSDimitry Andric         discard(*s);
663fe6060f1SDimitry Andric       discardSynthetic(*osec);
6644824e7fdSDimitry Andric       osec->commands.clear();
665fe6060f1SDimitry Andric       return false;
6660b57cec5SDimitry Andric     }
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric     // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
6690b57cec5SDimitry Andric     // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
6700b57cec5SDimitry Andric     // sections satisfy a given constraint. If not, a directive is handled
6710b57cec5SDimitry Andric     // as if it wasn't present from the beginning.
6720b57cec5SDimitry Andric     //
6730b57cec5SDimitry Andric     // Because we'll iterate over SectionCommands many more times, the easy
6740b57cec5SDimitry Andric     // way to "make it as if it wasn't present" is to make it empty.
675fe6060f1SDimitry Andric     if (!matchConstraints(v, osec->constraint)) {
6760b57cec5SDimitry Andric       for (InputSectionBase *s : v)
67785868e8aSDimitry Andric         s->parent = nullptr;
6784824e7fdSDimitry Andric       osec->commands.clear();
679fe6060f1SDimitry Andric       return false;
6800b57cec5SDimitry Andric     }
6810b57cec5SDimitry Andric 
6820b57cec5SDimitry Andric     // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
6830b57cec5SDimitry Andric     // is given, input sections are aligned to that value, whether the
6840b57cec5SDimitry Andric     // given value is larger or smaller than the original section alignment.
685fe6060f1SDimitry Andric     if (osec->subalignExpr) {
686fe6060f1SDimitry Andric       uint32_t subalign = osec->subalignExpr().getValue();
6870b57cec5SDimitry Andric       for (InputSectionBase *s : v)
688bdd1243dSDimitry Andric         s->addralign = subalign;
6890b57cec5SDimitry Andric     }
6900b57cec5SDimitry Andric 
69185868e8aSDimitry Andric     // Set the partition field the same way OutputSection::recordSection()
69285868e8aSDimitry Andric     // does. Partitions cannot be used with the SECTIONS command, so this is
69385868e8aSDimitry Andric     // always 1.
694fe6060f1SDimitry Andric     osec->partition = 1;
695fe6060f1SDimitry Andric     return true;
696fe6060f1SDimitry Andric   };
6970b57cec5SDimitry Andric 
698fe6060f1SDimitry Andric   // Process OVERWRITE_SECTIONS first so that it can overwrite the main script
699fe6060f1SDimitry Andric   // or orphans.
7000fca6ea1SDimitry Andric   if (config->enableNonContiguousRegions && !overwriteSections.empty())
7010fca6ea1SDimitry Andric     error("OVERWRITE_SECTIONS cannot be used with "
7020fca6ea1SDimitry Andric           "--enable-non-contiguous-regions");
70381ad6265SDimitry Andric   DenseMap<CachedHashStringRef, OutputDesc *> map;
704fe6060f1SDimitry Andric   size_t i = 0;
70581ad6265SDimitry Andric   for (OutputDesc *osd : overwriteSections) {
70681ad6265SDimitry Andric     OutputSection *osec = &osd->osec;
70704eeddc0SDimitry Andric     if (process(osec) &&
70881ad6265SDimitry Andric         !map.try_emplace(CachedHashStringRef(osec->name), osd).second)
709fe6060f1SDimitry Andric       warn("OVERWRITE_SECTIONS specifies duplicate " + osec->name);
71081ad6265SDimitry Andric   }
7114824e7fdSDimitry Andric   for (SectionCommand *&base : sectionCommands)
71281ad6265SDimitry Andric     if (auto *osd = dyn_cast<OutputDesc>(base)) {
71381ad6265SDimitry Andric       OutputSection *osec = &osd->osec;
71481ad6265SDimitry Andric       if (OutputDesc *overwrite = map.lookup(CachedHashStringRef(osec->name))) {
71581ad6265SDimitry Andric         log(overwrite->osec.location + " overwrites " + osec->name);
71681ad6265SDimitry Andric         overwrite->osec.sectionIndex = i++;
717fe6060f1SDimitry Andric         base = overwrite;
718fe6060f1SDimitry Andric       } else if (process(osec)) {
719fe6060f1SDimitry Andric         osec->sectionIndex = i++;
7200b57cec5SDimitry Andric       }
7210b57cec5SDimitry Andric     }
722fe6060f1SDimitry Andric 
723fe6060f1SDimitry Andric   // If an OVERWRITE_SECTIONS specified output section is not in
724fe6060f1SDimitry Andric   // sectionCommands, append it to the end. The section will be inserted by
725fe6060f1SDimitry Andric   // orphan placement.
72681ad6265SDimitry Andric   for (OutputDesc *osd : overwriteSections)
72781ad6265SDimitry Andric     if (osd->osec.partition == 1 && osd->osec.sectionIndex == UINT32_MAX)
72881ad6265SDimitry Andric       sectionCommands.push_back(osd);
72985868e8aSDimitry Andric }
73085868e8aSDimitry Andric 
processSymbolAssignments()73185868e8aSDimitry Andric void LinkerScript::processSymbolAssignments() {
73285868e8aSDimitry Andric   // Dot outside an output section still represents a relative address, whose
73385868e8aSDimitry Andric   // sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section
73485868e8aSDimitry Andric   // that fills the void outside a section. It has an index of one, which is
73585868e8aSDimitry Andric   // indistinguishable from any other regular section index.
73685868e8aSDimitry Andric   aether = make<OutputSection>("", 0, SHF_ALLOC);
73785868e8aSDimitry Andric   aether->sectionIndex = 1;
73885868e8aSDimitry Andric 
739bdd1243dSDimitry Andric   // `st` captures the local AddressState and makes it accessible deliberately.
74085868e8aSDimitry Andric   // This is needed as there are some cases where we cannot just thread the
74185868e8aSDimitry Andric   // current state through to a lambda function created by the script parser.
742bdd1243dSDimitry Andric   AddressState st;
743bdd1243dSDimitry Andric   state = &st;
744bdd1243dSDimitry Andric   st.outSec = aether;
74585868e8aSDimitry Andric 
7464824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands) {
7474824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
7484824e7fdSDimitry Andric       addSymbol(assign);
74985868e8aSDimitry Andric     else
75081ad6265SDimitry Andric       for (SectionCommand *subCmd : cast<OutputDesc>(cmd)->osec.commands)
7514824e7fdSDimitry Andric         if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
7524824e7fdSDimitry Andric           addSymbol(assign);
75385868e8aSDimitry Andric   }
75485868e8aSDimitry Andric 
755bdd1243dSDimitry Andric   state = nullptr;
7560b57cec5SDimitry Andric }
7570b57cec5SDimitry Andric 
findByName(ArrayRef<SectionCommand * > vec,StringRef name)7584824e7fdSDimitry Andric static OutputSection *findByName(ArrayRef<SectionCommand *> vec,
7590b57cec5SDimitry Andric                                  StringRef name) {
7604824e7fdSDimitry Andric   for (SectionCommand *cmd : vec)
76181ad6265SDimitry Andric     if (auto *osd = dyn_cast<OutputDesc>(cmd))
76281ad6265SDimitry Andric       if (osd->osec.name == name)
76381ad6265SDimitry Andric         return &osd->osec;
7640b57cec5SDimitry Andric   return nullptr;
7650b57cec5SDimitry Andric }
7660b57cec5SDimitry Andric 
createSection(InputSectionBase * isec,StringRef outsecName)76781ad6265SDimitry Andric static OutputDesc *createSection(InputSectionBase *isec, StringRef outsecName) {
76881ad6265SDimitry Andric   OutputDesc *osd = script->createOutputSection(outsecName, "<internal>");
76981ad6265SDimitry Andric   osd->osec.recordSection(isec);
77081ad6265SDimitry Andric   return osd;
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric 
addInputSec(StringMap<TinyPtrVector<OutputSection * >> & map,InputSectionBase * isec,StringRef outsecName)77381ad6265SDimitry Andric static OutputDesc *addInputSec(StringMap<TinyPtrVector<OutputSection *>> &map,
7740b57cec5SDimitry Andric                                InputSectionBase *isec, StringRef outsecName) {
7750b57cec5SDimitry Andric   // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r
7760b57cec5SDimitry Andric   // option is given. A section with SHT_GROUP defines a "section group", and
7770b57cec5SDimitry Andric   // its members have SHF_GROUP attribute. Usually these flags have already been
7780b57cec5SDimitry Andric   // stripped by InputFiles.cpp as section groups are processed and uniquified.
7790b57cec5SDimitry Andric   // However, for the -r option, we want to pass through all section groups
7800b57cec5SDimitry Andric   // as-is because adding/removing members or merging them with other groups
7810b57cec5SDimitry Andric   // change their semantics.
7820b57cec5SDimitry Andric   if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))
7830b57cec5SDimitry Andric     return createSection(isec, outsecName);
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric   // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
7860b57cec5SDimitry Andric   // relocation sections .rela.foo and .rela.bar for example. Most tools do
7870b57cec5SDimitry Andric   // not allow multiple REL[A] sections for output section. Hence we
7880b57cec5SDimitry Andric   // should combine these relocation sections into single output.
7890b57cec5SDimitry Andric   // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
7900b57cec5SDimitry Andric   // other REL[A] sections created by linker itself.
7910fca6ea1SDimitry Andric   if (!isa<SyntheticSection>(isec) && isStaticRelSecType(isec->type)) {
7920b57cec5SDimitry Andric     auto *sec = cast<InputSection>(isec);
7930b57cec5SDimitry Andric     OutputSection *out = sec->getRelocatedSection()->getOutputSection();
7940b57cec5SDimitry Andric 
7950fca6ea1SDimitry Andric     if (auto *relSec = out->relocationSection) {
7960fca6ea1SDimitry Andric       relSec->recordSection(sec);
7970b57cec5SDimitry Andric       return nullptr;
7980b57cec5SDimitry Andric     }
7990b57cec5SDimitry Andric 
80081ad6265SDimitry Andric     OutputDesc *osd = createSection(isec, outsecName);
80181ad6265SDimitry Andric     out->relocationSection = &osd->osec;
80281ad6265SDimitry Andric     return osd;
8030b57cec5SDimitry Andric   }
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric   //  The ELF spec just says
8060b57cec5SDimitry Andric   // ----------------------------------------------------------------
8070b57cec5SDimitry Andric   // In the first phase, input sections that match in name, type and
8080b57cec5SDimitry Andric   // attribute flags should be concatenated into single sections.
8090b57cec5SDimitry Andric   // ----------------------------------------------------------------
8100b57cec5SDimitry Andric   //
8110b57cec5SDimitry Andric   // However, it is clear that at least some flags have to be ignored for
8120b57cec5SDimitry Andric   // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
8130b57cec5SDimitry Andric   // ignored. We should not have two output .text sections just because one was
8140b57cec5SDimitry Andric   // in a group and another was not for example.
8150b57cec5SDimitry Andric   //
8160b57cec5SDimitry Andric   // It also seems that wording was a late addition and didn't get the
8170b57cec5SDimitry Andric   // necessary scrutiny.
8180b57cec5SDimitry Andric   //
8190b57cec5SDimitry Andric   // Merging sections with different flags is expected by some users. One
8200b57cec5SDimitry Andric   // reason is that if one file has
8210b57cec5SDimitry Andric   //
8220b57cec5SDimitry Andric   // int *const bar __attribute__((section(".foo"))) = (int *)0;
8230b57cec5SDimitry Andric   //
8240b57cec5SDimitry Andric   // gcc with -fPIC will produce a read only .foo section. But if another
8250b57cec5SDimitry Andric   // file has
8260b57cec5SDimitry Andric   //
8270b57cec5SDimitry Andric   // int zed;
8280b57cec5SDimitry Andric   // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
8290b57cec5SDimitry Andric   //
8300b57cec5SDimitry Andric   // gcc with -fPIC will produce a read write section.
8310b57cec5SDimitry Andric   //
8320b57cec5SDimitry Andric   // Last but not least, when using linker script the merge rules are forced by
8330b57cec5SDimitry Andric   // the script. Unfortunately, linker scripts are name based. This means that
8340b57cec5SDimitry Andric   // expressions like *(.foo*) can refer to multiple input sections with
8350b57cec5SDimitry Andric   // different flags. We cannot put them in different output sections or we
8360b57cec5SDimitry Andric   // would produce wrong results for
8370b57cec5SDimitry Andric   //
8380b57cec5SDimitry Andric   // start = .; *(.foo.*) end = .; *(.bar)
8390b57cec5SDimitry Andric   //
8400b57cec5SDimitry Andric   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
8410b57cec5SDimitry Andric   // another. The problem is that there is no way to layout those output
8420b57cec5SDimitry Andric   // sections such that the .foo sections are the only thing between the start
8430b57cec5SDimitry Andric   // and end symbols.
8440b57cec5SDimitry Andric   //
8450b57cec5SDimitry Andric   // Given the above issues, we instead merge sections by name and error on
8460b57cec5SDimitry Andric   // incompatible types and flags.
8470b57cec5SDimitry Andric   TinyPtrVector<OutputSection *> &v = map[outsecName];
8480b57cec5SDimitry Andric   for (OutputSection *sec : v) {
8490b57cec5SDimitry Andric     if (sec->partition != isec->partition)
8500b57cec5SDimitry Andric       continue;
85185868e8aSDimitry Andric 
85285868e8aSDimitry Andric     if (config->relocatable && (isec->flags & SHF_LINK_ORDER)) {
85385868e8aSDimitry Andric       // Merging two SHF_LINK_ORDER sections with different sh_link fields will
85485868e8aSDimitry Andric       // change their semantics, so we only merge them in -r links if they will
85585868e8aSDimitry Andric       // end up being linked to the same output section. The casts are fine
85685868e8aSDimitry Andric       // because everything in the map was created by the orphan placement code.
85785868e8aSDimitry Andric       auto *firstIsec = cast<InputSectionBase>(
8584824e7fdSDimitry Andric           cast<InputSectionDescription>(sec->commands[0])->sectionBases[0]);
859eaeb601bSDimitry Andric       OutputSection *firstIsecOut =
8600fca6ea1SDimitry Andric           (firstIsec->flags & SHF_LINK_ORDER)
861eaeb601bSDimitry Andric               ? firstIsec->getLinkOrderDep()->getOutputSection()
862eaeb601bSDimitry Andric               : nullptr;
863eaeb601bSDimitry Andric       if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection())
86485868e8aSDimitry Andric         continue;
86585868e8aSDimitry Andric     }
86685868e8aSDimitry Andric 
86785868e8aSDimitry Andric     sec->recordSection(isec);
8680b57cec5SDimitry Andric     return nullptr;
8690b57cec5SDimitry Andric   }
8700b57cec5SDimitry Andric 
87181ad6265SDimitry Andric   OutputDesc *osd = createSection(isec, outsecName);
87281ad6265SDimitry Andric   v.push_back(&osd->osec);
87381ad6265SDimitry Andric   return osd;
8740b57cec5SDimitry Andric }
8750b57cec5SDimitry Andric 
8760b57cec5SDimitry Andric // Add sections that didn't match any sections command.
addOrphanSections()8770b57cec5SDimitry Andric void LinkerScript::addOrphanSections() {
8780b57cec5SDimitry Andric   StringMap<TinyPtrVector<OutputSection *>> map;
87981ad6265SDimitry Andric   SmallVector<OutputDesc *, 0> v;
8800b57cec5SDimitry Andric 
88104eeddc0SDimitry Andric   auto add = [&](InputSectionBase *s) {
88285868e8aSDimitry Andric     if (s->isLive() && !s->parent) {
8835ffd83dbSDimitry Andric       orphanSections.push_back(s);
8845ffd83dbSDimitry Andric 
8850b57cec5SDimitry Andric       StringRef name = getOutputSectionName(s);
8865ffd83dbSDimitry Andric       if (config->unique) {
8875ffd83dbSDimitry Andric         v.push_back(createSection(s, name));
8885ffd83dbSDimitry Andric       } else if (OutputSection *sec = findByName(sectionCommands, name)) {
88985868e8aSDimitry Andric         sec->recordSection(s);
89085868e8aSDimitry Andric       } else {
89181ad6265SDimitry Andric         if (OutputDesc *osd = addInputSec(map, s, name))
89281ad6265SDimitry Andric           v.push_back(osd);
89385868e8aSDimitry Andric         assert(isa<MergeInputSection>(s) ||
89485868e8aSDimitry Andric                s->getOutputSection()->sectionIndex == UINT32_MAX);
89585868e8aSDimitry Andric       }
89685868e8aSDimitry Andric     }
8970b57cec5SDimitry Andric   };
8980b57cec5SDimitry Andric 
899fe6060f1SDimitry Andric   // For further --emit-reloc handling code we need target output section
9000b57cec5SDimitry Andric   // to be created before we create relocation output section, so we want
9010b57cec5SDimitry Andric   // to create target sections first. We do not want priority handling
9020b57cec5SDimitry Andric   // for synthetic sections because them are special.
903bdd1243dSDimitry Andric   size_t n = 0;
904bdd1243dSDimitry Andric   for (InputSectionBase *isec : ctx.inputSections) {
905bdd1243dSDimitry Andric     // Process InputSection and MergeInputSection.
906bdd1243dSDimitry Andric     if (LLVM_LIKELY(isa<InputSection>(isec)))
907bdd1243dSDimitry Andric       ctx.inputSections[n++] = isec;
908bdd1243dSDimitry Andric 
90985868e8aSDimitry Andric     // In -r links, SHF_LINK_ORDER sections are added while adding their parent
91085868e8aSDimitry Andric     // sections because we need to know the parent's output section before we
91185868e8aSDimitry Andric     // can select an output section for the SHF_LINK_ORDER section.
91285868e8aSDimitry Andric     if (config->relocatable && (isec->flags & SHF_LINK_ORDER))
91385868e8aSDimitry Andric       continue;
91485868e8aSDimitry Andric 
9150b57cec5SDimitry Andric     if (auto *sec = dyn_cast<InputSection>(isec))
9160b57cec5SDimitry Andric       if (InputSectionBase *rel = sec->getRelocatedSection())
9170b57cec5SDimitry Andric         if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent))
9180b57cec5SDimitry Andric           add(relIS);
9190b57cec5SDimitry Andric     add(isec);
92004eeddc0SDimitry Andric     if (config->relocatable)
92104eeddc0SDimitry Andric       for (InputSectionBase *depSec : isec->dependentSections)
92204eeddc0SDimitry Andric         if (depSec->flags & SHF_LINK_ORDER)
92304eeddc0SDimitry Andric           add(depSec);
9240b57cec5SDimitry Andric   }
925bdd1243dSDimitry Andric   // Keep just InputSection.
926bdd1243dSDimitry Andric   ctx.inputSections.resize(n);
9270b57cec5SDimitry Andric 
9280b57cec5SDimitry Andric   // If no SECTIONS command was given, we should insert sections commands
9290b57cec5SDimitry Andric   // before others, so that we can handle scripts which refers them,
9300b57cec5SDimitry Andric   // for example: "foo = ABSOLUTE(ADDR(.text)));".
9310b57cec5SDimitry Andric   // When SECTIONS command is present we just add all orphans to the end.
9320b57cec5SDimitry Andric   if (hasSectionsCommand)
9330b57cec5SDimitry Andric     sectionCommands.insert(sectionCommands.end(), v.begin(), v.end());
9340b57cec5SDimitry Andric   else
9350b57cec5SDimitry Andric     sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end());
9360b57cec5SDimitry Andric }
9370b57cec5SDimitry Andric 
diagnoseOrphanHandling() const9385ffd83dbSDimitry Andric void LinkerScript::diagnoseOrphanHandling() const {
939e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Diagnose orphan sections");
9400fca6ea1SDimitry Andric   if (config->orphanHandling == OrphanHandlingPolicy::Place ||
9410fca6ea1SDimitry Andric       !hasSectionsCommand)
942e8d8bef9SDimitry Andric     return;
9435ffd83dbSDimitry Andric   for (const InputSectionBase *sec : orphanSections) {
9445f757f3fSDimitry Andric     // .relro_padding is inserted before DATA_SEGMENT_RELRO_END, if present,
9455f757f3fSDimitry Andric     // automatically. The section is not supposed to be specified by scripts.
9465f757f3fSDimitry Andric     if (sec == in.relroPadding.get())
9475f757f3fSDimitry Andric       continue;
9485ffd83dbSDimitry Andric     // Input SHT_REL[A] retained by --emit-relocs are ignored by
9495ffd83dbSDimitry Andric     // computeInputSections(). Don't warn/error.
9505ffd83dbSDimitry Andric     if (isa<InputSection>(sec) &&
9515ffd83dbSDimitry Andric         cast<InputSection>(sec)->getRelocatedSection())
9525ffd83dbSDimitry Andric       continue;
9535ffd83dbSDimitry Andric 
9545ffd83dbSDimitry Andric     StringRef name = getOutputSectionName(sec);
9555ffd83dbSDimitry Andric     if (config->orphanHandling == OrphanHandlingPolicy::Error)
9565ffd83dbSDimitry Andric       error(toString(sec) + " is being placed in '" + name + "'");
957e8d8bef9SDimitry Andric     else
9585ffd83dbSDimitry Andric       warn(toString(sec) + " is being placed in '" + name + "'");
9595ffd83dbSDimitry Andric   }
9605ffd83dbSDimitry Andric }
9615ffd83dbSDimitry Andric 
diagnoseMissingSGSectionAddress() const96206c3fb27SDimitry Andric void LinkerScript::diagnoseMissingSGSectionAddress() const {
96306c3fb27SDimitry Andric   if (!config->cmseImplib || !in.armCmseSGSection->isNeeded())
96406c3fb27SDimitry Andric     return;
96506c3fb27SDimitry Andric 
96606c3fb27SDimitry Andric   OutputSection *sec = findByName(sectionCommands, ".gnu.sgstubs");
96706c3fb27SDimitry Andric   if (sec && !sec->addrExpr && !config->sectionStartMap.count(".gnu.sgstubs"))
96806c3fb27SDimitry Andric     error("no address assigned to the veneers output section " + sec->name);
96906c3fb27SDimitry Andric }
97006c3fb27SDimitry Andric 
9710b57cec5SDimitry Andric // This function searches for a memory region to place the given output
9720b57cec5SDimitry Andric // section in. If found, a pointer to the appropriate memory region is
973349cc55cSDimitry Andric // returned in the first member of the pair. Otherwise, a nullptr is returned.
974349cc55cSDimitry Andric // The second member of the pair is a hint that should be passed to the
975349cc55cSDimitry Andric // subsequent call of this method.
976349cc55cSDimitry Andric std::pair<MemoryRegion *, MemoryRegion *>
findMemoryRegion(OutputSection * sec,MemoryRegion * hint)977349cc55cSDimitry Andric LinkerScript::findMemoryRegion(OutputSection *sec, MemoryRegion *hint) {
978349cc55cSDimitry Andric   // Non-allocatable sections are not part of the process image.
979349cc55cSDimitry Andric   if (!(sec->flags & SHF_ALLOC)) {
98006c3fb27SDimitry Andric     bool hasInputOrByteCommand =
98106c3fb27SDimitry Andric         sec->hasInputSections ||
98206c3fb27SDimitry Andric         llvm::any_of(sec->commands, [](SectionCommand *comm) {
98306c3fb27SDimitry Andric           return ByteCommand::classof(comm);
98406c3fb27SDimitry Andric         });
98506c3fb27SDimitry Andric     if (!sec->memoryRegionName.empty() && hasInputOrByteCommand)
986349cc55cSDimitry Andric       warn("ignoring memory region assignment for non-allocatable section '" +
987349cc55cSDimitry Andric            sec->name + "'");
988349cc55cSDimitry Andric     return {nullptr, nullptr};
989349cc55cSDimitry Andric   }
990349cc55cSDimitry Andric 
9910b57cec5SDimitry Andric   // If a memory region name was specified in the output section command,
9920b57cec5SDimitry Andric   // then try to find that region first.
9930b57cec5SDimitry Andric   if (!sec->memoryRegionName.empty()) {
9940b57cec5SDimitry Andric     if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName))
995349cc55cSDimitry Andric       return {m, m};
9960b57cec5SDimitry Andric     error("memory region '" + sec->memoryRegionName + "' not declared");
997349cc55cSDimitry Andric     return {nullptr, nullptr};
9980b57cec5SDimitry Andric   }
9990b57cec5SDimitry Andric 
10000b57cec5SDimitry Andric   // If at least one memory region is defined, all sections must
10010b57cec5SDimitry Andric   // belong to some memory region. Otherwise, we don't need to do
10020b57cec5SDimitry Andric   // anything for memory regions.
10030b57cec5SDimitry Andric   if (memoryRegions.empty())
1004349cc55cSDimitry Andric     return {nullptr, nullptr};
1005349cc55cSDimitry Andric 
1006349cc55cSDimitry Andric   // An orphan section should continue the previous memory region.
1007349cc55cSDimitry Andric   if (sec->sectionIndex == UINT32_MAX && hint)
1008349cc55cSDimitry Andric     return {hint, hint};
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   // See if a region can be found by matching section flags.
10110b57cec5SDimitry Andric   for (auto &pair : memoryRegions) {
10120b57cec5SDimitry Andric     MemoryRegion *m = pair.second;
10134824e7fdSDimitry Andric     if (m->compatibleWith(sec->flags))
1014349cc55cSDimitry Andric       return {m, nullptr};
10150b57cec5SDimitry Andric   }
10160b57cec5SDimitry Andric 
10170b57cec5SDimitry Andric   // Otherwise, no suitable region was found.
10180b57cec5SDimitry Andric   error("no memory region specified for section '" + sec->name + "'");
1019349cc55cSDimitry Andric   return {nullptr, nullptr};
10200b57cec5SDimitry Andric }
10210b57cec5SDimitry Andric 
findFirstSection(PhdrEntry * load)10220b57cec5SDimitry Andric static OutputSection *findFirstSection(PhdrEntry *load) {
10230b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
10240b57cec5SDimitry Andric     if (sec->ptLoad == load)
10250b57cec5SDimitry Andric       return sec;
10260b57cec5SDimitry Andric   return nullptr;
10270b57cec5SDimitry Andric }
10280b57cec5SDimitry Andric 
10290fca6ea1SDimitry Andric // Assign addresses to an output section and offsets to its input sections and
10300fca6ea1SDimitry Andric // symbol assignments. Return true if the output section's address has changed.
assignOffsets(OutputSection * sec)10310fca6ea1SDimitry Andric bool LinkerScript::assignOffsets(OutputSection *sec) {
10326e75b2fbSDimitry Andric   const bool isTbss = (sec->flags & SHF_TLS) && sec->type == SHT_NOBITS;
1033bdd1243dSDimitry Andric   const bool sameMemRegion = state->memRegion == sec->memRegion;
1034bdd1243dSDimitry Andric   const bool prevLMARegionIsDefault = state->lmaRegion == nullptr;
1035e8d8bef9SDimitry Andric   const uint64_t savedDot = dot;
10360fca6ea1SDimitry Andric   bool addressChanged = false;
1037bdd1243dSDimitry Andric   state->memRegion = sec->memRegion;
1038bdd1243dSDimitry Andric   state->lmaRegion = sec->lmaRegion;
1039e8d8bef9SDimitry Andric 
10406e75b2fbSDimitry Andric   if (!(sec->flags & SHF_ALLOC)) {
10416e75b2fbSDimitry Andric     // Non-SHF_ALLOC sections have zero addresses.
10426e75b2fbSDimitry Andric     dot = 0;
10436e75b2fbSDimitry Andric   } else if (isTbss) {
10446e75b2fbSDimitry Andric     // Allow consecutive SHF_TLS SHT_NOBITS output sections. The address range
10456e75b2fbSDimitry Andric     // starts from the end address of the previous tbss section.
1046bdd1243dSDimitry Andric     if (state->tbssAddr == 0)
1047bdd1243dSDimitry Andric       state->tbssAddr = dot;
10486e75b2fbSDimitry Andric     else
1049bdd1243dSDimitry Andric       dot = state->tbssAddr;
10506e75b2fbSDimitry Andric   } else {
1051bdd1243dSDimitry Andric     if (state->memRegion)
1052bdd1243dSDimitry Andric       dot = state->memRegion->curPos;
1053e8d8bef9SDimitry Andric     if (sec->addrExpr)
10540b57cec5SDimitry Andric       setDot(sec->addrExpr, sec->location, false);
10550b57cec5SDimitry Andric 
105685868e8aSDimitry Andric     // If the address of the section has been moved forward by an explicit
105785868e8aSDimitry Andric     // expression so that it now starts past the current curPos of the enclosing
105885868e8aSDimitry Andric     // region, we need to expand the current region to account for the space
105985868e8aSDimitry Andric     // between the previous section, if any, and the start of this section.
1060bdd1243dSDimitry Andric     if (state->memRegion && state->memRegion->curPos < dot)
1061bdd1243dSDimitry Andric       expandMemoryRegion(state->memRegion, dot - state->memRegion->curPos,
10624824e7fdSDimitry Andric                          sec->name);
1063e8d8bef9SDimitry Andric   }
106485868e8aSDimitry Andric 
1065bdd1243dSDimitry Andric   state->outSec = sec;
10660fca6ea1SDimitry Andric   if (!(sec->addrExpr && script->hasSectionsCommand)) {
10670fca6ea1SDimitry Andric     // ALIGN is respected. sec->alignment is the max of ALIGN and the maximum of
10680fca6ea1SDimitry Andric     // input section alignments.
10694824e7fdSDimitry Andric     const uint64_t pos = dot;
1070bdd1243dSDimitry Andric     dot = alignToPowerOf2(dot, sec->addralign);
10714824e7fdSDimitry Andric     expandMemoryRegions(dot - pos);
10724824e7fdSDimitry Andric   }
10730fca6ea1SDimitry Andric   addressChanged = sec->addr != dot;
10740fca6ea1SDimitry Andric   sec->addr = dot;
10750b57cec5SDimitry Andric 
1076bdd1243dSDimitry Andric   // state->lmaOffset is LMA minus VMA. If LMA is explicitly specified via AT()
1077bdd1243dSDimitry Andric   // or AT>, recompute state->lmaOffset; otherwise, if both previous/current LMA
10785ffd83dbSDimitry Andric   // region is the default, and the two sections are in the same memory region,
10795ffd83dbSDimitry Andric   // reuse previous lmaOffset; otherwise, reset lmaOffset to 0. This emulates
10805ffd83dbSDimitry Andric   // heuristics described in
10815ffd83dbSDimitry Andric   // https://sourceware.org/binutils/docs/ld/Output-Section-LMA.html
1082349cc55cSDimitry Andric   if (sec->lmaExpr) {
1083bdd1243dSDimitry Andric     state->lmaOffset = sec->lmaExpr().getValue() - dot;
1084349cc55cSDimitry Andric   } else if (MemoryRegion *mr = sec->lmaRegion) {
1085bdd1243dSDimitry Andric     uint64_t lmaStart = alignToPowerOf2(mr->curPos, sec->addralign);
1086349cc55cSDimitry Andric     if (mr->curPos < lmaStart)
10874824e7fdSDimitry Andric       expandMemoryRegion(mr, lmaStart - mr->curPos, sec->name);
1088bdd1243dSDimitry Andric     state->lmaOffset = lmaStart - dot;
1089349cc55cSDimitry Andric   } else if (!sameMemRegion || !prevLMARegionIsDefault) {
1090bdd1243dSDimitry Andric     state->lmaOffset = 0;
1091349cc55cSDimitry Andric   }
10920b57cec5SDimitry Andric 
1093bdd1243dSDimitry Andric   // Propagate state->lmaOffset to the first "non-header" section.
10944824e7fdSDimitry Andric   if (PhdrEntry *l = sec->ptLoad)
10950b57cec5SDimitry Andric     if (sec == findFirstSection(l))
1096bdd1243dSDimitry Andric       l->lmaOffset = state->lmaOffset;
10970b57cec5SDimitry Andric 
10980b57cec5SDimitry Andric   // We can call this method multiple times during the creation of
10990b57cec5SDimitry Andric   // thunks and want to start over calculation each time.
11000b57cec5SDimitry Andric   sec->size = 0;
11010b57cec5SDimitry Andric 
11020b57cec5SDimitry Andric   // We visited SectionsCommands from processSectionCommands to
11030b57cec5SDimitry Andric   // layout sections. Now, we visit SectionsCommands again to fix
11040b57cec5SDimitry Andric   // section offsets.
11054824e7fdSDimitry Andric   for (SectionCommand *cmd : sec->commands) {
11060b57cec5SDimitry Andric     // This handles the assignments to symbol or to the dot.
11074824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
11084824e7fdSDimitry Andric       assign->addr = dot;
11094824e7fdSDimitry Andric       assignSymbol(assign, true);
11104824e7fdSDimitry Andric       assign->size = dot - assign->addr;
11110b57cec5SDimitry Andric       continue;
11120b57cec5SDimitry Andric     }
11130b57cec5SDimitry Andric 
11140b57cec5SDimitry Andric     // Handle BYTE(), SHORT(), LONG(), or QUAD().
11154824e7fdSDimitry Andric     if (auto *data = dyn_cast<ByteCommand>(cmd)) {
11164824e7fdSDimitry Andric       data->offset = dot - sec->addr;
11174824e7fdSDimitry Andric       dot += data->size;
11184824e7fdSDimitry Andric       expandOutputSection(data->size);
11190b57cec5SDimitry Andric       continue;
11200b57cec5SDimitry Andric     }
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric     // Handle a single input section description command.
11230b57cec5SDimitry Andric     // It calculates and assigns the offsets for each section and also
11240b57cec5SDimitry Andric     // updates the output section size.
11250fca6ea1SDimitry Andric 
11260fca6ea1SDimitry Andric     auto &sections = cast<InputSectionDescription>(cmd)->sections;
11270fca6ea1SDimitry Andric     for (InputSection *isec : sections) {
11284824e7fdSDimitry Andric       assert(isec->getParent() == sec);
11290fca6ea1SDimitry Andric       if (isa<PotentialSpillSection>(isec))
11300fca6ea1SDimitry Andric         continue;
11314824e7fdSDimitry Andric       const uint64_t pos = dot;
1132bdd1243dSDimitry Andric       dot = alignToPowerOf2(dot, isec->addralign);
11334824e7fdSDimitry Andric       isec->outSecOff = dot - sec->addr;
11344824e7fdSDimitry Andric       dot += isec->getSize();
11354824e7fdSDimitry Andric 
11364824e7fdSDimitry Andric       // Update output section size after adding each section. This is so that
11374824e7fdSDimitry Andric       // SIZEOF works correctly in the case below:
11384824e7fdSDimitry Andric       // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
11394824e7fdSDimitry Andric       expandOutputSection(dot - pos);
11404824e7fdSDimitry Andric     }
11410b57cec5SDimitry Andric   }
1142e8d8bef9SDimitry Andric 
11435f757f3fSDimitry Andric   // If .relro_padding is present, round up the end to a common-page-size
11445f757f3fSDimitry Andric   // boundary to protect the last page.
11455f757f3fSDimitry Andric   if (in.relroPadding && sec == in.relroPadding->getParent())
11465f757f3fSDimitry Andric     expandOutputSection(alignToPowerOf2(dot, config->commonPageSize) - dot);
11475f757f3fSDimitry Andric 
1148e8d8bef9SDimitry Andric   // Non-SHF_ALLOC sections do not affect the addresses of other OutputSections
1149e8d8bef9SDimitry Andric   // as they are not part of the process image.
11506e75b2fbSDimitry Andric   if (!(sec->flags & SHF_ALLOC)) {
1151e8d8bef9SDimitry Andric     dot = savedDot;
11526e75b2fbSDimitry Andric   } else if (isTbss) {
11536e75b2fbSDimitry Andric     // NOBITS TLS sections are similar. Additionally save the end address.
1154bdd1243dSDimitry Andric     state->tbssAddr = dot;
11556e75b2fbSDimitry Andric     dot = savedDot;
11566e75b2fbSDimitry Andric   }
11570fca6ea1SDimitry Andric   return addressChanged;
11580b57cec5SDimitry Andric }
11590b57cec5SDimitry Andric 
isDiscardable(const OutputSection & sec)1160349cc55cSDimitry Andric static bool isDiscardable(const OutputSection &sec) {
11610b57cec5SDimitry Andric   if (sec.name == "/DISCARD/")
11620b57cec5SDimitry Andric     return true;
11630b57cec5SDimitry Andric 
11640b57cec5SDimitry Andric   // We do not want to remove OutputSections with expressions that reference
11650b57cec5SDimitry Andric   // symbols even if the OutputSection is empty. We want to ensure that the
11660b57cec5SDimitry Andric   // expressions can be evaluated and report an error if they cannot.
11670b57cec5SDimitry Andric   if (sec.expressionsUseSymbols)
11680b57cec5SDimitry Andric     return false;
11690b57cec5SDimitry Andric 
11700b57cec5SDimitry Andric   // OutputSections may be referenced by name in ADDR and LOADADDR expressions,
11710b57cec5SDimitry Andric   // as an empty Section can has a valid VMA and LMA we keep the OutputSection
11720b57cec5SDimitry Andric   // to maintain the integrity of the other Expression.
11730b57cec5SDimitry Andric   if (sec.usedInExpression)
11740b57cec5SDimitry Andric     return false;
11750b57cec5SDimitry Andric 
11764824e7fdSDimitry Andric   for (SectionCommand *cmd : sec.commands) {
11774824e7fdSDimitry Andric     if (auto assign = dyn_cast<SymbolAssignment>(cmd))
11780b57cec5SDimitry Andric       // Don't create empty output sections just for unreferenced PROVIDE
11790b57cec5SDimitry Andric       // symbols.
11804824e7fdSDimitry Andric       if (assign->name != "." && !assign->sym)
11810b57cec5SDimitry Andric         continue;
11820b57cec5SDimitry Andric 
11834824e7fdSDimitry Andric     if (!isa<InputSectionDescription>(*cmd))
11840b57cec5SDimitry Andric       return false;
11850b57cec5SDimitry Andric   }
11860b57cec5SDimitry Andric   return true;
11870b57cec5SDimitry Andric }
11880b57cec5SDimitry Andric 
maybePropagatePhdrs(OutputSection & sec,SmallVector<StringRef,0> & phdrs)1189e8d8bef9SDimitry Andric static void maybePropagatePhdrs(OutputSection &sec,
119004eeddc0SDimitry Andric                                 SmallVector<StringRef, 0> &phdrs) {
1191e8d8bef9SDimitry Andric   if (sec.phdrs.empty()) {
1192e8d8bef9SDimitry Andric     // To match the bfd linker script behaviour, only propagate program
1193e8d8bef9SDimitry Andric     // headers to sections that are allocated.
1194e8d8bef9SDimitry Andric     if (sec.flags & SHF_ALLOC)
1195e8d8bef9SDimitry Andric       sec.phdrs = phdrs;
1196e8d8bef9SDimitry Andric   } else {
1197e8d8bef9SDimitry Andric     phdrs = sec.phdrs;
1198e8d8bef9SDimitry Andric   }
1199e8d8bef9SDimitry Andric }
1200e8d8bef9SDimitry Andric 
adjustOutputSections()12011fd87a68SDimitry Andric void LinkerScript::adjustOutputSections() {
12020b57cec5SDimitry Andric   // If the output section contains only symbol assignments, create a
12030b57cec5SDimitry Andric   // corresponding output section. The issue is what to do with linker script
12040b57cec5SDimitry Andric   // like ".foo : { symbol = 42; }". One option would be to convert it to
12050b57cec5SDimitry Andric   // "symbol = 42;". That is, move the symbol out of the empty section
12060b57cec5SDimitry Andric   // description. That seems to be what bfd does for this simple case. The
12070b57cec5SDimitry Andric   // problem is that this is not completely general. bfd will give up and
12080b57cec5SDimitry Andric   // create a dummy section too if there is a ". = . + 1" inside the section
12090b57cec5SDimitry Andric   // for example.
12100b57cec5SDimitry Andric   // Given that we want to create the section, we have to worry what impact
12110b57cec5SDimitry Andric   // it will have on the link. For example, if we just create a section with
12120b57cec5SDimitry Andric   // 0 for flags, it would change which PT_LOADs are created.
12130b57cec5SDimitry Andric   // We could remember that particular section is dummy and ignore it in
12140b57cec5SDimitry Andric   // other parts of the linker, but unfortunately there are quite a few places
12150b57cec5SDimitry Andric   // that would need to change:
12160b57cec5SDimitry Andric   //   * The program header creation.
12170b57cec5SDimitry Andric   //   * The orphan section placement.
12180b57cec5SDimitry Andric   //   * The address assignment.
12190b57cec5SDimitry Andric   // The other option is to pick flags that minimize the impact the section
12200b57cec5SDimitry Andric   // will have on the rest of the linker. That is why we copy the flags from
12215f757f3fSDimitry Andric   // the previous sections. We copy just SHF_ALLOC and SHF_WRITE to keep the
12225f757f3fSDimitry Andric   // impact low. We do not propagate SHF_EXECINSTR as in some cases this can
12235f757f3fSDimitry Andric   // lead to executable writeable section.
12240b57cec5SDimitry Andric   uint64_t flags = SHF_ALLOC;
12250b57cec5SDimitry Andric 
122604eeddc0SDimitry Andric   SmallVector<StringRef, 0> defPhdrs;
12275f757f3fSDimitry Andric   bool seenRelro = false;
12284824e7fdSDimitry Andric   for (SectionCommand *&cmd : sectionCommands) {
122981ad6265SDimitry Andric     if (!isa<OutputDesc>(cmd))
12300b57cec5SDimitry Andric       continue;
123181ad6265SDimitry Andric     auto *sec = &cast<OutputDesc>(cmd)->osec;
12320b57cec5SDimitry Andric 
12330b57cec5SDimitry Andric     // Handle align (e.g. ".foo : ALIGN(16) { ... }").
12340b57cec5SDimitry Andric     if (sec->alignExpr)
1235bdd1243dSDimitry Andric       sec->addralign =
1236bdd1243dSDimitry Andric           std::max<uint32_t>(sec->addralign, sec->alignExpr().getValue());
12370b57cec5SDimitry Andric 
12381fd87a68SDimitry Andric     bool isEmpty = (getFirstInputSection(sec) == nullptr);
12391fd87a68SDimitry Andric     bool discardable = isEmpty && isDiscardable(*sec);
12401fd87a68SDimitry Andric     // If sec has at least one input section and not discarded, remember its
12411fd87a68SDimitry Andric     // flags to be inherited by subsequent output sections. (sec may contain
12421fd87a68SDimitry Andric     // just one empty synthetic section.)
12431fd87a68SDimitry Andric     if (sec->hasInputSections && !discardable)
12440b57cec5SDimitry Andric       flags = sec->flags;
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric     // We do not want to keep any special flags for output section
12470b57cec5SDimitry Andric     // in case it is empty.
12480fca6ea1SDimitry Andric     if (isEmpty) {
12495f757f3fSDimitry Andric       sec->flags =
12505f757f3fSDimitry Andric           flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) | SHF_WRITE);
12510fca6ea1SDimitry Andric       sec->sortRank = getSectionRank(*sec);
12520fca6ea1SDimitry Andric     }
12530b57cec5SDimitry Andric 
1254e8d8bef9SDimitry Andric     // The code below may remove empty output sections. We should save the
1255e8d8bef9SDimitry Andric     // specified program headers (if exist) and propagate them to subsequent
1256e8d8bef9SDimitry Andric     // sections which do not specify program headers.
1257e8d8bef9SDimitry Andric     // An example of such a linker script is:
1258e8d8bef9SDimitry Andric     // SECTIONS { .empty : { *(.empty) } :rw
1259e8d8bef9SDimitry Andric     //            .foo : { *(.foo) } }
1260e8d8bef9SDimitry Andric     // Note: at this point the order of output sections has not been finalized,
1261e8d8bef9SDimitry Andric     // because orphans have not been inserted into their expected positions. We
1262e8d8bef9SDimitry Andric     // will handle them in adjustSectionsAfterSorting().
1263e8d8bef9SDimitry Andric     if (sec->sectionIndex != UINT32_MAX)
1264e8d8bef9SDimitry Andric       maybePropagatePhdrs(*sec, defPhdrs);
1265e8d8bef9SDimitry Andric 
12665f757f3fSDimitry Andric     // Discard .relro_padding if we have not seen one RELRO section. Note: when
12675f757f3fSDimitry Andric     // .tbss is the only RELRO section, there is no associated PT_LOAD segment
12685f757f3fSDimitry Andric     // (needsPtLoad), so we don't append .relro_padding in the case.
12695f757f3fSDimitry Andric     if (in.relroPadding && in.relroPadding->getParent() == sec && !seenRelro)
12705f757f3fSDimitry Andric       discardable = true;
12711fd87a68SDimitry Andric     if (discardable) {
12720b57cec5SDimitry Andric       sec->markDead();
12730b57cec5SDimitry Andric       cmd = nullptr;
12745f757f3fSDimitry Andric     } else {
12755f757f3fSDimitry Andric       seenRelro |=
12765f757f3fSDimitry Andric           sec->relro && !(sec->type == SHT_NOBITS && (sec->flags & SHF_TLS));
12770b57cec5SDimitry Andric     }
12780b57cec5SDimitry Andric   }
12790b57cec5SDimitry Andric 
12800b57cec5SDimitry Andric   // It is common practice to use very generic linker scripts. So for any
12810b57cec5SDimitry Andric   // given run some of the output sections in the script will be empty.
12820b57cec5SDimitry Andric   // We could create corresponding empty output sections, but that would
12830b57cec5SDimitry Andric   // clutter the output.
12840b57cec5SDimitry Andric   // We instead remove trivially empty sections. The bfd linker seems even
12850b57cec5SDimitry Andric   // more aggressive at removing them.
12864824e7fdSDimitry Andric   llvm::erase_if(sectionCommands, [&](SectionCommand *cmd) { return !cmd; });
12870b57cec5SDimitry Andric }
12880b57cec5SDimitry Andric 
adjustSectionsAfterSorting()12890b57cec5SDimitry Andric void LinkerScript::adjustSectionsAfterSorting() {
12900b57cec5SDimitry Andric   // Try and find an appropriate memory region to assign offsets in.
1291349cc55cSDimitry Andric   MemoryRegion *hint = nullptr;
12924824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands) {
129381ad6265SDimitry Andric     if (auto *osd = dyn_cast<OutputDesc>(cmd)) {
129481ad6265SDimitry Andric       OutputSection *sec = &osd->osec;
12950b57cec5SDimitry Andric       if (!sec->lmaRegionName.empty()) {
12960b57cec5SDimitry Andric         if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName))
12970b57cec5SDimitry Andric           sec->lmaRegion = m;
12980b57cec5SDimitry Andric         else
12990b57cec5SDimitry Andric           error("memory region '" + sec->lmaRegionName + "' not declared");
13000b57cec5SDimitry Andric       }
1301349cc55cSDimitry Andric       std::tie(sec->memRegion, hint) = findMemoryRegion(sec, hint);
13020b57cec5SDimitry Andric     }
13030b57cec5SDimitry Andric   }
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   // If output section command doesn't specify any segments,
13060b57cec5SDimitry Andric   // and we haven't previously assigned any section to segment,
13070b57cec5SDimitry Andric   // then we simply assign section to the very first load segment.
13080b57cec5SDimitry Andric   // Below is an example of such linker script:
13090b57cec5SDimitry Andric   // PHDRS { seg PT_LOAD; }
13100b57cec5SDimitry Andric   // SECTIONS { .aaa : { *(.aaa) } }
131104eeddc0SDimitry Andric   SmallVector<StringRef, 0> defPhdrs;
13120b57cec5SDimitry Andric   auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) {
13130b57cec5SDimitry Andric     return cmd.type == PT_LOAD;
13140b57cec5SDimitry Andric   });
13150b57cec5SDimitry Andric   if (firstPtLoad != phdrsCommands.end())
13160b57cec5SDimitry Andric     defPhdrs.push_back(firstPtLoad->name);
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric   // Walk the commands and propagate the program headers to commands that don't
13190b57cec5SDimitry Andric   // explicitly specify them.
13204824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands)
132181ad6265SDimitry Andric     if (auto *osd = dyn_cast<OutputDesc>(cmd))
132281ad6265SDimitry Andric       maybePropagatePhdrs(osd->osec, defPhdrs);
13230b57cec5SDimitry Andric }
13240b57cec5SDimitry Andric 
computeBase(uint64_t min,bool allocateHeaders)13250b57cec5SDimitry Andric static uint64_t computeBase(uint64_t min, bool allocateHeaders) {
13260b57cec5SDimitry Andric   // If there is no SECTIONS or if the linkerscript is explicit about program
13270b57cec5SDimitry Andric   // headers, do our best to allocate them.
13280b57cec5SDimitry Andric   if (!script->hasSectionsCommand || allocateHeaders)
13290b57cec5SDimitry Andric     return 0;
13300b57cec5SDimitry Andric   // Otherwise only allocate program headers if that would not add a page.
13310b57cec5SDimitry Andric   return alignDown(min, config->maxPageSize);
13320b57cec5SDimitry Andric }
13330b57cec5SDimitry Andric 
133469660011SDimitry Andric // When the SECTIONS command is used, try to find an address for the file and
133569660011SDimitry Andric // program headers output sections, which can be added to the first PT_LOAD
133669660011SDimitry Andric // segment when program headers are created.
13370b57cec5SDimitry Andric //
133869660011SDimitry Andric // We check if the headers fit below the first allocated section. If there isn't
133969660011SDimitry Andric // enough space for these sections, we'll remove them from the PT_LOAD segment,
134069660011SDimitry Andric // and we'll also remove the PT_PHDR segment.
allocateHeaders(SmallVector<PhdrEntry *,0> & phdrs)134104eeddc0SDimitry Andric void LinkerScript::allocateHeaders(SmallVector<PhdrEntry *, 0> &phdrs) {
13420b57cec5SDimitry Andric   uint64_t min = std::numeric_limits<uint64_t>::max();
13430b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
13440b57cec5SDimitry Andric     if (sec->flags & SHF_ALLOC)
13450b57cec5SDimitry Andric       min = std::min<uint64_t>(min, sec->addr);
13460b57cec5SDimitry Andric 
13470b57cec5SDimitry Andric   auto it = llvm::find_if(
13480b57cec5SDimitry Andric       phdrs, [](const PhdrEntry *e) { return e->p_type == PT_LOAD; });
13490b57cec5SDimitry Andric   if (it == phdrs.end())
13500b57cec5SDimitry Andric     return;
13510b57cec5SDimitry Andric   PhdrEntry *firstPTLoad = *it;
13520b57cec5SDimitry Andric 
13530b57cec5SDimitry Andric   bool hasExplicitHeaders =
13540b57cec5SDimitry Andric       llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) {
13550b57cec5SDimitry Andric         return cmd.hasPhdrs || cmd.hasFilehdr;
13560b57cec5SDimitry Andric       });
13570b57cec5SDimitry Andric   bool paged = !config->omagic && !config->nmagic;
13580b57cec5SDimitry Andric   uint64_t headerSize = getHeaderSize();
13590b57cec5SDimitry Andric   if ((paged || hasExplicitHeaders) &&
13600b57cec5SDimitry Andric       headerSize <= min - computeBase(min, hasExplicitHeaders)) {
13610b57cec5SDimitry Andric     min = alignDown(min - headerSize, config->maxPageSize);
13620b57cec5SDimitry Andric     Out::elfHeader->addr = min;
13630b57cec5SDimitry Andric     Out::programHeaders->addr = min + Out::elfHeader->size;
13640b57cec5SDimitry Andric     return;
13650b57cec5SDimitry Andric   }
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric   // Error if we were explicitly asked to allocate headers.
13680b57cec5SDimitry Andric   if (hasExplicitHeaders)
13690b57cec5SDimitry Andric     error("could not allocate headers");
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric   Out::elfHeader->ptLoad = nullptr;
13720b57cec5SDimitry Andric   Out::programHeaders->ptLoad = nullptr;
13730b57cec5SDimitry Andric   firstPTLoad->firstSec = findFirstSection(firstPTLoad);
13740b57cec5SDimitry Andric 
13750b57cec5SDimitry Andric   llvm::erase_if(phdrs,
13760b57cec5SDimitry Andric                  [](const PhdrEntry *e) { return e->p_type == PT_PHDR; });
13770b57cec5SDimitry Andric }
13780b57cec5SDimitry Andric 
AddressState()13790b57cec5SDimitry Andric LinkerScript::AddressState::AddressState() {
13800b57cec5SDimitry Andric   for (auto &mri : script->memoryRegions) {
13810b57cec5SDimitry Andric     MemoryRegion *mr = mri.second;
13825ffd83dbSDimitry Andric     mr->curPos = (mr->origin)().getValue();
13830b57cec5SDimitry Andric   }
13840b57cec5SDimitry Andric }
13850b57cec5SDimitry Andric 
13860b57cec5SDimitry Andric // Here we assign addresses as instructed by linker script SECTIONS
13870b57cec5SDimitry Andric // sub-commands. Doing that allows us to use final VA values, so here
13880b57cec5SDimitry Andric // we also handle rest commands like symbol assignments and ASSERTs.
13890fca6ea1SDimitry Andric // Return an output section that has changed its address or null, and a symbol
13900fca6ea1SDimitry Andric // that has changed its section or value (or nullptr if no symbol has changed).
13910fca6ea1SDimitry Andric std::pair<const OutputSection *, const Defined *>
assignAddresses()13920fca6ea1SDimitry Andric LinkerScript::assignAddresses() {
139369660011SDimitry Andric   if (script->hasSectionsCommand) {
139469660011SDimitry Andric     // With a linker script, assignment of addresses to headers is covered by
139569660011SDimitry Andric     // allocateHeaders().
139681ad6265SDimitry Andric     dot = config->imageBase.value_or(0);
139769660011SDimitry Andric   } else {
139869660011SDimitry Andric     // Assign addresses to headers right now.
139969660011SDimitry Andric     dot = target->getImageBase();
140069660011SDimitry Andric     Out::elfHeader->addr = dot;
140169660011SDimitry Andric     Out::programHeaders->addr = dot + Out::elfHeader->size;
140269660011SDimitry Andric     dot += getHeaderSize();
140369660011SDimitry Andric   }
14040b57cec5SDimitry Andric 
14050fca6ea1SDimitry Andric   OutputSection *changedOsec = nullptr;
1406bdd1243dSDimitry Andric   AddressState st;
1407bdd1243dSDimitry Andric   state = &st;
14080b57cec5SDimitry Andric   errorOnMissingSection = true;
1409bdd1243dSDimitry Andric   st.outSec = aether;
14100fca6ea1SDimitry Andric   recordedErrors.clear();
14110b57cec5SDimitry Andric 
141285868e8aSDimitry Andric   SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);
14134824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands) {
14144824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
14154824e7fdSDimitry Andric       assign->addr = dot;
14164824e7fdSDimitry Andric       assignSymbol(assign, false);
14174824e7fdSDimitry Andric       assign->size = dot - assign->addr;
14180b57cec5SDimitry Andric       continue;
14190b57cec5SDimitry Andric     }
14200fca6ea1SDimitry Andric     if (assignOffsets(&cast<OutputDesc>(cmd)->osec) && !changedOsec)
14210fca6ea1SDimitry Andric       changedOsec = &cast<OutputDesc>(cmd)->osec;
14220b57cec5SDimitry Andric   }
142385868e8aSDimitry Andric 
1424bdd1243dSDimitry Andric   state = nullptr;
14250fca6ea1SDimitry Andric   return {changedOsec, getChangedSymbolAssignment(oldValues)};
14260fca6ea1SDimitry Andric }
14270fca6ea1SDimitry Andric 
hasRegionOverflowed(MemoryRegion * mr)14280fca6ea1SDimitry Andric static bool hasRegionOverflowed(MemoryRegion *mr) {
14290fca6ea1SDimitry Andric   if (!mr)
14300fca6ea1SDimitry Andric     return false;
14310fca6ea1SDimitry Andric   return mr->curPos - mr->getOrigin() > mr->getLength();
14320fca6ea1SDimitry Andric }
14330fca6ea1SDimitry Andric 
14340fca6ea1SDimitry Andric // Spill input sections in reverse order of address assignment to (potentially)
14350fca6ea1SDimitry Andric // bring memory regions out of overflow. The size savings of a spill can only be
14360fca6ea1SDimitry Andric // estimated, since general linker script arithmetic may occur afterwards.
14370fca6ea1SDimitry Andric // Under-estimates may cause unnecessary spills, but over-estimates can always
14380fca6ea1SDimitry Andric // be corrected on the next pass.
spillSections()14390fca6ea1SDimitry Andric bool LinkerScript::spillSections() {
14400fca6ea1SDimitry Andric   if (!config->enableNonContiguousRegions)
14410fca6ea1SDimitry Andric     return false;
14420fca6ea1SDimitry Andric 
14430fca6ea1SDimitry Andric   bool spilled = false;
14440fca6ea1SDimitry Andric   for (SectionCommand *cmd : reverse(sectionCommands)) {
14450fca6ea1SDimitry Andric     auto *od = dyn_cast<OutputDesc>(cmd);
14460fca6ea1SDimitry Andric     if (!od)
14470fca6ea1SDimitry Andric       continue;
14480fca6ea1SDimitry Andric     OutputSection *osec = &od->osec;
14490fca6ea1SDimitry Andric     if (!osec->memRegion)
14500fca6ea1SDimitry Andric       continue;
14510fca6ea1SDimitry Andric 
14520fca6ea1SDimitry Andric     // Input sections that have replaced a potential spill and should be removed
14530fca6ea1SDimitry Andric     // from their input section description.
14540fca6ea1SDimitry Andric     DenseSet<InputSection *> spilledInputSections;
14550fca6ea1SDimitry Andric 
14560fca6ea1SDimitry Andric     for (SectionCommand *cmd : reverse(osec->commands)) {
14570fca6ea1SDimitry Andric       if (!hasRegionOverflowed(osec->memRegion) &&
14580fca6ea1SDimitry Andric           !hasRegionOverflowed(osec->lmaRegion))
14590fca6ea1SDimitry Andric         break;
14600fca6ea1SDimitry Andric 
14610fca6ea1SDimitry Andric       auto *isd = dyn_cast<InputSectionDescription>(cmd);
14620fca6ea1SDimitry Andric       if (!isd)
14630fca6ea1SDimitry Andric         continue;
14640fca6ea1SDimitry Andric       for (InputSection *isec : reverse(isd->sections)) {
14650fca6ea1SDimitry Andric         // Potential spill locations cannot be spilled.
14660fca6ea1SDimitry Andric         if (isa<PotentialSpillSection>(isec))
14670fca6ea1SDimitry Andric           continue;
14680fca6ea1SDimitry Andric 
14690fca6ea1SDimitry Andric         // Find the next potential spill location and remove it from the list.
14700fca6ea1SDimitry Andric         auto it = potentialSpillLists.find(isec);
14710fca6ea1SDimitry Andric         if (it == potentialSpillLists.end())
14720fca6ea1SDimitry Andric           continue;
14730fca6ea1SDimitry Andric         PotentialSpillList &list = it->second;
14740fca6ea1SDimitry Andric         PotentialSpillSection *spill = list.head;
14750fca6ea1SDimitry Andric         if (spill->next)
14760fca6ea1SDimitry Andric           list.head = spill->next;
14770fca6ea1SDimitry Andric         else
14780fca6ea1SDimitry Andric           potentialSpillLists.erase(isec);
14790fca6ea1SDimitry Andric 
14800fca6ea1SDimitry Andric         // Replace the next spill location with the spilled section and adjust
14810fca6ea1SDimitry Andric         // its properties to match the new location. Note that the alignment of
14820fca6ea1SDimitry Andric         // the spill section may have diverged from the original due to e.g. a
14830fca6ea1SDimitry Andric         // SUBALIGN. Correct assignment requires the spill's alignment to be
14840fca6ea1SDimitry Andric         // used, not the original.
14850fca6ea1SDimitry Andric         spilledInputSections.insert(isec);
14860fca6ea1SDimitry Andric         *llvm::find(spill->isd->sections, spill) = isec;
14870fca6ea1SDimitry Andric         isec->parent = spill->parent;
14880fca6ea1SDimitry Andric         isec->addralign = spill->addralign;
14890fca6ea1SDimitry Andric 
14900fca6ea1SDimitry Andric         // Record the (potential) reduction in the region's end position.
14910fca6ea1SDimitry Andric         osec->memRegion->curPos -= isec->getSize();
14920fca6ea1SDimitry Andric         if (osec->lmaRegion)
14930fca6ea1SDimitry Andric           osec->lmaRegion->curPos -= isec->getSize();
14940fca6ea1SDimitry Andric 
14950fca6ea1SDimitry Andric         // Spilling continues until the end position no longer overflows the
14960fca6ea1SDimitry Andric         // region. Then, another round of address assignment will either confirm
14970fca6ea1SDimitry Andric         // the spill's success or lead to yet more spilling.
14980fca6ea1SDimitry Andric         if (!hasRegionOverflowed(osec->memRegion) &&
14990fca6ea1SDimitry Andric             !hasRegionOverflowed(osec->lmaRegion))
15000fca6ea1SDimitry Andric           break;
15010fca6ea1SDimitry Andric       }
15020fca6ea1SDimitry Andric 
15030fca6ea1SDimitry Andric       // Remove any spilled input sections to complete their move.
15040fca6ea1SDimitry Andric       if (!spilledInputSections.empty()) {
15050fca6ea1SDimitry Andric         spilled = true;
15060fca6ea1SDimitry Andric         llvm::erase_if(isd->sections, [&](InputSection *isec) {
15070fca6ea1SDimitry Andric           return spilledInputSections.contains(isec);
15080fca6ea1SDimitry Andric         });
15090fca6ea1SDimitry Andric       }
15100fca6ea1SDimitry Andric     }
15110fca6ea1SDimitry Andric   }
15120fca6ea1SDimitry Andric 
15130fca6ea1SDimitry Andric   return spilled;
15140fca6ea1SDimitry Andric }
15150fca6ea1SDimitry Andric 
15160fca6ea1SDimitry Andric // Erase any potential spill sections that were not used.
erasePotentialSpillSections()15170fca6ea1SDimitry Andric void LinkerScript::erasePotentialSpillSections() {
15180fca6ea1SDimitry Andric   if (potentialSpillLists.empty())
15190fca6ea1SDimitry Andric     return;
15200fca6ea1SDimitry Andric 
15210fca6ea1SDimitry Andric   // Collect the set of input section descriptions that contain potential
15220fca6ea1SDimitry Andric   // spills.
15230fca6ea1SDimitry Andric   DenseSet<InputSectionDescription *> isds;
15240fca6ea1SDimitry Andric   for (const auto &[_, list] : potentialSpillLists)
15250fca6ea1SDimitry Andric     for (PotentialSpillSection *s = list.head; s; s = s->next)
15260fca6ea1SDimitry Andric       isds.insert(s->isd);
15270fca6ea1SDimitry Andric 
15280fca6ea1SDimitry Andric   for (InputSectionDescription *isd : isds)
15290fca6ea1SDimitry Andric     llvm::erase_if(isd->sections, [](InputSection *s) {
15300fca6ea1SDimitry Andric       return isa<PotentialSpillSection>(s);
15310fca6ea1SDimitry Andric     });
15320fca6ea1SDimitry Andric 
15330fca6ea1SDimitry Andric   potentialSpillLists.clear();
15340b57cec5SDimitry Andric }
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric // Creates program headers as instructed by PHDRS linker script command.
createPhdrs()153704eeddc0SDimitry Andric SmallVector<PhdrEntry *, 0> LinkerScript::createPhdrs() {
153804eeddc0SDimitry Andric   SmallVector<PhdrEntry *, 0> ret;
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric   // Process PHDRS and FILEHDR keywords because they are not
15410b57cec5SDimitry Andric   // real output sections and cannot be added in the following loop.
15420b57cec5SDimitry Andric   for (const PhdrsCommand &cmd : phdrsCommands) {
154381ad6265SDimitry Andric     PhdrEntry *phdr = make<PhdrEntry>(cmd.type, cmd.flags.value_or(PF_R));
15440b57cec5SDimitry Andric 
15450b57cec5SDimitry Andric     if (cmd.hasFilehdr)
15460b57cec5SDimitry Andric       phdr->add(Out::elfHeader);
15470b57cec5SDimitry Andric     if (cmd.hasPhdrs)
15480b57cec5SDimitry Andric       phdr->add(Out::programHeaders);
15490b57cec5SDimitry Andric 
15500b57cec5SDimitry Andric     if (cmd.lmaExpr) {
15510b57cec5SDimitry Andric       phdr->p_paddr = cmd.lmaExpr().getValue();
15520b57cec5SDimitry Andric       phdr->hasLMA = true;
15530b57cec5SDimitry Andric     }
15540b57cec5SDimitry Andric     ret.push_back(phdr);
15550b57cec5SDimitry Andric   }
15560b57cec5SDimitry Andric 
15570b57cec5SDimitry Andric   // Add output sections to program headers.
15580b57cec5SDimitry Andric   for (OutputSection *sec : outputSections) {
15590b57cec5SDimitry Andric     // Assign headers specified by linker script
15600b57cec5SDimitry Andric     for (size_t id : getPhdrIndices(sec)) {
15610b57cec5SDimitry Andric       ret[id]->add(sec);
156281ad6265SDimitry Andric       if (!phdrsCommands[id].flags)
15630b57cec5SDimitry Andric         ret[id]->p_flags |= sec->getPhdrFlags();
15640b57cec5SDimitry Andric     }
15650b57cec5SDimitry Andric   }
15660b57cec5SDimitry Andric   return ret;
15670b57cec5SDimitry Andric }
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric // Returns true if we should emit an .interp section.
15700b57cec5SDimitry Andric //
15710b57cec5SDimitry Andric // We usually do. But if PHDRS commands are given, and
15720b57cec5SDimitry Andric // no PT_INTERP is there, there's no place to emit an
15730b57cec5SDimitry Andric // .interp, so we don't do that in that case.
needsInterpSection()15740b57cec5SDimitry Andric bool LinkerScript::needsInterpSection() {
15750b57cec5SDimitry Andric   if (phdrsCommands.empty())
15760b57cec5SDimitry Andric     return true;
15770b57cec5SDimitry Andric   for (PhdrsCommand &cmd : phdrsCommands)
15780b57cec5SDimitry Andric     if (cmd.type == PT_INTERP)
15790b57cec5SDimitry Andric       return true;
15800b57cec5SDimitry Andric   return false;
15810b57cec5SDimitry Andric }
15820b57cec5SDimitry Andric 
getSymbolValue(StringRef name,const Twine & loc)15830b57cec5SDimitry Andric ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {
15840b57cec5SDimitry Andric   if (name == ".") {
1585bdd1243dSDimitry Andric     if (state)
1586bdd1243dSDimitry Andric       return {state->outSec, false, dot - state->outSec->addr, loc};
15870b57cec5SDimitry Andric     error(loc + ": unable to get location counter value");
15880b57cec5SDimitry Andric     return 0;
15890b57cec5SDimitry Andric   }
15900b57cec5SDimitry Andric 
1591bdd1243dSDimitry Andric   if (Symbol *sym = symtab.find(name)) {
159216d6b3b3SDimitry Andric     if (auto *ds = dyn_cast<Defined>(sym)) {
159316d6b3b3SDimitry Andric       ExprValue v{ds->section, false, ds->value, loc};
159416d6b3b3SDimitry Andric       // Retain the original st_type, so that the alias will get the same
159516d6b3b3SDimitry Andric       // behavior in relocation processing. Any operation will reset st_type to
159616d6b3b3SDimitry Andric       // STT_NOTYPE.
159716d6b3b3SDimitry Andric       v.type = ds->type;
159816d6b3b3SDimitry Andric       return v;
159916d6b3b3SDimitry Andric     }
16000b57cec5SDimitry Andric     if (isa<SharedSymbol>(sym))
16010b57cec5SDimitry Andric       if (!errorOnMissingSection)
16020b57cec5SDimitry Andric         return {nullptr, false, 0, loc};
16030b57cec5SDimitry Andric   }
16040b57cec5SDimitry Andric 
16050b57cec5SDimitry Andric   error(loc + ": symbol not found: " + name);
16060b57cec5SDimitry Andric   return 0;
16070b57cec5SDimitry Andric }
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric // Returns the index of the segment named Name.
getPhdrIndex(ArrayRef<PhdrsCommand> vec,StringRef name)1610bdd1243dSDimitry Andric static std::optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,
16110b57cec5SDimitry Andric                                           StringRef name) {
16120b57cec5SDimitry Andric   for (size_t i = 0; i < vec.size(); ++i)
16130b57cec5SDimitry Andric     if (vec[i].name == name)
16140b57cec5SDimitry Andric       return i;
1615bdd1243dSDimitry Andric   return std::nullopt;
16160b57cec5SDimitry Andric }
16170b57cec5SDimitry Andric 
16180b57cec5SDimitry Andric // Returns indices of ELF headers containing specific section. Each index is a
16190b57cec5SDimitry Andric // zero based number of ELF header listed within PHDRS {} script block.
getPhdrIndices(OutputSection * cmd)162004eeddc0SDimitry Andric SmallVector<size_t, 0> LinkerScript::getPhdrIndices(OutputSection *cmd) {
162104eeddc0SDimitry Andric   SmallVector<size_t, 0> ret;
16220b57cec5SDimitry Andric 
16230b57cec5SDimitry Andric   for (StringRef s : cmd->phdrs) {
1624bdd1243dSDimitry Andric     if (std::optional<size_t> idx = getPhdrIndex(phdrsCommands, s))
16250b57cec5SDimitry Andric       ret.push_back(*idx);
16260b57cec5SDimitry Andric     else if (s != "NONE")
16275ffd83dbSDimitry Andric       error(cmd->location + ": program header '" + s +
16280b57cec5SDimitry Andric             "' is not listed in PHDRS");
16290b57cec5SDimitry Andric   }
16300b57cec5SDimitry Andric   return ret;
16310b57cec5SDimitry Andric }
163206c3fb27SDimitry Andric 
printMemoryUsage(raw_ostream & os)163306c3fb27SDimitry Andric void LinkerScript::printMemoryUsage(raw_ostream& os) {
163406c3fb27SDimitry Andric   auto printSize = [&](uint64_t size) {
163506c3fb27SDimitry Andric     if ((size & 0x3fffffff) == 0)
163606c3fb27SDimitry Andric       os << format_decimal(size >> 30, 10) << " GB";
163706c3fb27SDimitry Andric     else if ((size & 0xfffff) == 0)
163806c3fb27SDimitry Andric       os << format_decimal(size >> 20, 10) << " MB";
163906c3fb27SDimitry Andric     else if ((size & 0x3ff) == 0)
164006c3fb27SDimitry Andric       os << format_decimal(size >> 10, 10) << " KB";
164106c3fb27SDimitry Andric     else
164206c3fb27SDimitry Andric       os << " " << format_decimal(size, 10) << " B";
164306c3fb27SDimitry Andric   };
164406c3fb27SDimitry Andric   os << "Memory region         Used Size  Region Size  %age Used\n";
164506c3fb27SDimitry Andric   for (auto &pair : memoryRegions) {
164606c3fb27SDimitry Andric     MemoryRegion *m = pair.second;
164706c3fb27SDimitry Andric     uint64_t usedLength = m->curPos - m->getOrigin();
164806c3fb27SDimitry Andric     os << right_justify(m->name, 16) << ": ";
164906c3fb27SDimitry Andric     printSize(usedLength);
165006c3fb27SDimitry Andric     uint64_t length = m->getLength();
165106c3fb27SDimitry Andric     if (length != 0) {
165206c3fb27SDimitry Andric       printSize(length);
165306c3fb27SDimitry Andric       double percent = usedLength * 100.0 / length;
165406c3fb27SDimitry Andric       os << "    " << format("%6.2f%%", percent);
165506c3fb27SDimitry Andric     }
165606c3fb27SDimitry Andric     os << '\n';
165706c3fb27SDimitry Andric   }
165806c3fb27SDimitry Andric }
165906c3fb27SDimitry Andric 
recordError(const Twine & msg)16600fca6ea1SDimitry Andric void LinkerScript::recordError(const Twine &msg) {
16610fca6ea1SDimitry Andric   auto &str = recordedErrors.emplace_back();
16620fca6ea1SDimitry Andric   msg.toVector(str);
16630fca6ea1SDimitry Andric }
16640fca6ea1SDimitry Andric 
checkMemoryRegion(const MemoryRegion * region,const OutputSection * osec,uint64_t addr)166506c3fb27SDimitry Andric static void checkMemoryRegion(const MemoryRegion *region,
166606c3fb27SDimitry Andric                               const OutputSection *osec, uint64_t addr) {
166706c3fb27SDimitry Andric   uint64_t osecEnd = addr + osec->size;
166806c3fb27SDimitry Andric   uint64_t regionEnd = region->getOrigin() + region->getLength();
166906c3fb27SDimitry Andric   if (osecEnd > regionEnd) {
167006c3fb27SDimitry Andric     error("section '" + osec->name + "' will not fit in region '" +
167106c3fb27SDimitry Andric           region->name + "': overflowed by " + Twine(osecEnd - regionEnd) +
167206c3fb27SDimitry Andric           " bytes");
167306c3fb27SDimitry Andric   }
167406c3fb27SDimitry Andric }
167506c3fb27SDimitry Andric 
checkFinalScriptConditions() const16765f757f3fSDimitry Andric void LinkerScript::checkFinalScriptConditions() const {
16770fca6ea1SDimitry Andric   for (StringRef err : recordedErrors)
16780fca6ea1SDimitry Andric     errorOrWarn(err);
167906c3fb27SDimitry Andric   for (const OutputSection *sec : outputSections) {
168006c3fb27SDimitry Andric     if (const MemoryRegion *memoryRegion = sec->memRegion)
168106c3fb27SDimitry Andric       checkMemoryRegion(memoryRegion, sec, sec->addr);
168206c3fb27SDimitry Andric     if (const MemoryRegion *lmaRegion = sec->lmaRegion)
168306c3fb27SDimitry Andric       checkMemoryRegion(lmaRegion, sec, sec->getLMA());
168406c3fb27SDimitry Andric   }
168506c3fb27SDimitry Andric }
16860fca6ea1SDimitry Andric 
addScriptReferencedSymbolsToSymTable()16870fca6ea1SDimitry Andric void LinkerScript::addScriptReferencedSymbolsToSymTable() {
16880fca6ea1SDimitry Andric   // Some symbols (such as __ehdr_start) are defined lazily only when there
16890fca6ea1SDimitry Andric   // are undefined symbols for them, so we add these to trigger that logic.
16900fca6ea1SDimitry Andric   auto reference = [](StringRef name) {
16910fca6ea1SDimitry Andric     Symbol *sym = symtab.addUnusedUndefined(name);
16920fca6ea1SDimitry Andric     sym->isUsedInRegularObj = true;
16930fca6ea1SDimitry Andric     sym->referenced = true;
16940fca6ea1SDimitry Andric   };
16950fca6ea1SDimitry Andric   for (StringRef name : referencedSymbols)
16960fca6ea1SDimitry Andric     reference(name);
16970fca6ea1SDimitry Andric 
16980fca6ea1SDimitry Andric   // Keeps track of references from which PROVIDE symbols have been added to the
16990fca6ea1SDimitry Andric   // symbol table.
17000fca6ea1SDimitry Andric   DenseSet<StringRef> added;
17010fca6ea1SDimitry Andric   SmallVector<const SmallVector<StringRef, 0> *, 0> symRefsVec;
17020fca6ea1SDimitry Andric   for (const auto &[name, symRefs] : provideMap)
17030fca6ea1SDimitry Andric     if (LinkerScript::shouldAddProvideSym(name) && added.insert(name).second)
17040fca6ea1SDimitry Andric       symRefsVec.push_back(&symRefs);
17050fca6ea1SDimitry Andric   while (symRefsVec.size()) {
17060fca6ea1SDimitry Andric     for (StringRef name : *symRefsVec.pop_back_val()) {
17070fca6ea1SDimitry Andric       reference(name);
17080fca6ea1SDimitry Andric       // Prevent the symbol from being discarded by --gc-sections.
17090fca6ea1SDimitry Andric       script->referencedSymbols.push_back(name);
17100fca6ea1SDimitry Andric       auto it = script->provideMap.find(name);
17110fca6ea1SDimitry Andric       if (it != script->provideMap.end() &&
17120fca6ea1SDimitry Andric           LinkerScript::shouldAddProvideSym(name) &&
17130fca6ea1SDimitry Andric           added.insert(name).second) {
17140fca6ea1SDimitry Andric         symRefsVec.push_back(&it->second);
17150fca6ea1SDimitry Andric       }
17160fca6ea1SDimitry Andric     }
17170fca6ea1SDimitry Andric   }
17180fca6ea1SDimitry Andric }
17190fca6ea1SDimitry Andric 
shouldAddProvideSym(StringRef symName)17200fca6ea1SDimitry Andric bool LinkerScript::shouldAddProvideSym(StringRef symName) {
17210fca6ea1SDimitry Andric   Symbol *sym = symtab.find(symName);
17220fca6ea1SDimitry Andric   return sym && !sym->isDefined() && !sym->isCommon();
17230fca6ea1SDimitry Andric }
1724