xref: /freebsd/contrib/llvm-project/lld/ELF/LinkerScript.cpp (revision 04eeddc0aa8e0a417a16eaf9d7d095207f4a8623)
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"
150b57cec5SDimitry Andric #include "InputSection.h"
160b57cec5SDimitry Andric #include "OutputSections.h"
170b57cec5SDimitry Andric #include "SymbolTable.h"
180b57cec5SDimitry Andric #include "Symbols.h"
190b57cec5SDimitry Andric #include "SyntheticSections.h"
200b57cec5SDimitry Andric #include "Target.h"
210b57cec5SDimitry Andric #include "Writer.h"
22*04eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
230b57cec5SDimitry Andric #include "lld/Common/Strings.h"
240b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
250b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
260b57cec5SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
270b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
280b57cec5SDimitry Andric #include "llvm/Support/Endian.h"
290b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
300b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
315ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h"
320b57cec5SDimitry Andric #include "llvm/Support/Path.h"
33e8d8bef9SDimitry Andric #include "llvm/Support/TimeProfiler.h"
340b57cec5SDimitry Andric #include <algorithm>
350b57cec5SDimitry Andric #include <cassert>
360b57cec5SDimitry Andric #include <cstddef>
370b57cec5SDimitry Andric #include <cstdint>
380b57cec5SDimitry Andric #include <iterator>
390b57cec5SDimitry Andric #include <limits>
400b57cec5SDimitry Andric #include <string>
410b57cec5SDimitry Andric #include <vector>
420b57cec5SDimitry Andric 
430b57cec5SDimitry Andric using namespace llvm;
440b57cec5SDimitry Andric using namespace llvm::ELF;
450b57cec5SDimitry Andric using namespace llvm::object;
460b57cec5SDimitry Andric using namespace llvm::support::endian;
475ffd83dbSDimitry Andric using namespace lld;
485ffd83dbSDimitry Andric using namespace lld::elf;
490b57cec5SDimitry Andric 
500eae32dcSDimitry Andric std::unique_ptr<LinkerScript> elf::script;
510b57cec5SDimitry Andric 
524824e7fdSDimitry Andric static bool isSectionPrefix(StringRef prefix, StringRef name) {
530eae32dcSDimitry Andric   return name.consume_front(prefix) && (name.empty() || name[0] == '.');
544824e7fdSDimitry Andric }
554824e7fdSDimitry Andric 
564824e7fdSDimitry Andric static StringRef getOutputSectionName(const InputSectionBase *s) {
574824e7fdSDimitry Andric   if (config->relocatable)
584824e7fdSDimitry Andric     return s->name;
594824e7fdSDimitry Andric 
604824e7fdSDimitry Andric   // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want
614824e7fdSDimitry Andric   // to emit .rela.text.foo as .rela.text.bar for consistency (this is not
624824e7fdSDimitry Andric   // technically required, but not doing it is odd). This code guarantees that.
634824e7fdSDimitry Andric   if (auto *isec = dyn_cast<InputSection>(s)) {
644824e7fdSDimitry Andric     if (InputSectionBase *rel = isec->getRelocatedSection()) {
654824e7fdSDimitry Andric       OutputSection *out = rel->getOutputSection();
664824e7fdSDimitry Andric       if (s->type == SHT_RELA)
67*04eeddc0SDimitry Andric         return saver().save(".rela" + out->name);
68*04eeddc0SDimitry Andric       return saver().save(".rel" + out->name);
694824e7fdSDimitry Andric     }
704824e7fdSDimitry Andric   }
714824e7fdSDimitry Andric 
724824e7fdSDimitry Andric   // A BssSection created for a common symbol is identified as "COMMON" in
734824e7fdSDimitry Andric   // linker scripts. It should go to .bss section.
744824e7fdSDimitry Andric   if (s->name == "COMMON")
754824e7fdSDimitry Andric     return ".bss";
764824e7fdSDimitry Andric 
774824e7fdSDimitry Andric   if (script->hasSectionsCommand)
784824e7fdSDimitry Andric     return s->name;
794824e7fdSDimitry Andric 
804824e7fdSDimitry Andric   // When no SECTIONS is specified, emulate GNU ld's internal linker scripts
814824e7fdSDimitry Andric   // by grouping sections with certain prefixes.
824824e7fdSDimitry Andric 
834824e7fdSDimitry Andric   // GNU ld places text sections with prefix ".text.hot.", ".text.unknown.",
844824e7fdSDimitry Andric   // ".text.unlikely.", ".text.startup." or ".text.exit." before others.
854824e7fdSDimitry Andric   // We provide an option -z keep-text-section-prefix to group such sections
864824e7fdSDimitry Andric   // into separate output sections. This is more flexible. See also
874824e7fdSDimitry Andric   // sortISDBySectionOrder().
884824e7fdSDimitry Andric   // ".text.unknown" means the hotness of the section is unknown. When
894824e7fdSDimitry Andric   // SampleFDO is used, if a function doesn't have sample, it could be very
904824e7fdSDimitry Andric   // cold or it could be a new function never being sampled. Those functions
914824e7fdSDimitry Andric   // will be kept in the ".text.unknown" section.
924824e7fdSDimitry Andric   // ".text.split." holds symbols which are split out from functions in other
934824e7fdSDimitry Andric   // input sections. For example, with -fsplit-machine-functions, placing the
944824e7fdSDimitry Andric   // cold parts in .text.split instead of .text.unlikely mitigates against poor
954824e7fdSDimitry Andric   // profile inaccuracy. Techniques such as hugepage remapping can make
964824e7fdSDimitry Andric   // conservative decisions at the section granularity.
970eae32dcSDimitry Andric   if (isSectionPrefix(".text", s->name)) {
984824e7fdSDimitry Andric     if (config->zKeepTextSectionPrefix)
990eae32dcSDimitry Andric       for (StringRef v : {".text.hot", ".text.unknown", ".text.unlikely",
1000eae32dcSDimitry Andric                           ".text.startup", ".text.exit", ".text.split"})
1010eae32dcSDimitry Andric         if (isSectionPrefix(v.substr(5), s->name.substr(5)))
1020eae32dcSDimitry Andric           return v;
1030eae32dcSDimitry Andric     return ".text";
1040eae32dcSDimitry Andric   }
1054824e7fdSDimitry Andric 
1064824e7fdSDimitry Andric   for (StringRef v :
1070eae32dcSDimitry Andric        {".data.rel.ro", ".data", ".rodata", ".bss.rel.ro", ".bss",
1080eae32dcSDimitry Andric         ".gcc_except_table", ".init_array", ".fini_array", ".tbss", ".tdata",
1090eae32dcSDimitry Andric         ".ARM.exidx", ".ARM.extab", ".ctors", ".dtors"})
1104824e7fdSDimitry Andric     if (isSectionPrefix(v, s->name))
1110eae32dcSDimitry Andric       return v;
1124824e7fdSDimitry Andric 
1134824e7fdSDimitry Andric   return s->name;
1140b57cec5SDimitry Andric }
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric uint64_t ExprValue::getValue() const {
1170b57cec5SDimitry Andric   if (sec)
1184824e7fdSDimitry Andric     return alignTo(sec->getOutputSection()->addr + sec->getOffset(val),
1190b57cec5SDimitry Andric                    alignment);
1200b57cec5SDimitry Andric   return alignTo(val, alignment);
1210b57cec5SDimitry Andric }
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric uint64_t ExprValue::getSecAddr() const {
1244824e7fdSDimitry Andric   return sec ? sec->getOutputSection()->addr + sec->getOffset(0) : 0;
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric uint64_t ExprValue::getSectionOffset() const {
1280b57cec5SDimitry Andric   // If the alignment is trivial, we don't have to compute the full
1290b57cec5SDimitry Andric   // value to know the offset. This allows this function to succeed in
1300b57cec5SDimitry Andric   // cases where the output section is not yet known.
13185868e8aSDimitry Andric   if (alignment == 1 && !sec)
1320b57cec5SDimitry Andric     return val;
1330b57cec5SDimitry Andric   return getValue() - getSecAddr();
1340b57cec5SDimitry Andric }
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric OutputSection *LinkerScript::createOutputSection(StringRef name,
1370b57cec5SDimitry Andric                                                  StringRef location) {
138*04eeddc0SDimitry Andric   OutputSection *&secRef = nameToOutputSection[CachedHashStringRef(name)];
1390b57cec5SDimitry Andric   OutputSection *sec;
1400b57cec5SDimitry Andric   if (secRef && secRef->location.empty()) {
1410b57cec5SDimitry Andric     // There was a forward reference.
1420b57cec5SDimitry Andric     sec = secRef;
1430b57cec5SDimitry Andric   } else {
1440b57cec5SDimitry Andric     sec = make<OutputSection>(name, SHT_PROGBITS, 0);
1450b57cec5SDimitry Andric     if (!secRef)
1460b57cec5SDimitry Andric       secRef = sec;
1470b57cec5SDimitry Andric   }
1485ffd83dbSDimitry Andric   sec->location = std::string(location);
1490b57cec5SDimitry Andric   return sec;
1500b57cec5SDimitry Andric }
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric OutputSection *LinkerScript::getOrCreateOutputSection(StringRef name) {
153*04eeddc0SDimitry Andric   OutputSection *&cmdRef = nameToOutputSection[CachedHashStringRef(name)];
1540b57cec5SDimitry Andric   if (!cmdRef)
1550b57cec5SDimitry Andric     cmdRef = make<OutputSection>(name, SHT_PROGBITS, 0);
1560b57cec5SDimitry Andric   return cmdRef;
1570b57cec5SDimitry Andric }
1580b57cec5SDimitry Andric 
1590b57cec5SDimitry Andric // Expands the memory region by the specified size.
1600b57cec5SDimitry Andric static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,
1614824e7fdSDimitry Andric                                StringRef secName) {
1620b57cec5SDimitry Andric   memRegion->curPos += size;
1635ffd83dbSDimitry Andric   uint64_t newSize = memRegion->curPos - (memRegion->origin)().getValue();
1645ffd83dbSDimitry Andric   uint64_t length = (memRegion->length)().getValue();
1655ffd83dbSDimitry Andric   if (newSize > length)
1664824e7fdSDimitry Andric     error("section '" + secName + "' will not fit in region '" +
1674824e7fdSDimitry Andric           memRegion->name + "': overflowed by " + Twine(newSize - length) +
1684824e7fdSDimitry Andric           " bytes");
1690b57cec5SDimitry Andric }
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric void LinkerScript::expandMemoryRegions(uint64_t size) {
1720b57cec5SDimitry Andric   if (ctx->memRegion)
1734824e7fdSDimitry Andric     expandMemoryRegion(ctx->memRegion, size, ctx->outSec->name);
1740b57cec5SDimitry Andric   // Only expand the LMARegion if it is different from memRegion.
1750b57cec5SDimitry Andric   if (ctx->lmaRegion && ctx->memRegion != ctx->lmaRegion)
1764824e7fdSDimitry Andric     expandMemoryRegion(ctx->lmaRegion, size, ctx->outSec->name);
1770b57cec5SDimitry Andric }
1780b57cec5SDimitry Andric 
1790b57cec5SDimitry Andric void LinkerScript::expandOutputSection(uint64_t size) {
1800b57cec5SDimitry Andric   ctx->outSec->size += size;
1810b57cec5SDimitry Andric   expandMemoryRegions(size);
1820b57cec5SDimitry Andric }
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {
1850b57cec5SDimitry Andric   uint64_t val = e().getValue();
1860b57cec5SDimitry Andric   if (val < dot && inSec)
1870b57cec5SDimitry Andric     error(loc + ": unable to move location counter backward for: " +
1880b57cec5SDimitry Andric           ctx->outSec->name);
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   // Update to location counter means update to section size.
1910b57cec5SDimitry Andric   if (inSec)
1920b57cec5SDimitry Andric     expandOutputSection(val - dot);
1930b57cec5SDimitry Andric 
1940b57cec5SDimitry Andric   dot = val;
1950b57cec5SDimitry Andric }
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric // Used for handling linker symbol assignments, for both finalizing
1980b57cec5SDimitry Andric // their values and doing early declarations. Returns true if symbol
1990b57cec5SDimitry Andric // should be defined from linker script.
2000b57cec5SDimitry Andric static bool shouldDefineSym(SymbolAssignment *cmd) {
2010b57cec5SDimitry Andric   if (cmd->name == ".")
2020b57cec5SDimitry Andric     return false;
2030b57cec5SDimitry Andric 
2040b57cec5SDimitry Andric   if (!cmd->provide)
2050b57cec5SDimitry Andric     return true;
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   // If a symbol was in PROVIDE(), we need to define it only
2080b57cec5SDimitry Andric   // when it is a referenced undefined symbol.
2090b57cec5SDimitry Andric   Symbol *b = symtab->find(cmd->name);
2100b57cec5SDimitry Andric   if (b && !b->isDefined())
2110b57cec5SDimitry Andric     return true;
2120b57cec5SDimitry Andric   return false;
2130b57cec5SDimitry Andric }
2140b57cec5SDimitry Andric 
21585868e8aSDimitry Andric // Called by processSymbolAssignments() to assign definitions to
21685868e8aSDimitry Andric // linker-script-defined symbols.
2170b57cec5SDimitry Andric void LinkerScript::addSymbol(SymbolAssignment *cmd) {
2180b57cec5SDimitry Andric   if (!shouldDefineSym(cmd))
2190b57cec5SDimitry Andric     return;
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   // Define a symbol.
2220b57cec5SDimitry Andric   ExprValue value = cmd->expression();
2230b57cec5SDimitry Andric   SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;
2240b57cec5SDimitry Andric   uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
2250b57cec5SDimitry Andric 
2260b57cec5SDimitry Andric   // When this function is called, section addresses have not been
2270b57cec5SDimitry Andric   // fixed yet. So, we may or may not know the value of the RHS
2280b57cec5SDimitry Andric   // expression.
2290b57cec5SDimitry Andric   //
2300b57cec5SDimitry Andric   // For example, if an expression is `x = 42`, we know x is always 42.
2310b57cec5SDimitry Andric   // However, if an expression is `x = .`, there's no way to know its
2320b57cec5SDimitry Andric   // value at the moment.
2330b57cec5SDimitry Andric   //
2340b57cec5SDimitry Andric   // We want to set symbol values early if we can. This allows us to
2350b57cec5SDimitry Andric   // use symbols as variables in linker scripts. Doing so allows us to
2360b57cec5SDimitry Andric   // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
2370b57cec5SDimitry Andric   uint64_t symValue = value.sec ? 0 : value.getValue();
2380b57cec5SDimitry Andric 
23916d6b3b3SDimitry Andric   Defined newSym(nullptr, cmd->name, STB_GLOBAL, visibility, value.type,
24085868e8aSDimitry Andric                  symValue, 0, sec);
2410b57cec5SDimitry Andric 
2420b57cec5SDimitry Andric   Symbol *sym = symtab->insert(cmd->name);
24385868e8aSDimitry Andric   sym->mergeProperties(newSym);
24485868e8aSDimitry Andric   sym->replace(newSym);
2450b57cec5SDimitry Andric   cmd->sym = cast<Defined>(sym);
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric 
2480b57cec5SDimitry Andric // This function is called from LinkerScript::declareSymbols.
2490b57cec5SDimitry Andric // It creates a placeholder symbol if needed.
2500b57cec5SDimitry Andric static void declareSymbol(SymbolAssignment *cmd) {
2510b57cec5SDimitry Andric   if (!shouldDefineSym(cmd))
2520b57cec5SDimitry Andric     return;
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
25585868e8aSDimitry Andric   Defined newSym(nullptr, cmd->name, STB_GLOBAL, visibility, STT_NOTYPE, 0, 0,
2560b57cec5SDimitry Andric                  nullptr);
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric   // We can't calculate final value right now.
2590b57cec5SDimitry Andric   Symbol *sym = symtab->insert(cmd->name);
26085868e8aSDimitry Andric   sym->mergeProperties(newSym);
26185868e8aSDimitry Andric   sym->replace(newSym);
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric   cmd->sym = cast<Defined>(sym);
2640b57cec5SDimitry Andric   cmd->provide = false;
2650b57cec5SDimitry Andric   sym->scriptDefined = true;
2660b57cec5SDimitry Andric }
2670b57cec5SDimitry Andric 
26885868e8aSDimitry Andric using SymbolAssignmentMap =
26985868e8aSDimitry Andric     DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;
27085868e8aSDimitry Andric 
27185868e8aSDimitry Andric // Collect section/value pairs of linker-script-defined symbols. This is used to
27285868e8aSDimitry Andric // check whether symbol values converge.
273*04eeddc0SDimitry Andric static SymbolAssignmentMap
274*04eeddc0SDimitry Andric getSymbolAssignmentValues(ArrayRef<SectionCommand *> sectionCommands) {
27585868e8aSDimitry Andric   SymbolAssignmentMap ret;
2764824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands) {
2774824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
2784824e7fdSDimitry Andric       if (assign->sym) // sym is nullptr for dot.
2794824e7fdSDimitry Andric         ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
2804824e7fdSDimitry Andric                                                     assign->sym->value));
28185868e8aSDimitry Andric       continue;
28285868e8aSDimitry Andric     }
2834824e7fdSDimitry Andric     for (SectionCommand *subCmd : cast<OutputSection>(cmd)->commands)
2844824e7fdSDimitry Andric       if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
2854824e7fdSDimitry Andric         if (assign->sym)
2864824e7fdSDimitry Andric           ret.try_emplace(assign->sym, std::make_pair(assign->sym->section,
2874824e7fdSDimitry Andric                                                       assign->sym->value));
28885868e8aSDimitry Andric   }
28985868e8aSDimitry Andric   return ret;
29085868e8aSDimitry Andric }
29185868e8aSDimitry Andric 
29285868e8aSDimitry Andric // Returns the lexicographical smallest (for determinism) Defined whose
29385868e8aSDimitry Andric // section/value has changed.
29485868e8aSDimitry Andric static const Defined *
29585868e8aSDimitry Andric getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {
29685868e8aSDimitry Andric   const Defined *changed = nullptr;
29785868e8aSDimitry Andric   for (auto &it : oldValues) {
29885868e8aSDimitry Andric     const Defined *sym = it.first;
29985868e8aSDimitry Andric     if (std::make_pair(sym->section, sym->value) != it.second &&
30085868e8aSDimitry Andric         (!changed || sym->getName() < changed->getName()))
30185868e8aSDimitry Andric       changed = sym;
30285868e8aSDimitry Andric   }
30385868e8aSDimitry Andric   return changed;
30485868e8aSDimitry Andric }
30585868e8aSDimitry Andric 
3065ffd83dbSDimitry Andric // Process INSERT [AFTER|BEFORE] commands. For each command, we move the
3075ffd83dbSDimitry Andric // specified output section to the designated place.
3080b57cec5SDimitry Andric void LinkerScript::processInsertCommands() {
309*04eeddc0SDimitry Andric   SmallVector<OutputSection *, 0> moves;
3105ffd83dbSDimitry Andric   for (const InsertCommand &cmd : insertCommands) {
311fe6060f1SDimitry Andric     for (StringRef name : cmd.names) {
312fe6060f1SDimitry Andric       // If base is empty, it may have been discarded by
3135ffd83dbSDimitry Andric       // adjustSectionsBeforeSorting(). We do not handle such output sections.
3144824e7fdSDimitry Andric       auto from = llvm::find_if(sectionCommands, [&](SectionCommand *subCmd) {
3154824e7fdSDimitry Andric         return isa<OutputSection>(subCmd) &&
3164824e7fdSDimitry Andric                cast<OutputSection>(subCmd)->name == name;
317fe6060f1SDimitry Andric       });
3185ffd83dbSDimitry Andric       if (from == sectionCommands.end())
3190b57cec5SDimitry Andric         continue;
320fe6060f1SDimitry Andric       moves.push_back(cast<OutputSection>(*from));
3215ffd83dbSDimitry Andric       sectionCommands.erase(from);
322fe6060f1SDimitry Andric     }
3230b57cec5SDimitry Andric 
3244824e7fdSDimitry Andric     auto insertPos =
3254824e7fdSDimitry Andric         llvm::find_if(sectionCommands, [&cmd](SectionCommand *subCmd) {
3264824e7fdSDimitry Andric           auto *to = dyn_cast<OutputSection>(subCmd);
3275ffd83dbSDimitry Andric           return to != nullptr && to->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.
3440b57cec5SDimitry Andric void LinkerScript::declareSymbols() {
3450b57cec5SDimitry Andric   assert(!ctx);
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.
3564824e7fdSDimitry Andric     auto *sec = cast<OutputSection>(cmd);
3570b57cec5SDimitry Andric     if (sec->constraint != ConstraintKind::NoConstraint)
3580b57cec5SDimitry Andric       continue;
3594824e7fdSDimitry 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.
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 
388e8d8bef9SDimitry Andric static inline StringRef getFilename(const InputFile *file) {
389e8d8bef9SDimitry Andric   return file ? file->getNameForScript() : StringRef();
390e8d8bef9SDimitry Andric }
391e8d8bef9SDimitry Andric 
392e8d8bef9SDimitry 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 
402e8d8bef9SDimitry 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 
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.
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 
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.
44285868e8aSDimitry Andric     return a->alignment > b->alignment;
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);
46185868e8aSDimitry Andric   }
4620b57cec5SDimitry Andric }
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric // Sort sections as instructed by SORT-family commands and --sort-section
4650b57cec5SDimitry Andric // option. Because SORT-family commands can be nested at most two depth
4660b57cec5SDimitry Andric // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
4670b57cec5SDimitry Andric // line option is respected even if a SORT command is given, the exact
4680b57cec5SDimitry Andric // behavior we have here is a bit complicated. Here are the rules.
4690b57cec5SDimitry Andric //
4700b57cec5SDimitry Andric // 1. If two SORT commands are given, --sort-section is ignored.
4710b57cec5SDimitry Andric // 2. If one SORT command is given, and if it is not SORT_NONE,
4720b57cec5SDimitry Andric //    --sort-section is handled as an inner SORT command.
4730b57cec5SDimitry Andric // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
4740b57cec5SDimitry Andric // 4. If no SORT command is given, sort according to --sort-section.
47585868e8aSDimitry Andric static void sortInputSections(MutableArrayRef<InputSectionBase *> vec,
476e8d8bef9SDimitry Andric                               SortSectionPolicy outer,
477e8d8bef9SDimitry Andric                               SortSectionPolicy inner) {
478e8d8bef9SDimitry Andric   if (outer == SortSectionPolicy::None)
4790b57cec5SDimitry Andric     return;
4800b57cec5SDimitry Andric 
481e8d8bef9SDimitry Andric   if (inner == SortSectionPolicy::Default)
4820b57cec5SDimitry Andric     sortSections(vec, config->sortSection);
4830b57cec5SDimitry Andric   else
484e8d8bef9SDimitry Andric     sortSections(vec, inner);
485e8d8bef9SDimitry Andric   sortSections(vec, outer);
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric 
4880b57cec5SDimitry Andric // Compute and remember which sections the InputSectionDescription matches.
489*04eeddc0SDimitry Andric SmallVector<InputSectionBase *, 0>
4905ffd83dbSDimitry Andric LinkerScript::computeInputSections(const InputSectionDescription *cmd,
4915ffd83dbSDimitry Andric                                    ArrayRef<InputSectionBase *> sections) {
492*04eeddc0SDimitry Andric   SmallVector<InputSectionBase *, 0> ret;
493*04eeddc0SDimitry Andric   SmallVector<size_t, 0> indexes;
494e8d8bef9SDimitry Andric   DenseSet<size_t> seen;
495e8d8bef9SDimitry Andric   auto sortByPositionThenCommandLine = [&](size_t begin, size_t end) {
496e8d8bef9SDimitry Andric     llvm::sort(MutableArrayRef<size_t>(indexes).slice(begin, end - begin));
497e8d8bef9SDimitry Andric     for (size_t i = begin; i != end; ++i)
498e8d8bef9SDimitry Andric       ret[i] = sections[indexes[i]];
499e8d8bef9SDimitry Andric     sortInputSections(
500e8d8bef9SDimitry Andric         MutableArrayRef<InputSectionBase *>(ret).slice(begin, end - begin),
501e8d8bef9SDimitry Andric         config->sortSection, SortSectionPolicy::None);
502e8d8bef9SDimitry Andric   };
5030b57cec5SDimitry Andric 
5040b57cec5SDimitry Andric   // Collects all sections that satisfy constraints of Cmd.
505e8d8bef9SDimitry Andric   size_t sizeAfterPrevSort = 0;
5060b57cec5SDimitry Andric   for (const SectionPattern &pat : cmd->sectionPatterns) {
507e8d8bef9SDimitry Andric     size_t sizeBeforeCurrPat = ret.size();
5080b57cec5SDimitry Andric 
509e8d8bef9SDimitry Andric     for (size_t i = 0, e = sections.size(); i != e; ++i) {
510e8d8bef9SDimitry Andric       // Skip if the section is dead or has been matched by a previous input
511e8d8bef9SDimitry Andric       // section description or a previous pattern.
512e8d8bef9SDimitry Andric       InputSectionBase *sec = sections[i];
513e8d8bef9SDimitry Andric       if (!sec->isLive() || sec->parent || seen.contains(i))
5140b57cec5SDimitry Andric         continue;
5150b57cec5SDimitry Andric 
516349cc55cSDimitry Andric       // For --emit-relocs we have to ignore entries like
5170b57cec5SDimitry Andric       //   .rela.dyn : { *(.rela.data) }
5180b57cec5SDimitry Andric       // which are common because they are in the default bfd script.
5190b57cec5SDimitry Andric       // We do not ignore SHT_REL[A] linker-synthesized sections here because
5200b57cec5SDimitry Andric       // want to support scripts that do custom layout for them.
52185868e8aSDimitry Andric       if (isa<InputSection>(sec) &&
52285868e8aSDimitry Andric           cast<InputSection>(sec)->getRelocatedSection())
5230b57cec5SDimitry Andric         continue;
5240b57cec5SDimitry Andric 
5255ffd83dbSDimitry Andric       // Check the name early to improve performance in the common case.
5265ffd83dbSDimitry Andric       if (!pat.sectionPat.match(sec->name))
5275ffd83dbSDimitry Andric         continue;
5285ffd83dbSDimitry Andric 
529e8d8bef9SDimitry Andric       if (!cmd->matchesFile(sec->file) || pat.excludesFile(sec->file) ||
5305ffd83dbSDimitry Andric           (sec->flags & cmd->withFlags) != cmd->withFlags ||
5315ffd83dbSDimitry Andric           (sec->flags & cmd->withoutFlags) != 0)
5320b57cec5SDimitry Andric         continue;
5330b57cec5SDimitry Andric 
53485868e8aSDimitry Andric       ret.push_back(sec);
535e8d8bef9SDimitry Andric       indexes.push_back(i);
536e8d8bef9SDimitry Andric       seen.insert(i);
5370b57cec5SDimitry Andric     }
5380b57cec5SDimitry Andric 
539e8d8bef9SDimitry Andric     if (pat.sortOuter == SortSectionPolicy::Default)
540e8d8bef9SDimitry Andric       continue;
541e8d8bef9SDimitry Andric 
542e8d8bef9SDimitry Andric     // Matched sections are ordered by radix sort with the keys being (SORT*,
543e8d8bef9SDimitry Andric     // --sort-section, input order), where SORT* (if present) is most
544e8d8bef9SDimitry Andric     // significant.
545e8d8bef9SDimitry Andric     //
546e8d8bef9SDimitry Andric     // Matched sections between the previous SORT* and this SORT* are sorted by
547e8d8bef9SDimitry Andric     // (--sort-alignment, input order).
548e8d8bef9SDimitry Andric     sortByPositionThenCommandLine(sizeAfterPrevSort, sizeBeforeCurrPat);
549e8d8bef9SDimitry Andric     // Matched sections by this SORT* pattern are sorted using all 3 keys.
550e8d8bef9SDimitry Andric     // ret[sizeBeforeCurrPat,ret.size()) are already in the input order, so we
551e8d8bef9SDimitry Andric     // just sort by sortOuter and sortInner.
55285868e8aSDimitry Andric     sortInputSections(
553e8d8bef9SDimitry Andric         MutableArrayRef<InputSectionBase *>(ret).slice(sizeBeforeCurrPat),
554e8d8bef9SDimitry Andric         pat.sortOuter, pat.sortInner);
555e8d8bef9SDimitry Andric     sizeAfterPrevSort = ret.size();
5560b57cec5SDimitry Andric   }
557e8d8bef9SDimitry Andric   // Matched sections after the last SORT* are sorted by (--sort-alignment,
558e8d8bef9SDimitry Andric   // input order).
559e8d8bef9SDimitry Andric   sortByPositionThenCommandLine(sizeAfterPrevSort, ret.size());
5600b57cec5SDimitry Andric   return ret;
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric 
5630eae32dcSDimitry Andric void LinkerScript::discard(InputSectionBase &s) {
564*04eeddc0SDimitry Andric   if (&s == in.shStrTab.get())
5650eae32dcSDimitry Andric     error("discarding " + s.name + " section is not allowed");
5660b57cec5SDimitry Andric 
5670eae32dcSDimitry Andric   s.markDead();
5680eae32dcSDimitry Andric   s.parent = nullptr;
5690eae32dcSDimitry Andric   for (InputSection *sec : s.dependentSections)
5700eae32dcSDimitry Andric     discard(*sec);
5710b57cec5SDimitry Andric }
5720b57cec5SDimitry Andric 
5735ffd83dbSDimitry Andric void LinkerScript::discardSynthetic(OutputSection &outCmd) {
5745ffd83dbSDimitry Andric   for (Partition &part : partitions) {
5755ffd83dbSDimitry Andric     if (!part.armExidx || !part.armExidx->isLive())
5765ffd83dbSDimitry Andric       continue;
577*04eeddc0SDimitry Andric     SmallVector<InputSectionBase *, 0> secs(
578*04eeddc0SDimitry Andric         part.armExidx->exidxSections.begin(),
5795ffd83dbSDimitry Andric         part.armExidx->exidxSections.end());
5804824e7fdSDimitry Andric     for (SectionCommand *cmd : outCmd.commands)
581*04eeddc0SDimitry Andric       if (auto *isd = dyn_cast<InputSectionDescription>(cmd))
582*04eeddc0SDimitry Andric         for (InputSectionBase *s : computeInputSections(isd, secs))
5830eae32dcSDimitry Andric           discard(*s);
5845ffd83dbSDimitry Andric   }
5855ffd83dbSDimitry Andric }
5865ffd83dbSDimitry Andric 
587*04eeddc0SDimitry Andric SmallVector<InputSectionBase *, 0>
5880b57cec5SDimitry Andric LinkerScript::createInputSectionList(OutputSection &outCmd) {
589*04eeddc0SDimitry Andric   SmallVector<InputSectionBase *, 0> ret;
5900b57cec5SDimitry Andric 
5914824e7fdSDimitry Andric   for (SectionCommand *cmd : outCmd.commands) {
5924824e7fdSDimitry Andric     if (auto *isd = dyn_cast<InputSectionDescription>(cmd)) {
5934824e7fdSDimitry Andric       isd->sectionBases = computeInputSections(isd, inputSections);
5944824e7fdSDimitry Andric       for (InputSectionBase *s : isd->sectionBases)
59585868e8aSDimitry Andric         s->parent = &outCmd;
5964824e7fdSDimitry Andric       ret.insert(ret.end(), isd->sectionBases.begin(), isd->sectionBases.end());
5970b57cec5SDimitry Andric     }
5980b57cec5SDimitry Andric   }
5990b57cec5SDimitry Andric   return ret;
6000b57cec5SDimitry Andric }
6010b57cec5SDimitry Andric 
60285868e8aSDimitry Andric // Create output sections described by SECTIONS commands.
6030b57cec5SDimitry Andric void LinkerScript::processSectionCommands() {
604fe6060f1SDimitry Andric   auto process = [this](OutputSection *osec) {
605*04eeddc0SDimitry Andric     SmallVector<InputSectionBase *, 0> v = createInputSectionList(*osec);
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric     // The output section name `/DISCARD/' is special.
6080b57cec5SDimitry Andric     // Any input section assigned to it is discarded.
609fe6060f1SDimitry Andric     if (osec->name == "/DISCARD/") {
61085868e8aSDimitry Andric       for (InputSectionBase *s : v)
6110eae32dcSDimitry Andric         discard(*s);
612fe6060f1SDimitry Andric       discardSynthetic(*osec);
6134824e7fdSDimitry Andric       osec->commands.clear();
614fe6060f1SDimitry Andric       return false;
6150b57cec5SDimitry Andric     }
6160b57cec5SDimitry Andric 
6170b57cec5SDimitry Andric     // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
6180b57cec5SDimitry Andric     // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
6190b57cec5SDimitry Andric     // sections satisfy a given constraint. If not, a directive is handled
6200b57cec5SDimitry Andric     // as if it wasn't present from the beginning.
6210b57cec5SDimitry Andric     //
6220b57cec5SDimitry Andric     // Because we'll iterate over SectionCommands many more times, the easy
6230b57cec5SDimitry Andric     // way to "make it as if it wasn't present" is to make it empty.
624fe6060f1SDimitry Andric     if (!matchConstraints(v, osec->constraint)) {
6250b57cec5SDimitry Andric       for (InputSectionBase *s : v)
62685868e8aSDimitry Andric         s->parent = nullptr;
6274824e7fdSDimitry Andric       osec->commands.clear();
628fe6060f1SDimitry Andric       return false;
6290b57cec5SDimitry Andric     }
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric     // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
6320b57cec5SDimitry Andric     // is given, input sections are aligned to that value, whether the
6330b57cec5SDimitry Andric     // given value is larger or smaller than the original section alignment.
634fe6060f1SDimitry Andric     if (osec->subalignExpr) {
635fe6060f1SDimitry Andric       uint32_t subalign = osec->subalignExpr().getValue();
6360b57cec5SDimitry Andric       for (InputSectionBase *s : v)
6370b57cec5SDimitry Andric         s->alignment = subalign;
6380b57cec5SDimitry Andric     }
6390b57cec5SDimitry Andric 
64085868e8aSDimitry Andric     // Set the partition field the same way OutputSection::recordSection()
64185868e8aSDimitry Andric     // does. Partitions cannot be used with the SECTIONS command, so this is
64285868e8aSDimitry Andric     // always 1.
643fe6060f1SDimitry Andric     osec->partition = 1;
644fe6060f1SDimitry Andric     return true;
645fe6060f1SDimitry Andric   };
6460b57cec5SDimitry Andric 
647fe6060f1SDimitry Andric   // Process OVERWRITE_SECTIONS first so that it can overwrite the main script
648fe6060f1SDimitry Andric   // or orphans.
649*04eeddc0SDimitry Andric   DenseMap<CachedHashStringRef, OutputSection *> map;
650fe6060f1SDimitry Andric   size_t i = 0;
651fe6060f1SDimitry Andric   for (OutputSection *osec : overwriteSections)
652*04eeddc0SDimitry Andric     if (process(osec) &&
653*04eeddc0SDimitry Andric         !map.try_emplace(CachedHashStringRef(osec->name), osec).second)
654fe6060f1SDimitry Andric       warn("OVERWRITE_SECTIONS specifies duplicate " + osec->name);
6554824e7fdSDimitry Andric   for (SectionCommand *&base : sectionCommands)
656fe6060f1SDimitry Andric     if (auto *osec = dyn_cast<OutputSection>(base)) {
657*04eeddc0SDimitry Andric       if (OutputSection *overwrite =
658*04eeddc0SDimitry Andric               map.lookup(CachedHashStringRef(osec->name))) {
659fe6060f1SDimitry Andric         log(overwrite->location + " overwrites " + osec->name);
660fe6060f1SDimitry Andric         overwrite->sectionIndex = i++;
661fe6060f1SDimitry Andric         base = overwrite;
662fe6060f1SDimitry Andric       } else if (process(osec)) {
663fe6060f1SDimitry Andric         osec->sectionIndex = i++;
6640b57cec5SDimitry Andric       }
6650b57cec5SDimitry Andric     }
666fe6060f1SDimitry Andric 
667fe6060f1SDimitry Andric   // If an OVERWRITE_SECTIONS specified output section is not in
668fe6060f1SDimitry Andric   // sectionCommands, append it to the end. The section will be inserted by
669fe6060f1SDimitry Andric   // orphan placement.
670fe6060f1SDimitry Andric   for (OutputSection *osec : overwriteSections)
671fe6060f1SDimitry Andric     if (osec->partition == 1 && osec->sectionIndex == UINT32_MAX)
672fe6060f1SDimitry Andric       sectionCommands.push_back(osec);
67385868e8aSDimitry Andric }
67485868e8aSDimitry Andric 
67585868e8aSDimitry Andric void LinkerScript::processSymbolAssignments() {
67685868e8aSDimitry Andric   // Dot outside an output section still represents a relative address, whose
67785868e8aSDimitry Andric   // sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section
67885868e8aSDimitry Andric   // that fills the void outside a section. It has an index of one, which is
67985868e8aSDimitry Andric   // indistinguishable from any other regular section index.
68085868e8aSDimitry Andric   aether = make<OutputSection>("", 0, SHF_ALLOC);
68185868e8aSDimitry Andric   aether->sectionIndex = 1;
68285868e8aSDimitry Andric 
68385868e8aSDimitry Andric   // ctx captures the local AddressState and makes it accessible deliberately.
68485868e8aSDimitry Andric   // This is needed as there are some cases where we cannot just thread the
68585868e8aSDimitry Andric   // current state through to a lambda function created by the script parser.
68685868e8aSDimitry Andric   AddressState state;
68785868e8aSDimitry Andric   ctx = &state;
68885868e8aSDimitry Andric   ctx->outSec = aether;
68985868e8aSDimitry Andric 
6904824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands) {
6914824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd))
6924824e7fdSDimitry Andric       addSymbol(assign);
69385868e8aSDimitry Andric     else
6944824e7fdSDimitry Andric       for (SectionCommand *subCmd : cast<OutputSection>(cmd)->commands)
6954824e7fdSDimitry Andric         if (auto *assign = dyn_cast<SymbolAssignment>(subCmd))
6964824e7fdSDimitry Andric           addSymbol(assign);
69785868e8aSDimitry Andric   }
69885868e8aSDimitry Andric 
6990b57cec5SDimitry Andric   ctx = nullptr;
7000b57cec5SDimitry Andric }
7010b57cec5SDimitry Andric 
7024824e7fdSDimitry Andric static OutputSection *findByName(ArrayRef<SectionCommand *> vec,
7030b57cec5SDimitry Andric                                  StringRef name) {
7044824e7fdSDimitry Andric   for (SectionCommand *cmd : vec)
7054824e7fdSDimitry Andric     if (auto *sec = dyn_cast<OutputSection>(cmd))
7060b57cec5SDimitry Andric       if (sec->name == name)
7070b57cec5SDimitry Andric         return sec;
7080b57cec5SDimitry Andric   return nullptr;
7090b57cec5SDimitry Andric }
7100b57cec5SDimitry Andric 
7110b57cec5SDimitry Andric static OutputSection *createSection(InputSectionBase *isec,
7120b57cec5SDimitry Andric                                     StringRef outsecName) {
7130b57cec5SDimitry Andric   OutputSection *sec = script->createOutputSection(outsecName, "<internal>");
71485868e8aSDimitry Andric   sec->recordSection(isec);
7150b57cec5SDimitry Andric   return sec;
7160b57cec5SDimitry Andric }
7170b57cec5SDimitry Andric 
7180b57cec5SDimitry Andric static OutputSection *
7190b57cec5SDimitry Andric addInputSec(StringMap<TinyPtrVector<OutputSection *>> &map,
7200b57cec5SDimitry Andric             InputSectionBase *isec, StringRef outsecName) {
7210b57cec5SDimitry Andric   // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r
7220b57cec5SDimitry Andric   // option is given. A section with SHT_GROUP defines a "section group", and
7230b57cec5SDimitry Andric   // its members have SHF_GROUP attribute. Usually these flags have already been
7240b57cec5SDimitry Andric   // stripped by InputFiles.cpp as section groups are processed and uniquified.
7250b57cec5SDimitry Andric   // However, for the -r option, we want to pass through all section groups
7260b57cec5SDimitry Andric   // as-is because adding/removing members or merging them with other groups
7270b57cec5SDimitry Andric   // change their semantics.
7280b57cec5SDimitry Andric   if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))
7290b57cec5SDimitry Andric     return createSection(isec, outsecName);
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric   // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
7320b57cec5SDimitry Andric   // relocation sections .rela.foo and .rela.bar for example. Most tools do
7330b57cec5SDimitry Andric   // not allow multiple REL[A] sections for output section. Hence we
7340b57cec5SDimitry Andric   // should combine these relocation sections into single output.
7350b57cec5SDimitry Andric   // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
7360b57cec5SDimitry Andric   // other REL[A] sections created by linker itself.
7370b57cec5SDimitry Andric   if (!isa<SyntheticSection>(isec) &&
7380b57cec5SDimitry Andric       (isec->type == SHT_REL || isec->type == SHT_RELA)) {
7390b57cec5SDimitry Andric     auto *sec = cast<InputSection>(isec);
7400b57cec5SDimitry Andric     OutputSection *out = sec->getRelocatedSection()->getOutputSection();
7410b57cec5SDimitry Andric 
7420b57cec5SDimitry Andric     if (out->relocationSection) {
74385868e8aSDimitry Andric       out->relocationSection->recordSection(sec);
7440b57cec5SDimitry Andric       return nullptr;
7450b57cec5SDimitry Andric     }
7460b57cec5SDimitry Andric 
7470b57cec5SDimitry Andric     out->relocationSection = createSection(isec, outsecName);
7480b57cec5SDimitry Andric     return out->relocationSection;
7490b57cec5SDimitry Andric   }
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric   //  The ELF spec just says
7520b57cec5SDimitry Andric   // ----------------------------------------------------------------
7530b57cec5SDimitry Andric   // In the first phase, input sections that match in name, type and
7540b57cec5SDimitry Andric   // attribute flags should be concatenated into single sections.
7550b57cec5SDimitry Andric   // ----------------------------------------------------------------
7560b57cec5SDimitry Andric   //
7570b57cec5SDimitry Andric   // However, it is clear that at least some flags have to be ignored for
7580b57cec5SDimitry Andric   // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
7590b57cec5SDimitry Andric   // ignored. We should not have two output .text sections just because one was
7600b57cec5SDimitry Andric   // in a group and another was not for example.
7610b57cec5SDimitry Andric   //
7620b57cec5SDimitry Andric   // It also seems that wording was a late addition and didn't get the
7630b57cec5SDimitry Andric   // necessary scrutiny.
7640b57cec5SDimitry Andric   //
7650b57cec5SDimitry Andric   // Merging sections with different flags is expected by some users. One
7660b57cec5SDimitry Andric   // reason is that if one file has
7670b57cec5SDimitry Andric   //
7680b57cec5SDimitry Andric   // int *const bar __attribute__((section(".foo"))) = (int *)0;
7690b57cec5SDimitry Andric   //
7700b57cec5SDimitry Andric   // gcc with -fPIC will produce a read only .foo section. But if another
7710b57cec5SDimitry Andric   // file has
7720b57cec5SDimitry Andric   //
7730b57cec5SDimitry Andric   // int zed;
7740b57cec5SDimitry Andric   // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
7750b57cec5SDimitry Andric   //
7760b57cec5SDimitry Andric   // gcc with -fPIC will produce a read write section.
7770b57cec5SDimitry Andric   //
7780b57cec5SDimitry Andric   // Last but not least, when using linker script the merge rules are forced by
7790b57cec5SDimitry Andric   // the script. Unfortunately, linker scripts are name based. This means that
7800b57cec5SDimitry Andric   // expressions like *(.foo*) can refer to multiple input sections with
7810b57cec5SDimitry Andric   // different flags. We cannot put them in different output sections or we
7820b57cec5SDimitry Andric   // would produce wrong results for
7830b57cec5SDimitry Andric   //
7840b57cec5SDimitry Andric   // start = .; *(.foo.*) end = .; *(.bar)
7850b57cec5SDimitry Andric   //
7860b57cec5SDimitry Andric   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
7870b57cec5SDimitry Andric   // another. The problem is that there is no way to layout those output
7880b57cec5SDimitry Andric   // sections such that the .foo sections are the only thing between the start
7890b57cec5SDimitry Andric   // and end symbols.
7900b57cec5SDimitry Andric   //
7910b57cec5SDimitry Andric   // Given the above issues, we instead merge sections by name and error on
7920b57cec5SDimitry Andric   // incompatible types and flags.
7930b57cec5SDimitry Andric   TinyPtrVector<OutputSection *> &v = map[outsecName];
7940b57cec5SDimitry Andric   for (OutputSection *sec : v) {
7950b57cec5SDimitry Andric     if (sec->partition != isec->partition)
7960b57cec5SDimitry Andric       continue;
79785868e8aSDimitry Andric 
79885868e8aSDimitry Andric     if (config->relocatable && (isec->flags & SHF_LINK_ORDER)) {
79985868e8aSDimitry Andric       // Merging two SHF_LINK_ORDER sections with different sh_link fields will
80085868e8aSDimitry Andric       // change their semantics, so we only merge them in -r links if they will
80185868e8aSDimitry Andric       // end up being linked to the same output section. The casts are fine
80285868e8aSDimitry Andric       // because everything in the map was created by the orphan placement code.
80385868e8aSDimitry Andric       auto *firstIsec = cast<InputSectionBase>(
8044824e7fdSDimitry Andric           cast<InputSectionDescription>(sec->commands[0])->sectionBases[0]);
805eaeb601bSDimitry Andric       OutputSection *firstIsecOut =
806eaeb601bSDimitry Andric           firstIsec->flags & SHF_LINK_ORDER
807eaeb601bSDimitry Andric               ? firstIsec->getLinkOrderDep()->getOutputSection()
808eaeb601bSDimitry Andric               : nullptr;
809eaeb601bSDimitry Andric       if (firstIsecOut != isec->getLinkOrderDep()->getOutputSection())
81085868e8aSDimitry Andric         continue;
81185868e8aSDimitry Andric     }
81285868e8aSDimitry Andric 
81385868e8aSDimitry Andric     sec->recordSection(isec);
8140b57cec5SDimitry Andric     return nullptr;
8150b57cec5SDimitry Andric   }
8160b57cec5SDimitry Andric 
8170b57cec5SDimitry Andric   OutputSection *sec = createSection(isec, outsecName);
8180b57cec5SDimitry Andric   v.push_back(sec);
8190b57cec5SDimitry Andric   return sec;
8200b57cec5SDimitry Andric }
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric // Add sections that didn't match any sections command.
8230b57cec5SDimitry Andric void LinkerScript::addOrphanSections() {
8240b57cec5SDimitry Andric   StringMap<TinyPtrVector<OutputSection *>> map;
825*04eeddc0SDimitry Andric   SmallVector<OutputSection *, 0> v;
8260b57cec5SDimitry Andric 
827*04eeddc0SDimitry Andric   auto add = [&](InputSectionBase *s) {
82885868e8aSDimitry Andric     if (s->isLive() && !s->parent) {
8295ffd83dbSDimitry Andric       orphanSections.push_back(s);
8305ffd83dbSDimitry Andric 
8310b57cec5SDimitry Andric       StringRef name = getOutputSectionName(s);
8325ffd83dbSDimitry Andric       if (config->unique) {
8335ffd83dbSDimitry Andric         v.push_back(createSection(s, name));
8345ffd83dbSDimitry Andric       } else if (OutputSection *sec = findByName(sectionCommands, name)) {
83585868e8aSDimitry Andric         sec->recordSection(s);
83685868e8aSDimitry Andric       } else {
8370b57cec5SDimitry Andric         if (OutputSection *os = addInputSec(map, s, name))
8380b57cec5SDimitry Andric           v.push_back(os);
83985868e8aSDimitry Andric         assert(isa<MergeInputSection>(s) ||
84085868e8aSDimitry Andric                s->getOutputSection()->sectionIndex == UINT32_MAX);
84185868e8aSDimitry Andric       }
84285868e8aSDimitry Andric     }
8430b57cec5SDimitry Andric   };
8440b57cec5SDimitry Andric 
845fe6060f1SDimitry Andric   // For further --emit-reloc handling code we need target output section
8460b57cec5SDimitry Andric   // to be created before we create relocation output section, so we want
8470b57cec5SDimitry Andric   // to create target sections first. We do not want priority handling
8480b57cec5SDimitry Andric   // for synthetic sections because them are special.
8490b57cec5SDimitry Andric   for (InputSectionBase *isec : inputSections) {
85085868e8aSDimitry Andric     // In -r links, SHF_LINK_ORDER sections are added while adding their parent
85185868e8aSDimitry Andric     // sections because we need to know the parent's output section before we
85285868e8aSDimitry Andric     // can select an output section for the SHF_LINK_ORDER section.
85385868e8aSDimitry Andric     if (config->relocatable && (isec->flags & SHF_LINK_ORDER))
85485868e8aSDimitry Andric       continue;
85585868e8aSDimitry Andric 
8560b57cec5SDimitry Andric     if (auto *sec = dyn_cast<InputSection>(isec))
8570b57cec5SDimitry Andric       if (InputSectionBase *rel = sec->getRelocatedSection())
8580b57cec5SDimitry Andric         if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent))
8590b57cec5SDimitry Andric           add(relIS);
8600b57cec5SDimitry Andric     add(isec);
861*04eeddc0SDimitry Andric     if (config->relocatable)
862*04eeddc0SDimitry Andric       for (InputSectionBase *depSec : isec->dependentSections)
863*04eeddc0SDimitry Andric         if (depSec->flags & SHF_LINK_ORDER)
864*04eeddc0SDimitry Andric           add(depSec);
8650b57cec5SDimitry Andric   }
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric   // If no SECTIONS command was given, we should insert sections commands
8680b57cec5SDimitry Andric   // before others, so that we can handle scripts which refers them,
8690b57cec5SDimitry Andric   // for example: "foo = ABSOLUTE(ADDR(.text)));".
8700b57cec5SDimitry Andric   // When SECTIONS command is present we just add all orphans to the end.
8710b57cec5SDimitry Andric   if (hasSectionsCommand)
8720b57cec5SDimitry Andric     sectionCommands.insert(sectionCommands.end(), v.begin(), v.end());
8730b57cec5SDimitry Andric   else
8740b57cec5SDimitry Andric     sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end());
8750b57cec5SDimitry Andric }
8760b57cec5SDimitry Andric 
8775ffd83dbSDimitry Andric void LinkerScript::diagnoseOrphanHandling() const {
878e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Diagnose orphan sections");
879e8d8bef9SDimitry Andric   if (config->orphanHandling == OrphanHandlingPolicy::Place)
880e8d8bef9SDimitry Andric     return;
8815ffd83dbSDimitry Andric   for (const InputSectionBase *sec : orphanSections) {
8825ffd83dbSDimitry Andric     // Input SHT_REL[A] retained by --emit-relocs are ignored by
8835ffd83dbSDimitry Andric     // computeInputSections(). Don't warn/error.
8845ffd83dbSDimitry Andric     if (isa<InputSection>(sec) &&
8855ffd83dbSDimitry Andric         cast<InputSection>(sec)->getRelocatedSection())
8865ffd83dbSDimitry Andric       continue;
8875ffd83dbSDimitry Andric 
8885ffd83dbSDimitry Andric     StringRef name = getOutputSectionName(sec);
8895ffd83dbSDimitry Andric     if (config->orphanHandling == OrphanHandlingPolicy::Error)
8905ffd83dbSDimitry Andric       error(toString(sec) + " is being placed in '" + name + "'");
891e8d8bef9SDimitry Andric     else
8925ffd83dbSDimitry Andric       warn(toString(sec) + " is being placed in '" + name + "'");
8935ffd83dbSDimitry Andric   }
8945ffd83dbSDimitry Andric }
8955ffd83dbSDimitry Andric 
8960b57cec5SDimitry Andric // This function searches for a memory region to place the given output
8970b57cec5SDimitry Andric // section in. If found, a pointer to the appropriate memory region is
898349cc55cSDimitry Andric // returned in the first member of the pair. Otherwise, a nullptr is returned.
899349cc55cSDimitry Andric // The second member of the pair is a hint that should be passed to the
900349cc55cSDimitry Andric // subsequent call of this method.
901349cc55cSDimitry Andric std::pair<MemoryRegion *, MemoryRegion *>
902349cc55cSDimitry Andric LinkerScript::findMemoryRegion(OutputSection *sec, MemoryRegion *hint) {
903349cc55cSDimitry Andric   // Non-allocatable sections are not part of the process image.
904349cc55cSDimitry Andric   if (!(sec->flags & SHF_ALLOC)) {
905349cc55cSDimitry Andric     if (!sec->memoryRegionName.empty())
906349cc55cSDimitry Andric       warn("ignoring memory region assignment for non-allocatable section '" +
907349cc55cSDimitry Andric            sec->name + "'");
908349cc55cSDimitry Andric     return {nullptr, nullptr};
909349cc55cSDimitry Andric   }
910349cc55cSDimitry Andric 
9110b57cec5SDimitry Andric   // If a memory region name was specified in the output section command,
9120b57cec5SDimitry Andric   // then try to find that region first.
9130b57cec5SDimitry Andric   if (!sec->memoryRegionName.empty()) {
9140b57cec5SDimitry Andric     if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName))
915349cc55cSDimitry Andric       return {m, m};
9160b57cec5SDimitry Andric     error("memory region '" + sec->memoryRegionName + "' not declared");
917349cc55cSDimitry Andric     return {nullptr, nullptr};
9180b57cec5SDimitry Andric   }
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric   // If at least one memory region is defined, all sections must
9210b57cec5SDimitry Andric   // belong to some memory region. Otherwise, we don't need to do
9220b57cec5SDimitry Andric   // anything for memory regions.
9230b57cec5SDimitry Andric   if (memoryRegions.empty())
924349cc55cSDimitry Andric     return {nullptr, nullptr};
925349cc55cSDimitry Andric 
926349cc55cSDimitry Andric   // An orphan section should continue the previous memory region.
927349cc55cSDimitry Andric   if (sec->sectionIndex == UINT32_MAX && hint)
928349cc55cSDimitry Andric     return {hint, hint};
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric   // See if a region can be found by matching section flags.
9310b57cec5SDimitry Andric   for (auto &pair : memoryRegions) {
9320b57cec5SDimitry Andric     MemoryRegion *m = pair.second;
9334824e7fdSDimitry Andric     if (m->compatibleWith(sec->flags))
934349cc55cSDimitry Andric       return {m, nullptr};
9350b57cec5SDimitry Andric   }
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   // Otherwise, no suitable region was found.
9380b57cec5SDimitry Andric   error("no memory region specified for section '" + sec->name + "'");
939349cc55cSDimitry Andric   return {nullptr, nullptr};
9400b57cec5SDimitry Andric }
9410b57cec5SDimitry Andric 
9420b57cec5SDimitry Andric static OutputSection *findFirstSection(PhdrEntry *load) {
9430b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
9440b57cec5SDimitry Andric     if (sec->ptLoad == load)
9450b57cec5SDimitry Andric       return sec;
9460b57cec5SDimitry Andric   return nullptr;
9470b57cec5SDimitry Andric }
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric // This function assigns offsets to input sections and an output section
9500b57cec5SDimitry Andric // for a single sections command (e.g. ".text { *(.text); }").
9510b57cec5SDimitry Andric void LinkerScript::assignOffsets(OutputSection *sec) {
9526e75b2fbSDimitry Andric   const bool isTbss = (sec->flags & SHF_TLS) && sec->type == SHT_NOBITS;
9535ffd83dbSDimitry Andric   const bool sameMemRegion = ctx->memRegion == sec->memRegion;
9545ffd83dbSDimitry Andric   const bool prevLMARegionIsDefault = ctx->lmaRegion == nullptr;
955e8d8bef9SDimitry Andric   const uint64_t savedDot = dot;
9560b57cec5SDimitry Andric   ctx->memRegion = sec->memRegion;
9570b57cec5SDimitry Andric   ctx->lmaRegion = sec->lmaRegion;
958e8d8bef9SDimitry Andric 
9596e75b2fbSDimitry Andric   if (!(sec->flags & SHF_ALLOC)) {
9606e75b2fbSDimitry Andric     // Non-SHF_ALLOC sections have zero addresses.
9616e75b2fbSDimitry Andric     dot = 0;
9626e75b2fbSDimitry Andric   } else if (isTbss) {
9636e75b2fbSDimitry Andric     // Allow consecutive SHF_TLS SHT_NOBITS output sections. The address range
9646e75b2fbSDimitry Andric     // starts from the end address of the previous tbss section.
9656e75b2fbSDimitry Andric     if (ctx->tbssAddr == 0)
9666e75b2fbSDimitry Andric       ctx->tbssAddr = dot;
9676e75b2fbSDimitry Andric     else
9686e75b2fbSDimitry Andric       dot = ctx->tbssAddr;
9696e75b2fbSDimitry Andric   } else {
9700b57cec5SDimitry Andric     if (ctx->memRegion)
9710b57cec5SDimitry Andric       dot = ctx->memRegion->curPos;
972e8d8bef9SDimitry Andric     if (sec->addrExpr)
9730b57cec5SDimitry Andric       setDot(sec->addrExpr, sec->location, false);
9740b57cec5SDimitry Andric 
97585868e8aSDimitry Andric     // If the address of the section has been moved forward by an explicit
97685868e8aSDimitry Andric     // expression so that it now starts past the current curPos of the enclosing
97785868e8aSDimitry Andric     // region, we need to expand the current region to account for the space
97885868e8aSDimitry Andric     // between the previous section, if any, and the start of this section.
97985868e8aSDimitry Andric     if (ctx->memRegion && ctx->memRegion->curPos < dot)
98085868e8aSDimitry Andric       expandMemoryRegion(ctx->memRegion, dot - ctx->memRegion->curPos,
9814824e7fdSDimitry Andric                          sec->name);
982e8d8bef9SDimitry Andric   }
98385868e8aSDimitry Andric 
9844824e7fdSDimitry Andric   ctx->outSec = sec;
9854824e7fdSDimitry Andric   if (sec->addrExpr && script->hasSectionsCommand) {
9864824e7fdSDimitry Andric     // The alignment is ignored.
9874824e7fdSDimitry Andric     sec->addr = dot;
9884824e7fdSDimitry Andric   } else {
9894824e7fdSDimitry Andric     // sec->alignment is the max of ALIGN and the maximum of input
9904824e7fdSDimitry Andric     // section alignments.
9914824e7fdSDimitry Andric     const uint64_t pos = dot;
9924824e7fdSDimitry Andric     dot = alignTo(dot, sec->alignment);
9934824e7fdSDimitry Andric     sec->addr = dot;
9944824e7fdSDimitry Andric     expandMemoryRegions(dot - pos);
9954824e7fdSDimitry Andric   }
9960b57cec5SDimitry Andric 
9975ffd83dbSDimitry Andric   // ctx->lmaOffset is LMA minus VMA. If LMA is explicitly specified via AT() or
9985ffd83dbSDimitry Andric   // AT>, recompute ctx->lmaOffset; otherwise, if both previous/current LMA
9995ffd83dbSDimitry Andric   // region is the default, and the two sections are in the same memory region,
10005ffd83dbSDimitry Andric   // reuse previous lmaOffset; otherwise, reset lmaOffset to 0. This emulates
10015ffd83dbSDimitry Andric   // heuristics described in
10025ffd83dbSDimitry Andric   // https://sourceware.org/binutils/docs/ld/Output-Section-LMA.html
1003349cc55cSDimitry Andric   if (sec->lmaExpr) {
10040b57cec5SDimitry Andric     ctx->lmaOffset = sec->lmaExpr().getValue() - dot;
1005349cc55cSDimitry Andric   } else if (MemoryRegion *mr = sec->lmaRegion) {
1006349cc55cSDimitry Andric     uint64_t lmaStart = alignTo(mr->curPos, sec->alignment);
1007349cc55cSDimitry Andric     if (mr->curPos < lmaStart)
10084824e7fdSDimitry Andric       expandMemoryRegion(mr, lmaStart - mr->curPos, sec->name);
1009349cc55cSDimitry Andric     ctx->lmaOffset = lmaStart - dot;
1010349cc55cSDimitry Andric   } else if (!sameMemRegion || !prevLMARegionIsDefault) {
10115ffd83dbSDimitry Andric     ctx->lmaOffset = 0;
1012349cc55cSDimitry Andric   }
10130b57cec5SDimitry Andric 
10145ffd83dbSDimitry Andric   // Propagate ctx->lmaOffset to the first "non-header" section.
10154824e7fdSDimitry Andric   if (PhdrEntry *l = sec->ptLoad)
10160b57cec5SDimitry Andric     if (sec == findFirstSection(l))
10170b57cec5SDimitry Andric       l->lmaOffset = ctx->lmaOffset;
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric   // We can call this method multiple times during the creation of
10200b57cec5SDimitry Andric   // thunks and want to start over calculation each time.
10210b57cec5SDimitry Andric   sec->size = 0;
10220b57cec5SDimitry Andric 
10230b57cec5SDimitry Andric   // We visited SectionsCommands from processSectionCommands to
10240b57cec5SDimitry Andric   // layout sections. Now, we visit SectionsCommands again to fix
10250b57cec5SDimitry Andric   // section offsets.
10264824e7fdSDimitry Andric   for (SectionCommand *cmd : sec->commands) {
10270b57cec5SDimitry Andric     // This handles the assignments to symbol or to the dot.
10284824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
10294824e7fdSDimitry Andric       assign->addr = dot;
10304824e7fdSDimitry Andric       assignSymbol(assign, true);
10314824e7fdSDimitry Andric       assign->size = dot - assign->addr;
10320b57cec5SDimitry Andric       continue;
10330b57cec5SDimitry Andric     }
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric     // Handle BYTE(), SHORT(), LONG(), or QUAD().
10364824e7fdSDimitry Andric     if (auto *data = dyn_cast<ByteCommand>(cmd)) {
10374824e7fdSDimitry Andric       data->offset = dot - sec->addr;
10384824e7fdSDimitry Andric       dot += data->size;
10394824e7fdSDimitry Andric       expandOutputSection(data->size);
10400b57cec5SDimitry Andric       continue;
10410b57cec5SDimitry Andric     }
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric     // Handle a single input section description command.
10440b57cec5SDimitry Andric     // It calculates and assigns the offsets for each section and also
10450b57cec5SDimitry Andric     // updates the output section size.
10464824e7fdSDimitry Andric     for (InputSection *isec : cast<InputSectionDescription>(cmd)->sections) {
10474824e7fdSDimitry Andric       assert(isec->getParent() == sec);
10484824e7fdSDimitry Andric       const uint64_t pos = dot;
10494824e7fdSDimitry Andric       dot = alignTo(dot, isec->alignment);
10504824e7fdSDimitry Andric       isec->outSecOff = dot - sec->addr;
10514824e7fdSDimitry Andric       dot += isec->getSize();
10524824e7fdSDimitry Andric 
10534824e7fdSDimitry Andric       // Update output section size after adding each section. This is so that
10544824e7fdSDimitry Andric       // SIZEOF works correctly in the case below:
10554824e7fdSDimitry Andric       // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
10564824e7fdSDimitry Andric       expandOutputSection(dot - pos);
10574824e7fdSDimitry Andric     }
10580b57cec5SDimitry Andric   }
1059e8d8bef9SDimitry Andric 
1060e8d8bef9SDimitry Andric   // Non-SHF_ALLOC sections do not affect the addresses of other OutputSections
1061e8d8bef9SDimitry Andric   // as they are not part of the process image.
10626e75b2fbSDimitry Andric   if (!(sec->flags & SHF_ALLOC)) {
1063e8d8bef9SDimitry Andric     dot = savedDot;
10646e75b2fbSDimitry Andric   } else if (isTbss) {
10656e75b2fbSDimitry Andric     // NOBITS TLS sections are similar. Additionally save the end address.
10666e75b2fbSDimitry Andric     ctx->tbssAddr = dot;
10676e75b2fbSDimitry Andric     dot = savedDot;
10686e75b2fbSDimitry Andric   }
10690b57cec5SDimitry Andric }
10700b57cec5SDimitry Andric 
1071349cc55cSDimitry Andric static bool isDiscardable(const OutputSection &sec) {
10720b57cec5SDimitry Andric   if (sec.name == "/DISCARD/")
10730b57cec5SDimitry Andric     return true;
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric   // We do not want to remove OutputSections with expressions that reference
10760b57cec5SDimitry Andric   // symbols even if the OutputSection is empty. We want to ensure that the
10770b57cec5SDimitry Andric   // expressions can be evaluated and report an error if they cannot.
10780b57cec5SDimitry Andric   if (sec.expressionsUseSymbols)
10790b57cec5SDimitry Andric     return false;
10800b57cec5SDimitry Andric 
10810b57cec5SDimitry Andric   // OutputSections may be referenced by name in ADDR and LOADADDR expressions,
10820b57cec5SDimitry Andric   // as an empty Section can has a valid VMA and LMA we keep the OutputSection
10830b57cec5SDimitry Andric   // to maintain the integrity of the other Expression.
10840b57cec5SDimitry Andric   if (sec.usedInExpression)
10850b57cec5SDimitry Andric     return false;
10860b57cec5SDimitry Andric 
10874824e7fdSDimitry Andric   for (SectionCommand *cmd : sec.commands) {
10884824e7fdSDimitry Andric     if (auto assign = dyn_cast<SymbolAssignment>(cmd))
10890b57cec5SDimitry Andric       // Don't create empty output sections just for unreferenced PROVIDE
10900b57cec5SDimitry Andric       // symbols.
10914824e7fdSDimitry Andric       if (assign->name != "." && !assign->sym)
10920b57cec5SDimitry Andric         continue;
10930b57cec5SDimitry Andric 
10944824e7fdSDimitry Andric     if (!isa<InputSectionDescription>(*cmd))
10950b57cec5SDimitry Andric       return false;
10960b57cec5SDimitry Andric   }
10970b57cec5SDimitry Andric   return true;
10980b57cec5SDimitry Andric }
10990b57cec5SDimitry Andric 
1100349cc55cSDimitry Andric bool LinkerScript::isDiscarded(const OutputSection *sec) const {
1101349cc55cSDimitry Andric   return hasSectionsCommand && (getFirstInputSection(sec) == nullptr) &&
1102349cc55cSDimitry Andric          isDiscardable(*sec);
1103349cc55cSDimitry Andric }
1104349cc55cSDimitry Andric 
1105e8d8bef9SDimitry Andric static void maybePropagatePhdrs(OutputSection &sec,
1106*04eeddc0SDimitry Andric                                 SmallVector<StringRef, 0> &phdrs) {
1107e8d8bef9SDimitry Andric   if (sec.phdrs.empty()) {
1108e8d8bef9SDimitry Andric     // To match the bfd linker script behaviour, only propagate program
1109e8d8bef9SDimitry Andric     // headers to sections that are allocated.
1110e8d8bef9SDimitry Andric     if (sec.flags & SHF_ALLOC)
1111e8d8bef9SDimitry Andric       sec.phdrs = phdrs;
1112e8d8bef9SDimitry Andric   } else {
1113e8d8bef9SDimitry Andric     phdrs = sec.phdrs;
1114e8d8bef9SDimitry Andric   }
1115e8d8bef9SDimitry Andric }
1116e8d8bef9SDimitry Andric 
11170b57cec5SDimitry Andric void LinkerScript::adjustSectionsBeforeSorting() {
11180b57cec5SDimitry Andric   // If the output section contains only symbol assignments, create a
11190b57cec5SDimitry Andric   // corresponding output section. The issue is what to do with linker script
11200b57cec5SDimitry Andric   // like ".foo : { symbol = 42; }". One option would be to convert it to
11210b57cec5SDimitry Andric   // "symbol = 42;". That is, move the symbol out of the empty section
11220b57cec5SDimitry Andric   // description. That seems to be what bfd does for this simple case. The
11230b57cec5SDimitry Andric   // problem is that this is not completely general. bfd will give up and
11240b57cec5SDimitry Andric   // create a dummy section too if there is a ". = . + 1" inside the section
11250b57cec5SDimitry Andric   // for example.
11260b57cec5SDimitry Andric   // Given that we want to create the section, we have to worry what impact
11270b57cec5SDimitry Andric   // it will have on the link. For example, if we just create a section with
11280b57cec5SDimitry Andric   // 0 for flags, it would change which PT_LOADs are created.
11290b57cec5SDimitry Andric   // We could remember that particular section is dummy and ignore it in
11300b57cec5SDimitry Andric   // other parts of the linker, but unfortunately there are quite a few places
11310b57cec5SDimitry Andric   // that would need to change:
11320b57cec5SDimitry Andric   //   * The program header creation.
11330b57cec5SDimitry Andric   //   * The orphan section placement.
11340b57cec5SDimitry Andric   //   * The address assignment.
11350b57cec5SDimitry Andric   // The other option is to pick flags that minimize the impact the section
11360b57cec5SDimitry Andric   // will have on the rest of the linker. That is why we copy the flags from
11370b57cec5SDimitry Andric   // the previous sections. Only a few flags are needed to keep the impact low.
11380b57cec5SDimitry Andric   uint64_t flags = SHF_ALLOC;
11390b57cec5SDimitry Andric 
1140*04eeddc0SDimitry Andric   SmallVector<StringRef, 0> defPhdrs;
11414824e7fdSDimitry Andric   for (SectionCommand *&cmd : sectionCommands) {
11420b57cec5SDimitry Andric     auto *sec = dyn_cast<OutputSection>(cmd);
11430b57cec5SDimitry Andric     if (!sec)
11440b57cec5SDimitry Andric       continue;
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric     // Handle align (e.g. ".foo : ALIGN(16) { ... }").
11470b57cec5SDimitry Andric     if (sec->alignExpr)
11480b57cec5SDimitry Andric       sec->alignment =
11490b57cec5SDimitry Andric           std::max<uint32_t>(sec->alignment, sec->alignExpr().getValue());
11500b57cec5SDimitry Andric 
11510b57cec5SDimitry Andric     // The input section might have been removed (if it was an empty synthetic
11520b57cec5SDimitry Andric     // section), but we at least know the flags.
11530b57cec5SDimitry Andric     if (sec->hasInputSections)
11540b57cec5SDimitry Andric       flags = sec->flags;
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric     // We do not want to keep any special flags for output section
11570b57cec5SDimitry Andric     // in case it is empty.
11585ffd83dbSDimitry Andric     bool isEmpty = (getFirstInputSection(sec) == nullptr);
11590b57cec5SDimitry Andric     if (isEmpty)
11600b57cec5SDimitry Andric       sec->flags = flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) |
11610b57cec5SDimitry Andric                             SHF_WRITE | SHF_EXECINSTR);
11620b57cec5SDimitry Andric 
1163e8d8bef9SDimitry Andric     // The code below may remove empty output sections. We should save the
1164e8d8bef9SDimitry Andric     // specified program headers (if exist) and propagate them to subsequent
1165e8d8bef9SDimitry Andric     // sections which do not specify program headers.
1166e8d8bef9SDimitry Andric     // An example of such a linker script is:
1167e8d8bef9SDimitry Andric     // SECTIONS { .empty : { *(.empty) } :rw
1168e8d8bef9SDimitry Andric     //            .foo : { *(.foo) } }
1169e8d8bef9SDimitry Andric     // Note: at this point the order of output sections has not been finalized,
1170e8d8bef9SDimitry Andric     // because orphans have not been inserted into their expected positions. We
1171e8d8bef9SDimitry Andric     // will handle them in adjustSectionsAfterSorting().
1172e8d8bef9SDimitry Andric     if (sec->sectionIndex != UINT32_MAX)
1173e8d8bef9SDimitry Andric       maybePropagatePhdrs(*sec, defPhdrs);
1174e8d8bef9SDimitry Andric 
11750b57cec5SDimitry Andric     if (isEmpty && isDiscardable(*sec)) {
11760b57cec5SDimitry Andric       sec->markDead();
11770b57cec5SDimitry Andric       cmd = nullptr;
11780b57cec5SDimitry Andric     }
11790b57cec5SDimitry Andric   }
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric   // It is common practice to use very generic linker scripts. So for any
11820b57cec5SDimitry Andric   // given run some of the output sections in the script will be empty.
11830b57cec5SDimitry Andric   // We could create corresponding empty output sections, but that would
11840b57cec5SDimitry Andric   // clutter the output.
11850b57cec5SDimitry Andric   // We instead remove trivially empty sections. The bfd linker seems even
11860b57cec5SDimitry Andric   // more aggressive at removing them.
11874824e7fdSDimitry Andric   llvm::erase_if(sectionCommands, [&](SectionCommand *cmd) { return !cmd; });
11880b57cec5SDimitry Andric }
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric void LinkerScript::adjustSectionsAfterSorting() {
11910b57cec5SDimitry Andric   // Try and find an appropriate memory region to assign offsets in.
1192349cc55cSDimitry Andric   MemoryRegion *hint = nullptr;
11934824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands) {
11944824e7fdSDimitry Andric     if (auto *sec = dyn_cast<OutputSection>(cmd)) {
11950b57cec5SDimitry Andric       if (!sec->lmaRegionName.empty()) {
11960b57cec5SDimitry Andric         if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName))
11970b57cec5SDimitry Andric           sec->lmaRegion = m;
11980b57cec5SDimitry Andric         else
11990b57cec5SDimitry Andric           error("memory region '" + sec->lmaRegionName + "' not declared");
12000b57cec5SDimitry Andric       }
1201349cc55cSDimitry Andric       std::tie(sec->memRegion, hint) = findMemoryRegion(sec, hint);
12020b57cec5SDimitry Andric     }
12030b57cec5SDimitry Andric   }
12040b57cec5SDimitry Andric 
12050b57cec5SDimitry Andric   // If output section command doesn't specify any segments,
12060b57cec5SDimitry Andric   // and we haven't previously assigned any section to segment,
12070b57cec5SDimitry Andric   // then we simply assign section to the very first load segment.
12080b57cec5SDimitry Andric   // Below is an example of such linker script:
12090b57cec5SDimitry Andric   // PHDRS { seg PT_LOAD; }
12100b57cec5SDimitry Andric   // SECTIONS { .aaa : { *(.aaa) } }
1211*04eeddc0SDimitry Andric   SmallVector<StringRef, 0> defPhdrs;
12120b57cec5SDimitry Andric   auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) {
12130b57cec5SDimitry Andric     return cmd.type == PT_LOAD;
12140b57cec5SDimitry Andric   });
12150b57cec5SDimitry Andric   if (firstPtLoad != phdrsCommands.end())
12160b57cec5SDimitry Andric     defPhdrs.push_back(firstPtLoad->name);
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric   // Walk the commands and propagate the program headers to commands that don't
12190b57cec5SDimitry Andric   // explicitly specify them.
12204824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands)
12214824e7fdSDimitry Andric     if (auto *sec = dyn_cast<OutputSection>(cmd))
1222e8d8bef9SDimitry Andric       maybePropagatePhdrs(*sec, defPhdrs);
12230b57cec5SDimitry Andric }
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric static uint64_t computeBase(uint64_t min, bool allocateHeaders) {
12260b57cec5SDimitry Andric   // If there is no SECTIONS or if the linkerscript is explicit about program
12270b57cec5SDimitry Andric   // headers, do our best to allocate them.
12280b57cec5SDimitry Andric   if (!script->hasSectionsCommand || allocateHeaders)
12290b57cec5SDimitry Andric     return 0;
12300b57cec5SDimitry Andric   // Otherwise only allocate program headers if that would not add a page.
12310b57cec5SDimitry Andric   return alignDown(min, config->maxPageSize);
12320b57cec5SDimitry Andric }
12330b57cec5SDimitry Andric 
123469660011SDimitry Andric // When the SECTIONS command is used, try to find an address for the file and
123569660011SDimitry Andric // program headers output sections, which can be added to the first PT_LOAD
123669660011SDimitry Andric // segment when program headers are created.
12370b57cec5SDimitry Andric //
123869660011SDimitry Andric // We check if the headers fit below the first allocated section. If there isn't
123969660011SDimitry Andric // enough space for these sections, we'll remove them from the PT_LOAD segment,
124069660011SDimitry Andric // and we'll also remove the PT_PHDR segment.
1241*04eeddc0SDimitry Andric void LinkerScript::allocateHeaders(SmallVector<PhdrEntry *, 0> &phdrs) {
12420b57cec5SDimitry Andric   uint64_t min = std::numeric_limits<uint64_t>::max();
12430b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
12440b57cec5SDimitry Andric     if (sec->flags & SHF_ALLOC)
12450b57cec5SDimitry Andric       min = std::min<uint64_t>(min, sec->addr);
12460b57cec5SDimitry Andric 
12470b57cec5SDimitry Andric   auto it = llvm::find_if(
12480b57cec5SDimitry Andric       phdrs, [](const PhdrEntry *e) { return e->p_type == PT_LOAD; });
12490b57cec5SDimitry Andric   if (it == phdrs.end())
12500b57cec5SDimitry Andric     return;
12510b57cec5SDimitry Andric   PhdrEntry *firstPTLoad = *it;
12520b57cec5SDimitry Andric 
12530b57cec5SDimitry Andric   bool hasExplicitHeaders =
12540b57cec5SDimitry Andric       llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) {
12550b57cec5SDimitry Andric         return cmd.hasPhdrs || cmd.hasFilehdr;
12560b57cec5SDimitry Andric       });
12570b57cec5SDimitry Andric   bool paged = !config->omagic && !config->nmagic;
12580b57cec5SDimitry Andric   uint64_t headerSize = getHeaderSize();
12590b57cec5SDimitry Andric   if ((paged || hasExplicitHeaders) &&
12600b57cec5SDimitry Andric       headerSize <= min - computeBase(min, hasExplicitHeaders)) {
12610b57cec5SDimitry Andric     min = alignDown(min - headerSize, config->maxPageSize);
12620b57cec5SDimitry Andric     Out::elfHeader->addr = min;
12630b57cec5SDimitry Andric     Out::programHeaders->addr = min + Out::elfHeader->size;
12640b57cec5SDimitry Andric     return;
12650b57cec5SDimitry Andric   }
12660b57cec5SDimitry Andric 
12670b57cec5SDimitry Andric   // Error if we were explicitly asked to allocate headers.
12680b57cec5SDimitry Andric   if (hasExplicitHeaders)
12690b57cec5SDimitry Andric     error("could not allocate headers");
12700b57cec5SDimitry Andric 
12710b57cec5SDimitry Andric   Out::elfHeader->ptLoad = nullptr;
12720b57cec5SDimitry Andric   Out::programHeaders->ptLoad = nullptr;
12730b57cec5SDimitry Andric   firstPTLoad->firstSec = findFirstSection(firstPTLoad);
12740b57cec5SDimitry Andric 
12750b57cec5SDimitry Andric   llvm::erase_if(phdrs,
12760b57cec5SDimitry Andric                  [](const PhdrEntry *e) { return e->p_type == PT_PHDR; });
12770b57cec5SDimitry Andric }
12780b57cec5SDimitry Andric 
12790b57cec5SDimitry Andric LinkerScript::AddressState::AddressState() {
12800b57cec5SDimitry Andric   for (auto &mri : script->memoryRegions) {
12810b57cec5SDimitry Andric     MemoryRegion *mr = mri.second;
12825ffd83dbSDimitry Andric     mr->curPos = (mr->origin)().getValue();
12830b57cec5SDimitry Andric   }
12840b57cec5SDimitry Andric }
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric // Here we assign addresses as instructed by linker script SECTIONS
12870b57cec5SDimitry Andric // sub-commands. Doing that allows us to use final VA values, so here
12880b57cec5SDimitry Andric // we also handle rest commands like symbol assignments and ASSERTs.
128985868e8aSDimitry Andric // Returns a symbol that has changed its section or value, or nullptr if no
129085868e8aSDimitry Andric // symbol has changed.
129185868e8aSDimitry Andric const Defined *LinkerScript::assignAddresses() {
129269660011SDimitry Andric   if (script->hasSectionsCommand) {
129369660011SDimitry Andric     // With a linker script, assignment of addresses to headers is covered by
129469660011SDimitry Andric     // allocateHeaders().
129569660011SDimitry Andric     dot = config->imageBase.getValueOr(0);
129669660011SDimitry Andric   } else {
129769660011SDimitry Andric     // Assign addresses to headers right now.
129869660011SDimitry Andric     dot = target->getImageBase();
129969660011SDimitry Andric     Out::elfHeader->addr = dot;
130069660011SDimitry Andric     Out::programHeaders->addr = dot + Out::elfHeader->size;
130169660011SDimitry Andric     dot += getHeaderSize();
130269660011SDimitry Andric   }
13030b57cec5SDimitry Andric 
13044824e7fdSDimitry Andric   AddressState state;
13054824e7fdSDimitry Andric   ctx = &state;
13060b57cec5SDimitry Andric   errorOnMissingSection = true;
13074824e7fdSDimitry Andric   ctx->outSec = aether;
13080b57cec5SDimitry Andric 
130985868e8aSDimitry Andric   SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);
13104824e7fdSDimitry Andric   for (SectionCommand *cmd : sectionCommands) {
13114824e7fdSDimitry Andric     if (auto *assign = dyn_cast<SymbolAssignment>(cmd)) {
13124824e7fdSDimitry Andric       assign->addr = dot;
13134824e7fdSDimitry Andric       assignSymbol(assign, false);
13144824e7fdSDimitry Andric       assign->size = dot - assign->addr;
13150b57cec5SDimitry Andric       continue;
13160b57cec5SDimitry Andric     }
13174824e7fdSDimitry Andric     assignOffsets(cast<OutputSection>(cmd));
13180b57cec5SDimitry Andric   }
131985868e8aSDimitry Andric 
13200b57cec5SDimitry Andric   ctx = nullptr;
132185868e8aSDimitry Andric   return getChangedSymbolAssignment(oldValues);
13220b57cec5SDimitry Andric }
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric // Creates program headers as instructed by PHDRS linker script command.
1325*04eeddc0SDimitry Andric SmallVector<PhdrEntry *, 0> LinkerScript::createPhdrs() {
1326*04eeddc0SDimitry Andric   SmallVector<PhdrEntry *, 0> ret;
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric   // Process PHDRS and FILEHDR keywords because they are not
13290b57cec5SDimitry Andric   // real output sections and cannot be added in the following loop.
13300b57cec5SDimitry Andric   for (const PhdrsCommand &cmd : phdrsCommands) {
13310eae32dcSDimitry Andric     PhdrEntry *phdr = make<PhdrEntry>(cmd.type, cmd.flags.getValueOr(PF_R));
13320b57cec5SDimitry Andric 
13330b57cec5SDimitry Andric     if (cmd.hasFilehdr)
13340b57cec5SDimitry Andric       phdr->add(Out::elfHeader);
13350b57cec5SDimitry Andric     if (cmd.hasPhdrs)
13360b57cec5SDimitry Andric       phdr->add(Out::programHeaders);
13370b57cec5SDimitry Andric 
13380b57cec5SDimitry Andric     if (cmd.lmaExpr) {
13390b57cec5SDimitry Andric       phdr->p_paddr = cmd.lmaExpr().getValue();
13400b57cec5SDimitry Andric       phdr->hasLMA = true;
13410b57cec5SDimitry Andric     }
13420b57cec5SDimitry Andric     ret.push_back(phdr);
13430b57cec5SDimitry Andric   }
13440b57cec5SDimitry Andric 
13450b57cec5SDimitry Andric   // Add output sections to program headers.
13460b57cec5SDimitry Andric   for (OutputSection *sec : outputSections) {
13470b57cec5SDimitry Andric     // Assign headers specified by linker script
13480b57cec5SDimitry Andric     for (size_t id : getPhdrIndices(sec)) {
13490b57cec5SDimitry Andric       ret[id]->add(sec);
13500b57cec5SDimitry Andric       if (!phdrsCommands[id].flags.hasValue())
13510b57cec5SDimitry Andric         ret[id]->p_flags |= sec->getPhdrFlags();
13520b57cec5SDimitry Andric     }
13530b57cec5SDimitry Andric   }
13540b57cec5SDimitry Andric   return ret;
13550b57cec5SDimitry Andric }
13560b57cec5SDimitry Andric 
13570b57cec5SDimitry Andric // Returns true if we should emit an .interp section.
13580b57cec5SDimitry Andric //
13590b57cec5SDimitry Andric // We usually do. But if PHDRS commands are given, and
13600b57cec5SDimitry Andric // no PT_INTERP is there, there's no place to emit an
13610b57cec5SDimitry Andric // .interp, so we don't do that in that case.
13620b57cec5SDimitry Andric bool LinkerScript::needsInterpSection() {
13630b57cec5SDimitry Andric   if (phdrsCommands.empty())
13640b57cec5SDimitry Andric     return true;
13650b57cec5SDimitry Andric   for (PhdrsCommand &cmd : phdrsCommands)
13660b57cec5SDimitry Andric     if (cmd.type == PT_INTERP)
13670b57cec5SDimitry Andric       return true;
13680b57cec5SDimitry Andric   return false;
13690b57cec5SDimitry Andric }
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {
13720b57cec5SDimitry Andric   if (name == ".") {
13730b57cec5SDimitry Andric     if (ctx)
13740b57cec5SDimitry Andric       return {ctx->outSec, false, dot - ctx->outSec->addr, loc};
13750b57cec5SDimitry Andric     error(loc + ": unable to get location counter value");
13760b57cec5SDimitry Andric     return 0;
13770b57cec5SDimitry Andric   }
13780b57cec5SDimitry Andric 
13790b57cec5SDimitry Andric   if (Symbol *sym = symtab->find(name)) {
138016d6b3b3SDimitry Andric     if (auto *ds = dyn_cast<Defined>(sym)) {
138116d6b3b3SDimitry Andric       ExprValue v{ds->section, false, ds->value, loc};
138216d6b3b3SDimitry Andric       // Retain the original st_type, so that the alias will get the same
138316d6b3b3SDimitry Andric       // behavior in relocation processing. Any operation will reset st_type to
138416d6b3b3SDimitry Andric       // STT_NOTYPE.
138516d6b3b3SDimitry Andric       v.type = ds->type;
138616d6b3b3SDimitry Andric       return v;
138716d6b3b3SDimitry Andric     }
13880b57cec5SDimitry Andric     if (isa<SharedSymbol>(sym))
13890b57cec5SDimitry Andric       if (!errorOnMissingSection)
13900b57cec5SDimitry Andric         return {nullptr, false, 0, loc};
13910b57cec5SDimitry Andric   }
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   error(loc + ": symbol not found: " + name);
13940b57cec5SDimitry Andric   return 0;
13950b57cec5SDimitry Andric }
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric // Returns the index of the segment named Name.
13980b57cec5SDimitry Andric static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,
13990b57cec5SDimitry Andric                                      StringRef name) {
14000b57cec5SDimitry Andric   for (size_t i = 0; i < vec.size(); ++i)
14010b57cec5SDimitry Andric     if (vec[i].name == name)
14020b57cec5SDimitry Andric       return i;
14030b57cec5SDimitry Andric   return None;
14040b57cec5SDimitry Andric }
14050b57cec5SDimitry Andric 
14060b57cec5SDimitry Andric // Returns indices of ELF headers containing specific section. Each index is a
14070b57cec5SDimitry Andric // zero based number of ELF header listed within PHDRS {} script block.
1408*04eeddc0SDimitry Andric SmallVector<size_t, 0> LinkerScript::getPhdrIndices(OutputSection *cmd) {
1409*04eeddc0SDimitry Andric   SmallVector<size_t, 0> ret;
14100b57cec5SDimitry Andric 
14110b57cec5SDimitry Andric   for (StringRef s : cmd->phdrs) {
14120b57cec5SDimitry Andric     if (Optional<size_t> idx = getPhdrIndex(phdrsCommands, s))
14130b57cec5SDimitry Andric       ret.push_back(*idx);
14140b57cec5SDimitry Andric     else if (s != "NONE")
14155ffd83dbSDimitry Andric       error(cmd->location + ": program header '" + s +
14160b57cec5SDimitry Andric             "' is not listed in PHDRS");
14170b57cec5SDimitry Andric   }
14180b57cec5SDimitry Andric   return ret;
14190b57cec5SDimitry Andric }
1420