xref: /freebsd/contrib/llvm-project/lld/ELF/LinkerScript.cpp (revision 480093f4440d54b30b3025afeac24b48f2ba7a2e)
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"
220b57cec5SDimitry Andric #include "lld/Common/Memory.h"
230b57cec5SDimitry Andric #include "lld/Common/Strings.h"
240b57cec5SDimitry Andric #include "lld/Common/Threads.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"
310b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
320b57cec5SDimitry Andric #include "llvm/Support/Path.h"
330b57cec5SDimitry Andric #include <algorithm>
340b57cec5SDimitry Andric #include <cassert>
350b57cec5SDimitry Andric #include <cstddef>
360b57cec5SDimitry Andric #include <cstdint>
370b57cec5SDimitry Andric #include <iterator>
380b57cec5SDimitry Andric #include <limits>
390b57cec5SDimitry Andric #include <string>
400b57cec5SDimitry Andric #include <vector>
410b57cec5SDimitry Andric 
420b57cec5SDimitry Andric using namespace llvm;
430b57cec5SDimitry Andric using namespace llvm::ELF;
440b57cec5SDimitry Andric using namespace llvm::object;
450b57cec5SDimitry Andric using namespace llvm::support::endian;
460b57cec5SDimitry Andric 
4785868e8aSDimitry Andric namespace lld {
4885868e8aSDimitry Andric namespace elf {
4985868e8aSDimitry Andric LinkerScript *script;
500b57cec5SDimitry Andric 
5185868e8aSDimitry Andric static uint64_t getOutputSectionVA(SectionBase *sec) {
5285868e8aSDimitry Andric   OutputSection *os = sec->getOutputSection();
5385868e8aSDimitry Andric   assert(os && "input section has no output section assigned");
5485868e8aSDimitry Andric   return os ? os->addr : 0;
550b57cec5SDimitry Andric }
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric uint64_t ExprValue::getValue() const {
580b57cec5SDimitry Andric   if (sec)
5985868e8aSDimitry Andric     return alignTo(sec->getOffset(val) + getOutputSectionVA(sec),
600b57cec5SDimitry Andric                    alignment);
610b57cec5SDimitry Andric   return alignTo(val, alignment);
620b57cec5SDimitry Andric }
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric uint64_t ExprValue::getSecAddr() const {
650b57cec5SDimitry Andric   if (sec)
6685868e8aSDimitry Andric     return sec->getOffset(0) + getOutputSectionVA(sec);
670b57cec5SDimitry Andric   return 0;
680b57cec5SDimitry Andric }
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric uint64_t ExprValue::getSectionOffset() const {
710b57cec5SDimitry Andric   // If the alignment is trivial, we don't have to compute the full
720b57cec5SDimitry Andric   // value to know the offset. This allows this function to succeed in
730b57cec5SDimitry Andric   // cases where the output section is not yet known.
7485868e8aSDimitry Andric   if (alignment == 1 && !sec)
750b57cec5SDimitry Andric     return val;
760b57cec5SDimitry Andric   return getValue() - getSecAddr();
770b57cec5SDimitry Andric }
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric OutputSection *LinkerScript::createOutputSection(StringRef name,
800b57cec5SDimitry Andric                                                  StringRef location) {
810b57cec5SDimitry Andric   OutputSection *&secRef = nameToOutputSection[name];
820b57cec5SDimitry Andric   OutputSection *sec;
830b57cec5SDimitry Andric   if (secRef && secRef->location.empty()) {
840b57cec5SDimitry Andric     // There was a forward reference.
850b57cec5SDimitry Andric     sec = secRef;
860b57cec5SDimitry Andric   } else {
870b57cec5SDimitry Andric     sec = make<OutputSection>(name, SHT_PROGBITS, 0);
880b57cec5SDimitry Andric     if (!secRef)
890b57cec5SDimitry Andric       secRef = sec;
900b57cec5SDimitry Andric   }
910b57cec5SDimitry Andric   sec->location = location;
920b57cec5SDimitry Andric   return sec;
930b57cec5SDimitry Andric }
940b57cec5SDimitry Andric 
950b57cec5SDimitry Andric OutputSection *LinkerScript::getOrCreateOutputSection(StringRef name) {
960b57cec5SDimitry Andric   OutputSection *&cmdRef = nameToOutputSection[name];
970b57cec5SDimitry Andric   if (!cmdRef)
980b57cec5SDimitry Andric     cmdRef = make<OutputSection>(name, SHT_PROGBITS, 0);
990b57cec5SDimitry Andric   return cmdRef;
1000b57cec5SDimitry Andric }
1010b57cec5SDimitry Andric 
1020b57cec5SDimitry Andric // Expands the memory region by the specified size.
1030b57cec5SDimitry Andric static void expandMemoryRegion(MemoryRegion *memRegion, uint64_t size,
1040b57cec5SDimitry Andric                                StringRef regionName, StringRef secName) {
1050b57cec5SDimitry Andric   memRegion->curPos += size;
1060b57cec5SDimitry Andric   uint64_t newSize = memRegion->curPos - memRegion->origin;
1070b57cec5SDimitry Andric   if (newSize > memRegion->length)
1080b57cec5SDimitry Andric     error("section '" + secName + "' will not fit in region '" + regionName +
1090b57cec5SDimitry Andric           "': overflowed by " + Twine(newSize - memRegion->length) + " bytes");
1100b57cec5SDimitry Andric }
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric void LinkerScript::expandMemoryRegions(uint64_t size) {
1130b57cec5SDimitry Andric   if (ctx->memRegion)
1140b57cec5SDimitry Andric     expandMemoryRegion(ctx->memRegion, size, ctx->memRegion->name,
1150b57cec5SDimitry Andric                        ctx->outSec->name);
1160b57cec5SDimitry Andric   // Only expand the LMARegion if it is different from memRegion.
1170b57cec5SDimitry Andric   if (ctx->lmaRegion && ctx->memRegion != ctx->lmaRegion)
1180b57cec5SDimitry Andric     expandMemoryRegion(ctx->lmaRegion, size, ctx->lmaRegion->name,
1190b57cec5SDimitry Andric                        ctx->outSec->name);
1200b57cec5SDimitry Andric }
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric void LinkerScript::expandOutputSection(uint64_t size) {
1230b57cec5SDimitry Andric   ctx->outSec->size += size;
1240b57cec5SDimitry Andric   expandMemoryRegions(size);
1250b57cec5SDimitry Andric }
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric void LinkerScript::setDot(Expr e, const Twine &loc, bool inSec) {
1280b57cec5SDimitry Andric   uint64_t val = e().getValue();
1290b57cec5SDimitry Andric   if (val < dot && inSec)
1300b57cec5SDimitry Andric     error(loc + ": unable to move location counter backward for: " +
1310b57cec5SDimitry Andric           ctx->outSec->name);
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric   // Update to location counter means update to section size.
1340b57cec5SDimitry Andric   if (inSec)
1350b57cec5SDimitry Andric     expandOutputSection(val - dot);
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric   dot = val;
1380b57cec5SDimitry Andric }
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric // Used for handling linker symbol assignments, for both finalizing
1410b57cec5SDimitry Andric // their values and doing early declarations. Returns true if symbol
1420b57cec5SDimitry Andric // should be defined from linker script.
1430b57cec5SDimitry Andric static bool shouldDefineSym(SymbolAssignment *cmd) {
1440b57cec5SDimitry Andric   if (cmd->name == ".")
1450b57cec5SDimitry Andric     return false;
1460b57cec5SDimitry Andric 
1470b57cec5SDimitry Andric   if (!cmd->provide)
1480b57cec5SDimitry Andric     return true;
1490b57cec5SDimitry Andric 
1500b57cec5SDimitry Andric   // If a symbol was in PROVIDE(), we need to define it only
1510b57cec5SDimitry Andric   // when it is a referenced undefined symbol.
1520b57cec5SDimitry Andric   Symbol *b = symtab->find(cmd->name);
1530b57cec5SDimitry Andric   if (b && !b->isDefined())
1540b57cec5SDimitry Andric     return true;
1550b57cec5SDimitry Andric   return false;
1560b57cec5SDimitry Andric }
1570b57cec5SDimitry Andric 
15885868e8aSDimitry Andric // Called by processSymbolAssignments() to assign definitions to
15985868e8aSDimitry Andric // linker-script-defined symbols.
1600b57cec5SDimitry Andric void LinkerScript::addSymbol(SymbolAssignment *cmd) {
1610b57cec5SDimitry Andric   if (!shouldDefineSym(cmd))
1620b57cec5SDimitry Andric     return;
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   // Define a symbol.
1650b57cec5SDimitry Andric   ExprValue value = cmd->expression();
1660b57cec5SDimitry Andric   SectionBase *sec = value.isAbsolute() ? nullptr : value.sec;
1670b57cec5SDimitry Andric   uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   // When this function is called, section addresses have not been
1700b57cec5SDimitry Andric   // fixed yet. So, we may or may not know the value of the RHS
1710b57cec5SDimitry Andric   // expression.
1720b57cec5SDimitry Andric   //
1730b57cec5SDimitry Andric   // For example, if an expression is `x = 42`, we know x is always 42.
1740b57cec5SDimitry Andric   // However, if an expression is `x = .`, there's no way to know its
1750b57cec5SDimitry Andric   // value at the moment.
1760b57cec5SDimitry Andric   //
1770b57cec5SDimitry Andric   // We want to set symbol values early if we can. This allows us to
1780b57cec5SDimitry Andric   // use symbols as variables in linker scripts. Doing so allows us to
1790b57cec5SDimitry Andric   // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
1800b57cec5SDimitry Andric   uint64_t symValue = value.sec ? 0 : value.getValue();
1810b57cec5SDimitry Andric 
18285868e8aSDimitry Andric   Defined newSym(nullptr, cmd->name, STB_GLOBAL, visibility, STT_NOTYPE,
18385868e8aSDimitry Andric                  symValue, 0, sec);
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   Symbol *sym = symtab->insert(cmd->name);
18685868e8aSDimitry Andric   sym->mergeProperties(newSym);
18785868e8aSDimitry Andric   sym->replace(newSym);
1880b57cec5SDimitry Andric   cmd->sym = cast<Defined>(sym);
1890b57cec5SDimitry Andric }
1900b57cec5SDimitry Andric 
1910b57cec5SDimitry Andric // This function is called from LinkerScript::declareSymbols.
1920b57cec5SDimitry Andric // It creates a placeholder symbol if needed.
1930b57cec5SDimitry Andric static void declareSymbol(SymbolAssignment *cmd) {
1940b57cec5SDimitry Andric   if (!shouldDefineSym(cmd))
1950b57cec5SDimitry Andric     return;
1960b57cec5SDimitry Andric 
1970b57cec5SDimitry Andric   uint8_t visibility = cmd->hidden ? STV_HIDDEN : STV_DEFAULT;
19885868e8aSDimitry Andric   Defined newSym(nullptr, cmd->name, STB_GLOBAL, visibility, STT_NOTYPE, 0, 0,
1990b57cec5SDimitry Andric                  nullptr);
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric   // We can't calculate final value right now.
2020b57cec5SDimitry Andric   Symbol *sym = symtab->insert(cmd->name);
20385868e8aSDimitry Andric   sym->mergeProperties(newSym);
20485868e8aSDimitry Andric   sym->replace(newSym);
2050b57cec5SDimitry Andric 
2060b57cec5SDimitry Andric   cmd->sym = cast<Defined>(sym);
2070b57cec5SDimitry Andric   cmd->provide = false;
2080b57cec5SDimitry Andric   sym->scriptDefined = true;
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric 
21185868e8aSDimitry Andric using SymbolAssignmentMap =
21285868e8aSDimitry Andric     DenseMap<const Defined *, std::pair<SectionBase *, uint64_t>>;
21385868e8aSDimitry Andric 
21485868e8aSDimitry Andric // Collect section/value pairs of linker-script-defined symbols. This is used to
21585868e8aSDimitry Andric // check whether symbol values converge.
21685868e8aSDimitry Andric static SymbolAssignmentMap
21785868e8aSDimitry Andric getSymbolAssignmentValues(const std::vector<BaseCommand *> &sectionCommands) {
21885868e8aSDimitry Andric   SymbolAssignmentMap ret;
21985868e8aSDimitry Andric   for (BaseCommand *base : sectionCommands) {
22085868e8aSDimitry Andric     if (auto *cmd = dyn_cast<SymbolAssignment>(base)) {
22185868e8aSDimitry Andric       if (cmd->sym) // sym is nullptr for dot.
22285868e8aSDimitry Andric         ret.try_emplace(cmd->sym,
22385868e8aSDimitry Andric                         std::make_pair(cmd->sym->section, cmd->sym->value));
22485868e8aSDimitry Andric       continue;
22585868e8aSDimitry Andric     }
22685868e8aSDimitry Andric     for (BaseCommand *sub_base : cast<OutputSection>(base)->sectionCommands)
22785868e8aSDimitry Andric       if (auto *cmd = dyn_cast<SymbolAssignment>(sub_base))
22885868e8aSDimitry Andric         if (cmd->sym)
22985868e8aSDimitry Andric           ret.try_emplace(cmd->sym,
23085868e8aSDimitry Andric                           std::make_pair(cmd->sym->section, cmd->sym->value));
23185868e8aSDimitry Andric   }
23285868e8aSDimitry Andric   return ret;
23385868e8aSDimitry Andric }
23485868e8aSDimitry Andric 
23585868e8aSDimitry Andric // Returns the lexicographical smallest (for determinism) Defined whose
23685868e8aSDimitry Andric // section/value has changed.
23785868e8aSDimitry Andric static const Defined *
23885868e8aSDimitry Andric getChangedSymbolAssignment(const SymbolAssignmentMap &oldValues) {
23985868e8aSDimitry Andric   const Defined *changed = nullptr;
24085868e8aSDimitry Andric   for (auto &it : oldValues) {
24185868e8aSDimitry Andric     const Defined *sym = it.first;
24285868e8aSDimitry Andric     if (std::make_pair(sym->section, sym->value) != it.second &&
24385868e8aSDimitry Andric         (!changed || sym->getName() < changed->getName()))
24485868e8aSDimitry Andric       changed = sym;
24585868e8aSDimitry Andric   }
24685868e8aSDimitry Andric   return changed;
24785868e8aSDimitry Andric }
24885868e8aSDimitry Andric 
2490b57cec5SDimitry Andric // This method is used to handle INSERT AFTER statement. Here we rebuild
2500b57cec5SDimitry Andric // the list of script commands to mix sections inserted into.
2510b57cec5SDimitry Andric void LinkerScript::processInsertCommands() {
2520b57cec5SDimitry Andric   std::vector<BaseCommand *> v;
2530b57cec5SDimitry Andric   auto insert = [&](std::vector<BaseCommand *> &from) {
2540b57cec5SDimitry Andric     v.insert(v.end(), from.begin(), from.end());
2550b57cec5SDimitry Andric     from.clear();
2560b57cec5SDimitry Andric   };
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric   for (BaseCommand *base : sectionCommands) {
2590b57cec5SDimitry Andric     if (auto *os = dyn_cast<OutputSection>(base)) {
2600b57cec5SDimitry Andric       insert(insertBeforeCommands[os->name]);
2610b57cec5SDimitry Andric       v.push_back(base);
2620b57cec5SDimitry Andric       insert(insertAfterCommands[os->name]);
2630b57cec5SDimitry Andric       continue;
2640b57cec5SDimitry Andric     }
2650b57cec5SDimitry Andric     v.push_back(base);
2660b57cec5SDimitry Andric   }
2670b57cec5SDimitry Andric 
2680b57cec5SDimitry Andric   for (auto &cmds : {insertBeforeCommands, insertAfterCommands})
2690b57cec5SDimitry Andric     for (const std::pair<StringRef, std::vector<BaseCommand *>> &p : cmds)
2700b57cec5SDimitry Andric       if (!p.second.empty())
2710b57cec5SDimitry Andric         error("unable to INSERT AFTER/BEFORE " + p.first +
2720b57cec5SDimitry Andric               ": section not defined");
2730b57cec5SDimitry Andric 
2740b57cec5SDimitry Andric   sectionCommands = std::move(v);
2750b57cec5SDimitry Andric }
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric // Symbols defined in script should not be inlined by LTO. At the same time
2780b57cec5SDimitry Andric // we don't know their final values until late stages of link. Here we scan
2790b57cec5SDimitry Andric // over symbol assignment commands and create placeholder symbols if needed.
2800b57cec5SDimitry Andric void LinkerScript::declareSymbols() {
2810b57cec5SDimitry Andric   assert(!ctx);
2820b57cec5SDimitry Andric   for (BaseCommand *base : sectionCommands) {
2830b57cec5SDimitry Andric     if (auto *cmd = dyn_cast<SymbolAssignment>(base)) {
2840b57cec5SDimitry Andric       declareSymbol(cmd);
2850b57cec5SDimitry Andric       continue;
2860b57cec5SDimitry Andric     }
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric     // If the output section directive has constraints,
2890b57cec5SDimitry Andric     // we can't say for sure if it is going to be included or not.
2900b57cec5SDimitry Andric     // Skip such sections for now. Improve the checks if we ever
2910b57cec5SDimitry Andric     // need symbols from that sections to be declared early.
2920b57cec5SDimitry Andric     auto *sec = cast<OutputSection>(base);
2930b57cec5SDimitry Andric     if (sec->constraint != ConstraintKind::NoConstraint)
2940b57cec5SDimitry Andric       continue;
2950b57cec5SDimitry Andric     for (BaseCommand *base2 : sec->sectionCommands)
2960b57cec5SDimitry Andric       if (auto *cmd = dyn_cast<SymbolAssignment>(base2))
2970b57cec5SDimitry Andric         declareSymbol(cmd);
2980b57cec5SDimitry Andric   }
2990b57cec5SDimitry Andric }
3000b57cec5SDimitry Andric 
3010b57cec5SDimitry Andric // This function is called from assignAddresses, while we are
3020b57cec5SDimitry Andric // fixing the output section addresses. This function is supposed
3030b57cec5SDimitry Andric // to set the final value for a given symbol assignment.
3040b57cec5SDimitry Andric void LinkerScript::assignSymbol(SymbolAssignment *cmd, bool inSec) {
3050b57cec5SDimitry Andric   if (cmd->name == ".") {
3060b57cec5SDimitry Andric     setDot(cmd->expression, cmd->location, inSec);
3070b57cec5SDimitry Andric     return;
3080b57cec5SDimitry Andric   }
3090b57cec5SDimitry Andric 
3100b57cec5SDimitry Andric   if (!cmd->sym)
3110b57cec5SDimitry Andric     return;
3120b57cec5SDimitry Andric 
3130b57cec5SDimitry Andric   ExprValue v = cmd->expression();
3140b57cec5SDimitry Andric   if (v.isAbsolute()) {
3150b57cec5SDimitry Andric     cmd->sym->section = nullptr;
3160b57cec5SDimitry Andric     cmd->sym->value = v.getValue();
3170b57cec5SDimitry Andric   } else {
3180b57cec5SDimitry Andric     cmd->sym->section = v.sec;
3190b57cec5SDimitry Andric     cmd->sym->value = v.getSectionOffset();
3200b57cec5SDimitry Andric   }
3210b57cec5SDimitry Andric }
3220b57cec5SDimitry Andric 
3230b57cec5SDimitry Andric static std::string getFilename(InputFile *file) {
3240b57cec5SDimitry Andric   if (!file)
3250b57cec5SDimitry Andric     return "";
3260b57cec5SDimitry Andric   if (file->archiveName.empty())
3270b57cec5SDimitry Andric     return file->getName();
3280b57cec5SDimitry Andric   return (file->archiveName + "(" + file->getName() + ")").str();
3290b57cec5SDimitry Andric }
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric bool LinkerScript::shouldKeep(InputSectionBase *s) {
3320b57cec5SDimitry Andric   if (keptSections.empty())
3330b57cec5SDimitry Andric     return false;
3340b57cec5SDimitry Andric   std::string filename = getFilename(s->file);
3350b57cec5SDimitry Andric   for (InputSectionDescription *id : keptSections)
3360b57cec5SDimitry Andric     if (id->filePat.match(filename))
3370b57cec5SDimitry Andric       for (SectionPattern &p : id->sectionPatterns)
3380b57cec5SDimitry Andric         if (p.sectionPat.match(s->name))
3390b57cec5SDimitry Andric           return true;
3400b57cec5SDimitry Andric   return false;
3410b57cec5SDimitry Andric }
3420b57cec5SDimitry Andric 
3430b57cec5SDimitry Andric // A helper function for the SORT() command.
34485868e8aSDimitry Andric static bool matchConstraints(ArrayRef<InputSectionBase *> sections,
3450b57cec5SDimitry Andric                              ConstraintKind kind) {
3460b57cec5SDimitry Andric   if (kind == ConstraintKind::NoConstraint)
3470b57cec5SDimitry Andric     return true;
3480b57cec5SDimitry Andric 
3490b57cec5SDimitry Andric   bool isRW = llvm::any_of(
35085868e8aSDimitry Andric       sections, [](InputSectionBase *sec) { return sec->flags & SHF_WRITE; });
3510b57cec5SDimitry Andric 
3520b57cec5SDimitry Andric   return (isRW && kind == ConstraintKind::ReadWrite) ||
3530b57cec5SDimitry Andric          (!isRW && kind == ConstraintKind::ReadOnly);
3540b57cec5SDimitry Andric }
3550b57cec5SDimitry Andric 
35685868e8aSDimitry Andric static void sortSections(MutableArrayRef<InputSectionBase *> vec,
3570b57cec5SDimitry Andric                          SortSectionPolicy k) {
35885868e8aSDimitry Andric   auto alignmentComparator = [](InputSectionBase *a, InputSectionBase *b) {
35985868e8aSDimitry Andric     // ">" is not a mistake. Sections with larger alignments are placed
36085868e8aSDimitry Andric     // before sections with smaller alignments in order to reduce the
36185868e8aSDimitry Andric     // amount of padding necessary. This is compatible with GNU.
36285868e8aSDimitry Andric     return a->alignment > b->alignment;
36385868e8aSDimitry Andric   };
36485868e8aSDimitry Andric   auto nameComparator = [](InputSectionBase *a, InputSectionBase *b) {
36585868e8aSDimitry Andric     return a->name < b->name;
36685868e8aSDimitry Andric   };
36785868e8aSDimitry Andric   auto priorityComparator = [](InputSectionBase *a, InputSectionBase *b) {
36885868e8aSDimitry Andric     return getPriority(a->name) < getPriority(b->name);
36985868e8aSDimitry Andric   };
37085868e8aSDimitry Andric 
37185868e8aSDimitry Andric   switch (k) {
37285868e8aSDimitry Andric   case SortSectionPolicy::Default:
37385868e8aSDimitry Andric   case SortSectionPolicy::None:
37485868e8aSDimitry Andric     return;
37585868e8aSDimitry Andric   case SortSectionPolicy::Alignment:
37685868e8aSDimitry Andric     return llvm::stable_sort(vec, alignmentComparator);
37785868e8aSDimitry Andric   case SortSectionPolicy::Name:
37885868e8aSDimitry Andric     return llvm::stable_sort(vec, nameComparator);
37985868e8aSDimitry Andric   case SortSectionPolicy::Priority:
38085868e8aSDimitry Andric     return llvm::stable_sort(vec, priorityComparator);
38185868e8aSDimitry Andric   }
3820b57cec5SDimitry Andric }
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric // Sort sections as instructed by SORT-family commands and --sort-section
3850b57cec5SDimitry Andric // option. Because SORT-family commands can be nested at most two depth
3860b57cec5SDimitry Andric // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
3870b57cec5SDimitry Andric // line option is respected even if a SORT command is given, the exact
3880b57cec5SDimitry Andric // behavior we have here is a bit complicated. Here are the rules.
3890b57cec5SDimitry Andric //
3900b57cec5SDimitry Andric // 1. If two SORT commands are given, --sort-section is ignored.
3910b57cec5SDimitry Andric // 2. If one SORT command is given, and if it is not SORT_NONE,
3920b57cec5SDimitry Andric //    --sort-section is handled as an inner SORT command.
3930b57cec5SDimitry Andric // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
3940b57cec5SDimitry Andric // 4. If no SORT command is given, sort according to --sort-section.
39585868e8aSDimitry Andric static void sortInputSections(MutableArrayRef<InputSectionBase *> vec,
3960b57cec5SDimitry Andric                               const SectionPattern &pat) {
3970b57cec5SDimitry Andric   if (pat.sortOuter == SortSectionPolicy::None)
3980b57cec5SDimitry Andric     return;
3990b57cec5SDimitry Andric 
4000b57cec5SDimitry Andric   if (pat.sortInner == SortSectionPolicy::Default)
4010b57cec5SDimitry Andric     sortSections(vec, config->sortSection);
4020b57cec5SDimitry Andric   else
4030b57cec5SDimitry Andric     sortSections(vec, pat.sortInner);
4040b57cec5SDimitry Andric   sortSections(vec, pat.sortOuter);
4050b57cec5SDimitry Andric }
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric // Compute and remember which sections the InputSectionDescription matches.
40885868e8aSDimitry Andric std::vector<InputSectionBase *>
4090b57cec5SDimitry Andric LinkerScript::computeInputSections(const InputSectionDescription *cmd) {
41085868e8aSDimitry Andric   std::vector<InputSectionBase *> ret;
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric   // Collects all sections that satisfy constraints of Cmd.
4130b57cec5SDimitry Andric   for (const SectionPattern &pat : cmd->sectionPatterns) {
4140b57cec5SDimitry Andric     size_t sizeBefore = ret.size();
4150b57cec5SDimitry Andric 
4160b57cec5SDimitry Andric     for (InputSectionBase *sec : inputSections) {
41785868e8aSDimitry Andric       if (!sec->isLive() || sec->parent)
4180b57cec5SDimitry Andric         continue;
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric       // For -emit-relocs we have to ignore entries like
4210b57cec5SDimitry Andric       //   .rela.dyn : { *(.rela.data) }
4220b57cec5SDimitry Andric       // which are common because they are in the default bfd script.
4230b57cec5SDimitry Andric       // We do not ignore SHT_REL[A] linker-synthesized sections here because
4240b57cec5SDimitry Andric       // want to support scripts that do custom layout for them.
42585868e8aSDimitry Andric       if (isa<InputSection>(sec) &&
42685868e8aSDimitry Andric           cast<InputSection>(sec)->getRelocatedSection())
4270b57cec5SDimitry Andric         continue;
4280b57cec5SDimitry Andric 
4290b57cec5SDimitry Andric       std::string filename = getFilename(sec->file);
4300b57cec5SDimitry Andric       if (!cmd->filePat.match(filename) ||
4310b57cec5SDimitry Andric           pat.excludedFilePat.match(filename) ||
4320b57cec5SDimitry Andric           !pat.sectionPat.match(sec->name))
4330b57cec5SDimitry Andric         continue;
4340b57cec5SDimitry Andric 
43585868e8aSDimitry Andric       ret.push_back(sec);
4360b57cec5SDimitry Andric     }
4370b57cec5SDimitry Andric 
43885868e8aSDimitry Andric     sortInputSections(
43985868e8aSDimitry Andric         MutableArrayRef<InputSectionBase *>(ret).slice(sizeBefore), pat);
4400b57cec5SDimitry Andric   }
4410b57cec5SDimitry Andric   return ret;
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric 
44485868e8aSDimitry Andric void LinkerScript::discard(InputSectionBase *s) {
445*480093f4SDimitry Andric   if (s == in.shStrTab || s == mainPart->relrDyn)
4460b57cec5SDimitry Andric     error("discarding " + s->name + " section is not allowed");
4470b57cec5SDimitry Andric 
4480b57cec5SDimitry Andric   // You can discard .hash and .gnu.hash sections by linker scripts. Since
4490b57cec5SDimitry Andric   // they are synthesized sections, we need to handle them differently than
4500b57cec5SDimitry Andric   // other regular sections.
4510b57cec5SDimitry Andric   if (s == mainPart->gnuHashTab)
4520b57cec5SDimitry Andric     mainPart->gnuHashTab = nullptr;
4530b57cec5SDimitry Andric   if (s == mainPart->hashTab)
4540b57cec5SDimitry Andric     mainPart->hashTab = nullptr;
4550b57cec5SDimitry Andric 
4560b57cec5SDimitry Andric   s->markDead();
45785868e8aSDimitry Andric   s->parent = nullptr;
45885868e8aSDimitry Andric   for (InputSection *ds : s->dependentSections)
45985868e8aSDimitry Andric     discard(ds);
4600b57cec5SDimitry Andric }
4610b57cec5SDimitry Andric 
46285868e8aSDimitry Andric std::vector<InputSectionBase *>
4630b57cec5SDimitry Andric LinkerScript::createInputSectionList(OutputSection &outCmd) {
46485868e8aSDimitry Andric   std::vector<InputSectionBase *> ret;
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric   for (BaseCommand *base : outCmd.sectionCommands) {
4670b57cec5SDimitry Andric     if (auto *cmd = dyn_cast<InputSectionDescription>(base)) {
46885868e8aSDimitry Andric       cmd->sectionBases = computeInputSections(cmd);
46985868e8aSDimitry Andric       for (InputSectionBase *s : cmd->sectionBases)
47085868e8aSDimitry Andric         s->parent = &outCmd;
47185868e8aSDimitry Andric       ret.insert(ret.end(), cmd->sectionBases.begin(), cmd->sectionBases.end());
4720b57cec5SDimitry Andric     }
4730b57cec5SDimitry Andric   }
4740b57cec5SDimitry Andric   return ret;
4750b57cec5SDimitry Andric }
4760b57cec5SDimitry Andric 
47785868e8aSDimitry Andric // Create output sections described by SECTIONS commands.
4780b57cec5SDimitry Andric void LinkerScript::processSectionCommands() {
4790b57cec5SDimitry Andric   size_t i = 0;
4800b57cec5SDimitry Andric   for (BaseCommand *base : sectionCommands) {
4810b57cec5SDimitry Andric     if (auto *sec = dyn_cast<OutputSection>(base)) {
48285868e8aSDimitry Andric       std::vector<InputSectionBase *> v = createInputSectionList(*sec);
4830b57cec5SDimitry Andric 
4840b57cec5SDimitry Andric       // The output section name `/DISCARD/' is special.
4850b57cec5SDimitry Andric       // Any input section assigned to it is discarded.
4860b57cec5SDimitry Andric       if (sec->name == "/DISCARD/") {
48785868e8aSDimitry Andric         for (InputSectionBase *s : v)
48885868e8aSDimitry Andric           discard(s);
4890b57cec5SDimitry Andric         sec->sectionCommands.clear();
4900b57cec5SDimitry Andric         continue;
4910b57cec5SDimitry Andric       }
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
4940b57cec5SDimitry Andric       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
4950b57cec5SDimitry Andric       // sections satisfy a given constraint. If not, a directive is handled
4960b57cec5SDimitry Andric       // as if it wasn't present from the beginning.
4970b57cec5SDimitry Andric       //
4980b57cec5SDimitry Andric       // Because we'll iterate over SectionCommands many more times, the easy
4990b57cec5SDimitry Andric       // way to "make it as if it wasn't present" is to make it empty.
5000b57cec5SDimitry Andric       if (!matchConstraints(v, sec->constraint)) {
5010b57cec5SDimitry Andric         for (InputSectionBase *s : v)
50285868e8aSDimitry Andric           s->parent = nullptr;
5030b57cec5SDimitry Andric         sec->sectionCommands.clear();
5040b57cec5SDimitry Andric         continue;
5050b57cec5SDimitry Andric       }
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
5080b57cec5SDimitry Andric       // is given, input sections are aligned to that value, whether the
5090b57cec5SDimitry Andric       // given value is larger or smaller than the original section alignment.
5100b57cec5SDimitry Andric       if (sec->subalignExpr) {
5110b57cec5SDimitry Andric         uint32_t subalign = sec->subalignExpr().getValue();
5120b57cec5SDimitry Andric         for (InputSectionBase *s : v)
5130b57cec5SDimitry Andric           s->alignment = subalign;
5140b57cec5SDimitry Andric       }
5150b57cec5SDimitry Andric 
51685868e8aSDimitry Andric       // Set the partition field the same way OutputSection::recordSection()
51785868e8aSDimitry Andric       // does. Partitions cannot be used with the SECTIONS command, so this is
51885868e8aSDimitry Andric       // always 1.
51985868e8aSDimitry Andric       sec->partition = 1;
5200b57cec5SDimitry Andric 
5210b57cec5SDimitry Andric       sec->sectionIndex = i++;
5220b57cec5SDimitry Andric     }
5230b57cec5SDimitry Andric   }
52485868e8aSDimitry Andric }
52585868e8aSDimitry Andric 
52685868e8aSDimitry Andric void LinkerScript::processSymbolAssignments() {
52785868e8aSDimitry Andric   // Dot outside an output section still represents a relative address, whose
52885868e8aSDimitry Andric   // sh_shndx should not be SHN_UNDEF or SHN_ABS. Create a dummy aether section
52985868e8aSDimitry Andric   // that fills the void outside a section. It has an index of one, which is
53085868e8aSDimitry Andric   // indistinguishable from any other regular section index.
53185868e8aSDimitry Andric   aether = make<OutputSection>("", 0, SHF_ALLOC);
53285868e8aSDimitry Andric   aether->sectionIndex = 1;
53385868e8aSDimitry Andric 
53485868e8aSDimitry Andric   // ctx captures the local AddressState and makes it accessible deliberately.
53585868e8aSDimitry Andric   // This is needed as there are some cases where we cannot just thread the
53685868e8aSDimitry Andric   // current state through to a lambda function created by the script parser.
53785868e8aSDimitry Andric   AddressState state;
53885868e8aSDimitry Andric   ctx = &state;
53985868e8aSDimitry Andric   ctx->outSec = aether;
54085868e8aSDimitry Andric 
54185868e8aSDimitry Andric   for (BaseCommand *base : sectionCommands) {
54285868e8aSDimitry Andric     if (auto *cmd = dyn_cast<SymbolAssignment>(base))
54385868e8aSDimitry Andric       addSymbol(cmd);
54485868e8aSDimitry Andric     else
54585868e8aSDimitry Andric       for (BaseCommand *sub_base : cast<OutputSection>(base)->sectionCommands)
54685868e8aSDimitry Andric         if (auto *cmd = dyn_cast<SymbolAssignment>(sub_base))
54785868e8aSDimitry Andric           addSymbol(cmd);
54885868e8aSDimitry Andric   }
54985868e8aSDimitry Andric 
5500b57cec5SDimitry Andric   ctx = nullptr;
5510b57cec5SDimitry Andric }
5520b57cec5SDimitry Andric 
5530b57cec5SDimitry Andric static OutputSection *findByName(ArrayRef<BaseCommand *> vec,
5540b57cec5SDimitry Andric                                  StringRef name) {
5550b57cec5SDimitry Andric   for (BaseCommand *base : vec)
5560b57cec5SDimitry Andric     if (auto *sec = dyn_cast<OutputSection>(base))
5570b57cec5SDimitry Andric       if (sec->name == name)
5580b57cec5SDimitry Andric         return sec;
5590b57cec5SDimitry Andric   return nullptr;
5600b57cec5SDimitry Andric }
5610b57cec5SDimitry Andric 
5620b57cec5SDimitry Andric static OutputSection *createSection(InputSectionBase *isec,
5630b57cec5SDimitry Andric                                     StringRef outsecName) {
5640b57cec5SDimitry Andric   OutputSection *sec = script->createOutputSection(outsecName, "<internal>");
56585868e8aSDimitry Andric   sec->recordSection(isec);
5660b57cec5SDimitry Andric   return sec;
5670b57cec5SDimitry Andric }
5680b57cec5SDimitry Andric 
5690b57cec5SDimitry Andric static OutputSection *
5700b57cec5SDimitry Andric addInputSec(StringMap<TinyPtrVector<OutputSection *>> &map,
5710b57cec5SDimitry Andric             InputSectionBase *isec, StringRef outsecName) {
5720b57cec5SDimitry Andric   // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r
5730b57cec5SDimitry Andric   // option is given. A section with SHT_GROUP defines a "section group", and
5740b57cec5SDimitry Andric   // its members have SHF_GROUP attribute. Usually these flags have already been
5750b57cec5SDimitry Andric   // stripped by InputFiles.cpp as section groups are processed and uniquified.
5760b57cec5SDimitry Andric   // However, for the -r option, we want to pass through all section groups
5770b57cec5SDimitry Andric   // as-is because adding/removing members or merging them with other groups
5780b57cec5SDimitry Andric   // change their semantics.
5790b57cec5SDimitry Andric   if (isec->type == SHT_GROUP || (isec->flags & SHF_GROUP))
5800b57cec5SDimitry Andric     return createSection(isec, outsecName);
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric   // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
5830b57cec5SDimitry Andric   // relocation sections .rela.foo and .rela.bar for example. Most tools do
5840b57cec5SDimitry Andric   // not allow multiple REL[A] sections for output section. Hence we
5850b57cec5SDimitry Andric   // should combine these relocation sections into single output.
5860b57cec5SDimitry Andric   // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
5870b57cec5SDimitry Andric   // other REL[A] sections created by linker itself.
5880b57cec5SDimitry Andric   if (!isa<SyntheticSection>(isec) &&
5890b57cec5SDimitry Andric       (isec->type == SHT_REL || isec->type == SHT_RELA)) {
5900b57cec5SDimitry Andric     auto *sec = cast<InputSection>(isec);
5910b57cec5SDimitry Andric     OutputSection *out = sec->getRelocatedSection()->getOutputSection();
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric     if (out->relocationSection) {
59485868e8aSDimitry Andric       out->relocationSection->recordSection(sec);
5950b57cec5SDimitry Andric       return nullptr;
5960b57cec5SDimitry Andric     }
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric     out->relocationSection = createSection(isec, outsecName);
5990b57cec5SDimitry Andric     return out->relocationSection;
6000b57cec5SDimitry Andric   }
6010b57cec5SDimitry Andric 
6020b57cec5SDimitry Andric   //  The ELF spec just says
6030b57cec5SDimitry Andric   // ----------------------------------------------------------------
6040b57cec5SDimitry Andric   // In the first phase, input sections that match in name, type and
6050b57cec5SDimitry Andric   // attribute flags should be concatenated into single sections.
6060b57cec5SDimitry Andric   // ----------------------------------------------------------------
6070b57cec5SDimitry Andric   //
6080b57cec5SDimitry Andric   // However, it is clear that at least some flags have to be ignored for
6090b57cec5SDimitry Andric   // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
6100b57cec5SDimitry Andric   // ignored. We should not have two output .text sections just because one was
6110b57cec5SDimitry Andric   // in a group and another was not for example.
6120b57cec5SDimitry Andric   //
6130b57cec5SDimitry Andric   // It also seems that wording was a late addition and didn't get the
6140b57cec5SDimitry Andric   // necessary scrutiny.
6150b57cec5SDimitry Andric   //
6160b57cec5SDimitry Andric   // Merging sections with different flags is expected by some users. One
6170b57cec5SDimitry Andric   // reason is that if one file has
6180b57cec5SDimitry Andric   //
6190b57cec5SDimitry Andric   // int *const bar __attribute__((section(".foo"))) = (int *)0;
6200b57cec5SDimitry Andric   //
6210b57cec5SDimitry Andric   // gcc with -fPIC will produce a read only .foo section. But if another
6220b57cec5SDimitry Andric   // file has
6230b57cec5SDimitry Andric   //
6240b57cec5SDimitry Andric   // int zed;
6250b57cec5SDimitry Andric   // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
6260b57cec5SDimitry Andric   //
6270b57cec5SDimitry Andric   // gcc with -fPIC will produce a read write section.
6280b57cec5SDimitry Andric   //
6290b57cec5SDimitry Andric   // Last but not least, when using linker script the merge rules are forced by
6300b57cec5SDimitry Andric   // the script. Unfortunately, linker scripts are name based. This means that
6310b57cec5SDimitry Andric   // expressions like *(.foo*) can refer to multiple input sections with
6320b57cec5SDimitry Andric   // different flags. We cannot put them in different output sections or we
6330b57cec5SDimitry Andric   // would produce wrong results for
6340b57cec5SDimitry Andric   //
6350b57cec5SDimitry Andric   // start = .; *(.foo.*) end = .; *(.bar)
6360b57cec5SDimitry Andric   //
6370b57cec5SDimitry Andric   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
6380b57cec5SDimitry Andric   // another. The problem is that there is no way to layout those output
6390b57cec5SDimitry Andric   // sections such that the .foo sections are the only thing between the start
6400b57cec5SDimitry Andric   // and end symbols.
6410b57cec5SDimitry Andric   //
6420b57cec5SDimitry Andric   // Given the above issues, we instead merge sections by name and error on
6430b57cec5SDimitry Andric   // incompatible types and flags.
6440b57cec5SDimitry Andric   TinyPtrVector<OutputSection *> &v = map[outsecName];
6450b57cec5SDimitry Andric   for (OutputSection *sec : v) {
6460b57cec5SDimitry Andric     if (sec->partition != isec->partition)
6470b57cec5SDimitry Andric       continue;
64885868e8aSDimitry Andric 
64985868e8aSDimitry Andric     if (config->relocatable && (isec->flags & SHF_LINK_ORDER)) {
65085868e8aSDimitry Andric       // Merging two SHF_LINK_ORDER sections with different sh_link fields will
65185868e8aSDimitry Andric       // change their semantics, so we only merge them in -r links if they will
65285868e8aSDimitry Andric       // end up being linked to the same output section. The casts are fine
65385868e8aSDimitry Andric       // because everything in the map was created by the orphan placement code.
65485868e8aSDimitry Andric       auto *firstIsec = cast<InputSectionBase>(
65585868e8aSDimitry Andric           cast<InputSectionDescription>(sec->sectionCommands[0])
65685868e8aSDimitry Andric               ->sectionBases[0]);
65785868e8aSDimitry Andric       if (firstIsec->getLinkOrderDep()->getOutputSection() !=
65885868e8aSDimitry Andric           isec->getLinkOrderDep()->getOutputSection())
65985868e8aSDimitry Andric         continue;
66085868e8aSDimitry Andric     }
66185868e8aSDimitry Andric 
66285868e8aSDimitry Andric     sec->recordSection(isec);
6630b57cec5SDimitry Andric     return nullptr;
6640b57cec5SDimitry Andric   }
6650b57cec5SDimitry Andric 
6660b57cec5SDimitry Andric   OutputSection *sec = createSection(isec, outsecName);
6670b57cec5SDimitry Andric   v.push_back(sec);
6680b57cec5SDimitry Andric   return sec;
6690b57cec5SDimitry Andric }
6700b57cec5SDimitry Andric 
6710b57cec5SDimitry Andric // Add sections that didn't match any sections command.
6720b57cec5SDimitry Andric void LinkerScript::addOrphanSections() {
6730b57cec5SDimitry Andric   StringMap<TinyPtrVector<OutputSection *>> map;
6740b57cec5SDimitry Andric   std::vector<OutputSection *> v;
6750b57cec5SDimitry Andric 
67685868e8aSDimitry Andric   std::function<void(InputSectionBase *)> add;
67785868e8aSDimitry Andric   add = [&](InputSectionBase *s) {
67885868e8aSDimitry Andric     if (s->isLive() && !s->parent) {
6790b57cec5SDimitry Andric       StringRef name = getOutputSectionName(s);
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric       if (config->orphanHandling == OrphanHandlingPolicy::Error)
6820b57cec5SDimitry Andric         error(toString(s) + " is being placed in '" + name + "'");
6830b57cec5SDimitry Andric       else if (config->orphanHandling == OrphanHandlingPolicy::Warn)
6840b57cec5SDimitry Andric         warn(toString(s) + " is being placed in '" + name + "'");
6850b57cec5SDimitry Andric 
6860b57cec5SDimitry Andric       if (OutputSection *sec = findByName(sectionCommands, name)) {
68785868e8aSDimitry Andric         sec->recordSection(s);
68885868e8aSDimitry Andric       } else {
6890b57cec5SDimitry Andric         if (OutputSection *os = addInputSec(map, s, name))
6900b57cec5SDimitry Andric           v.push_back(os);
69185868e8aSDimitry Andric         assert(isa<MergeInputSection>(s) ||
69285868e8aSDimitry Andric                s->getOutputSection()->sectionIndex == UINT32_MAX);
69385868e8aSDimitry Andric       }
69485868e8aSDimitry Andric     }
69585868e8aSDimitry Andric 
69685868e8aSDimitry Andric     if (config->relocatable)
69785868e8aSDimitry Andric       for (InputSectionBase *depSec : s->dependentSections)
69885868e8aSDimitry Andric         if (depSec->flags & SHF_LINK_ORDER)
69985868e8aSDimitry Andric           add(depSec);
7000b57cec5SDimitry Andric   };
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric   // For futher --emit-reloc handling code we need target output section
7030b57cec5SDimitry Andric   // to be created before we create relocation output section, so we want
7040b57cec5SDimitry Andric   // to create target sections first. We do not want priority handling
7050b57cec5SDimitry Andric   // for synthetic sections because them are special.
7060b57cec5SDimitry Andric   for (InputSectionBase *isec : inputSections) {
70785868e8aSDimitry Andric     // In -r links, SHF_LINK_ORDER sections are added while adding their parent
70885868e8aSDimitry Andric     // sections because we need to know the parent's output section before we
70985868e8aSDimitry Andric     // can select an output section for the SHF_LINK_ORDER section.
71085868e8aSDimitry Andric     if (config->relocatable && (isec->flags & SHF_LINK_ORDER))
71185868e8aSDimitry Andric       continue;
71285868e8aSDimitry Andric 
7130b57cec5SDimitry Andric     if (auto *sec = dyn_cast<InputSection>(isec))
7140b57cec5SDimitry Andric       if (InputSectionBase *rel = sec->getRelocatedSection())
7150b57cec5SDimitry Andric         if (auto *relIS = dyn_cast_or_null<InputSectionBase>(rel->parent))
7160b57cec5SDimitry Andric           add(relIS);
7170b57cec5SDimitry Andric     add(isec);
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric   // If no SECTIONS command was given, we should insert sections commands
7210b57cec5SDimitry Andric   // before others, so that we can handle scripts which refers them,
7220b57cec5SDimitry Andric   // for example: "foo = ABSOLUTE(ADDR(.text)));".
7230b57cec5SDimitry Andric   // When SECTIONS command is present we just add all orphans to the end.
7240b57cec5SDimitry Andric   if (hasSectionsCommand)
7250b57cec5SDimitry Andric     sectionCommands.insert(sectionCommands.end(), v.begin(), v.end());
7260b57cec5SDimitry Andric   else
7270b57cec5SDimitry Andric     sectionCommands.insert(sectionCommands.begin(), v.begin(), v.end());
7280b57cec5SDimitry Andric }
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric uint64_t LinkerScript::advance(uint64_t size, unsigned alignment) {
7310b57cec5SDimitry Andric   bool isTbss =
7320b57cec5SDimitry Andric       (ctx->outSec->flags & SHF_TLS) && ctx->outSec->type == SHT_NOBITS;
7330b57cec5SDimitry Andric   uint64_t start = isTbss ? dot + ctx->threadBssOffset : dot;
7340b57cec5SDimitry Andric   start = alignTo(start, alignment);
7350b57cec5SDimitry Andric   uint64_t end = start + size;
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric   if (isTbss)
7380b57cec5SDimitry Andric     ctx->threadBssOffset = end - dot;
7390b57cec5SDimitry Andric   else
7400b57cec5SDimitry Andric     dot = end;
7410b57cec5SDimitry Andric   return end;
7420b57cec5SDimitry Andric }
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric void LinkerScript::output(InputSection *s) {
7450b57cec5SDimitry Andric   assert(ctx->outSec == s->getParent());
7460b57cec5SDimitry Andric   uint64_t before = advance(0, 1);
7470b57cec5SDimitry Andric   uint64_t pos = advance(s->getSize(), s->alignment);
7480b57cec5SDimitry Andric   s->outSecOff = pos - s->getSize() - ctx->outSec->addr;
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric   // Update output section size after adding each section. This is so that
7510b57cec5SDimitry Andric   // SIZEOF works correctly in the case below:
7520b57cec5SDimitry Andric   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
7530b57cec5SDimitry Andric   expandOutputSection(pos - before);
7540b57cec5SDimitry Andric }
7550b57cec5SDimitry Andric 
7560b57cec5SDimitry Andric void LinkerScript::switchTo(OutputSection *sec) {
7570b57cec5SDimitry Andric   ctx->outSec = sec;
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric   uint64_t before = advance(0, 1);
7600b57cec5SDimitry Andric   ctx->outSec->addr = advance(0, ctx->outSec->alignment);
7610b57cec5SDimitry Andric   expandMemoryRegions(ctx->outSec->addr - before);
7620b57cec5SDimitry Andric }
7630b57cec5SDimitry Andric 
7640b57cec5SDimitry Andric // This function searches for a memory region to place the given output
7650b57cec5SDimitry Andric // section in. If found, a pointer to the appropriate memory region is
7660b57cec5SDimitry Andric // returned. Otherwise, a nullptr is returned.
7670b57cec5SDimitry Andric MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *sec) {
7680b57cec5SDimitry Andric   // If a memory region name was specified in the output section command,
7690b57cec5SDimitry Andric   // then try to find that region first.
7700b57cec5SDimitry Andric   if (!sec->memoryRegionName.empty()) {
7710b57cec5SDimitry Andric     if (MemoryRegion *m = memoryRegions.lookup(sec->memoryRegionName))
7720b57cec5SDimitry Andric       return m;
7730b57cec5SDimitry Andric     error("memory region '" + sec->memoryRegionName + "' not declared");
7740b57cec5SDimitry Andric     return nullptr;
7750b57cec5SDimitry Andric   }
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric   // If at least one memory region is defined, all sections must
7780b57cec5SDimitry Andric   // belong to some memory region. Otherwise, we don't need to do
7790b57cec5SDimitry Andric   // anything for memory regions.
7800b57cec5SDimitry Andric   if (memoryRegions.empty())
7810b57cec5SDimitry Andric     return nullptr;
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric   // See if a region can be found by matching section flags.
7840b57cec5SDimitry Andric   for (auto &pair : memoryRegions) {
7850b57cec5SDimitry Andric     MemoryRegion *m = pair.second;
7860b57cec5SDimitry Andric     if ((m->flags & sec->flags) && (m->negFlags & sec->flags) == 0)
7870b57cec5SDimitry Andric       return m;
7880b57cec5SDimitry Andric   }
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric   // Otherwise, no suitable region was found.
7910b57cec5SDimitry Andric   if (sec->flags & SHF_ALLOC)
7920b57cec5SDimitry Andric     error("no memory region specified for section '" + sec->name + "'");
7930b57cec5SDimitry Andric   return nullptr;
7940b57cec5SDimitry Andric }
7950b57cec5SDimitry Andric 
7960b57cec5SDimitry Andric static OutputSection *findFirstSection(PhdrEntry *load) {
7970b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
7980b57cec5SDimitry Andric     if (sec->ptLoad == load)
7990b57cec5SDimitry Andric       return sec;
8000b57cec5SDimitry Andric   return nullptr;
8010b57cec5SDimitry Andric }
8020b57cec5SDimitry Andric 
8030b57cec5SDimitry Andric // This function assigns offsets to input sections and an output section
8040b57cec5SDimitry Andric // for a single sections command (e.g. ".text { *(.text); }").
8050b57cec5SDimitry Andric void LinkerScript::assignOffsets(OutputSection *sec) {
8060b57cec5SDimitry Andric   if (!(sec->flags & SHF_ALLOC))
8070b57cec5SDimitry Andric     dot = 0;
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric   ctx->memRegion = sec->memRegion;
8100b57cec5SDimitry Andric   ctx->lmaRegion = sec->lmaRegion;
8110b57cec5SDimitry Andric   if (ctx->memRegion)
8120b57cec5SDimitry Andric     dot = ctx->memRegion->curPos;
8130b57cec5SDimitry Andric 
8140b57cec5SDimitry Andric   if ((sec->flags & SHF_ALLOC) && sec->addrExpr)
8150b57cec5SDimitry Andric     setDot(sec->addrExpr, sec->location, false);
8160b57cec5SDimitry Andric 
81785868e8aSDimitry Andric   // If the address of the section has been moved forward by an explicit
81885868e8aSDimitry Andric   // expression so that it now starts past the current curPos of the enclosing
81985868e8aSDimitry Andric   // region, we need to expand the current region to account for the space
82085868e8aSDimitry Andric   // between the previous section, if any, and the start of this section.
82185868e8aSDimitry Andric   if (ctx->memRegion && ctx->memRegion->curPos < dot)
82285868e8aSDimitry Andric     expandMemoryRegion(ctx->memRegion, dot - ctx->memRegion->curPos,
82385868e8aSDimitry Andric                        ctx->memRegion->name, sec->name);
82485868e8aSDimitry Andric 
8250b57cec5SDimitry Andric   switchTo(sec);
8260b57cec5SDimitry Andric 
8270b57cec5SDimitry Andric   if (sec->lmaExpr)
8280b57cec5SDimitry Andric     ctx->lmaOffset = sec->lmaExpr().getValue() - dot;
8290b57cec5SDimitry Andric 
8300b57cec5SDimitry Andric   if (MemoryRegion *mr = sec->lmaRegion)
8310b57cec5SDimitry Andric     ctx->lmaOffset = mr->curPos - dot;
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric   // If neither AT nor AT> is specified for an allocatable section, the linker
8340b57cec5SDimitry Andric   // will set the LMA such that the difference between VMA and LMA for the
8350b57cec5SDimitry Andric   // section is the same as the preceding output section in the same region
8360b57cec5SDimitry Andric   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
8370b57cec5SDimitry Andric   // This, however, should only be done by the first "non-header" section
8380b57cec5SDimitry Andric   // in the segment.
8390b57cec5SDimitry Andric   if (PhdrEntry *l = ctx->outSec->ptLoad)
8400b57cec5SDimitry Andric     if (sec == findFirstSection(l))
8410b57cec5SDimitry Andric       l->lmaOffset = ctx->lmaOffset;
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric   // We can call this method multiple times during the creation of
8440b57cec5SDimitry Andric   // thunks and want to start over calculation each time.
8450b57cec5SDimitry Andric   sec->size = 0;
8460b57cec5SDimitry Andric 
8470b57cec5SDimitry Andric   // We visited SectionsCommands from processSectionCommands to
8480b57cec5SDimitry Andric   // layout sections. Now, we visit SectionsCommands again to fix
8490b57cec5SDimitry Andric   // section offsets.
8500b57cec5SDimitry Andric   for (BaseCommand *base : sec->sectionCommands) {
8510b57cec5SDimitry Andric     // This handles the assignments to symbol or to the dot.
8520b57cec5SDimitry Andric     if (auto *cmd = dyn_cast<SymbolAssignment>(base)) {
8530b57cec5SDimitry Andric       cmd->addr = dot;
8540b57cec5SDimitry Andric       assignSymbol(cmd, true);
8550b57cec5SDimitry Andric       cmd->size = dot - cmd->addr;
8560b57cec5SDimitry Andric       continue;
8570b57cec5SDimitry Andric     }
8580b57cec5SDimitry Andric 
8590b57cec5SDimitry Andric     // Handle BYTE(), SHORT(), LONG(), or QUAD().
8600b57cec5SDimitry Andric     if (auto *cmd = dyn_cast<ByteCommand>(base)) {
8610b57cec5SDimitry Andric       cmd->offset = dot - ctx->outSec->addr;
8620b57cec5SDimitry Andric       dot += cmd->size;
8630b57cec5SDimitry Andric       expandOutputSection(cmd->size);
8640b57cec5SDimitry Andric       continue;
8650b57cec5SDimitry Andric     }
8660b57cec5SDimitry Andric 
8670b57cec5SDimitry Andric     // Handle a single input section description command.
8680b57cec5SDimitry Andric     // It calculates and assigns the offsets for each section and also
8690b57cec5SDimitry Andric     // updates the output section size.
8700b57cec5SDimitry Andric     for (InputSection *sec : cast<InputSectionDescription>(base)->sections)
8710b57cec5SDimitry Andric       output(sec);
8720b57cec5SDimitry Andric   }
8730b57cec5SDimitry Andric }
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric static bool isDiscardable(OutputSection &sec) {
8760b57cec5SDimitry Andric   if (sec.name == "/DISCARD/")
8770b57cec5SDimitry Andric     return true;
8780b57cec5SDimitry Andric 
8790b57cec5SDimitry Andric   // We do not remove empty sections that are explicitly
8800b57cec5SDimitry Andric   // assigned to any segment.
8810b57cec5SDimitry Andric   if (!sec.phdrs.empty())
8820b57cec5SDimitry Andric     return false;
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   // We do not want to remove OutputSections with expressions that reference
8850b57cec5SDimitry Andric   // symbols even if the OutputSection is empty. We want to ensure that the
8860b57cec5SDimitry Andric   // expressions can be evaluated and report an error if they cannot.
8870b57cec5SDimitry Andric   if (sec.expressionsUseSymbols)
8880b57cec5SDimitry Andric     return false;
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric   // OutputSections may be referenced by name in ADDR and LOADADDR expressions,
8910b57cec5SDimitry Andric   // as an empty Section can has a valid VMA and LMA we keep the OutputSection
8920b57cec5SDimitry Andric   // to maintain the integrity of the other Expression.
8930b57cec5SDimitry Andric   if (sec.usedInExpression)
8940b57cec5SDimitry Andric     return false;
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric   for (BaseCommand *base : sec.sectionCommands) {
8970b57cec5SDimitry Andric     if (auto cmd = dyn_cast<SymbolAssignment>(base))
8980b57cec5SDimitry Andric       // Don't create empty output sections just for unreferenced PROVIDE
8990b57cec5SDimitry Andric       // symbols.
9000b57cec5SDimitry Andric       if (cmd->name != "." && !cmd->sym)
9010b57cec5SDimitry Andric         continue;
9020b57cec5SDimitry Andric 
9030b57cec5SDimitry Andric     if (!isa<InputSectionDescription>(*base))
9040b57cec5SDimitry Andric       return false;
9050b57cec5SDimitry Andric   }
9060b57cec5SDimitry Andric   return true;
9070b57cec5SDimitry Andric }
9080b57cec5SDimitry Andric 
9090b57cec5SDimitry Andric void LinkerScript::adjustSectionsBeforeSorting() {
9100b57cec5SDimitry Andric   // If the output section contains only symbol assignments, create a
9110b57cec5SDimitry Andric   // corresponding output section. The issue is what to do with linker script
9120b57cec5SDimitry Andric   // like ".foo : { symbol = 42; }". One option would be to convert it to
9130b57cec5SDimitry Andric   // "symbol = 42;". That is, move the symbol out of the empty section
9140b57cec5SDimitry Andric   // description. That seems to be what bfd does for this simple case. The
9150b57cec5SDimitry Andric   // problem is that this is not completely general. bfd will give up and
9160b57cec5SDimitry Andric   // create a dummy section too if there is a ". = . + 1" inside the section
9170b57cec5SDimitry Andric   // for example.
9180b57cec5SDimitry Andric   // Given that we want to create the section, we have to worry what impact
9190b57cec5SDimitry Andric   // it will have on the link. For example, if we just create a section with
9200b57cec5SDimitry Andric   // 0 for flags, it would change which PT_LOADs are created.
9210b57cec5SDimitry Andric   // We could remember that particular section is dummy and ignore it in
9220b57cec5SDimitry Andric   // other parts of the linker, but unfortunately there are quite a few places
9230b57cec5SDimitry Andric   // that would need to change:
9240b57cec5SDimitry Andric   //   * The program header creation.
9250b57cec5SDimitry Andric   //   * The orphan section placement.
9260b57cec5SDimitry Andric   //   * The address assignment.
9270b57cec5SDimitry Andric   // The other option is to pick flags that minimize the impact the section
9280b57cec5SDimitry Andric   // will have on the rest of the linker. That is why we copy the flags from
9290b57cec5SDimitry Andric   // the previous sections. Only a few flags are needed to keep the impact low.
9300b57cec5SDimitry Andric   uint64_t flags = SHF_ALLOC;
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric   for (BaseCommand *&cmd : sectionCommands) {
9330b57cec5SDimitry Andric     auto *sec = dyn_cast<OutputSection>(cmd);
9340b57cec5SDimitry Andric     if (!sec)
9350b57cec5SDimitry Andric       continue;
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric     // Handle align (e.g. ".foo : ALIGN(16) { ... }").
9380b57cec5SDimitry Andric     if (sec->alignExpr)
9390b57cec5SDimitry Andric       sec->alignment =
9400b57cec5SDimitry Andric           std::max<uint32_t>(sec->alignment, sec->alignExpr().getValue());
9410b57cec5SDimitry Andric 
9420b57cec5SDimitry Andric     // The input section might have been removed (if it was an empty synthetic
9430b57cec5SDimitry Andric     // section), but we at least know the flags.
9440b57cec5SDimitry Andric     if (sec->hasInputSections)
9450b57cec5SDimitry Andric       flags = sec->flags;
9460b57cec5SDimitry Andric 
9470b57cec5SDimitry Andric     // We do not want to keep any special flags for output section
9480b57cec5SDimitry Andric     // in case it is empty.
9490b57cec5SDimitry Andric     bool isEmpty = getInputSections(sec).empty();
9500b57cec5SDimitry Andric     if (isEmpty)
9510b57cec5SDimitry Andric       sec->flags = flags & ((sec->nonAlloc ? 0 : (uint64_t)SHF_ALLOC) |
9520b57cec5SDimitry Andric                             SHF_WRITE | SHF_EXECINSTR);
9530b57cec5SDimitry Andric 
9540b57cec5SDimitry Andric     if (isEmpty && isDiscardable(*sec)) {
9550b57cec5SDimitry Andric       sec->markDead();
9560b57cec5SDimitry Andric       cmd = nullptr;
9570b57cec5SDimitry Andric     }
9580b57cec5SDimitry Andric   }
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   // It is common practice to use very generic linker scripts. So for any
9610b57cec5SDimitry Andric   // given run some of the output sections in the script will be empty.
9620b57cec5SDimitry Andric   // We could create corresponding empty output sections, but that would
9630b57cec5SDimitry Andric   // clutter the output.
9640b57cec5SDimitry Andric   // We instead remove trivially empty sections. The bfd linker seems even
9650b57cec5SDimitry Andric   // more aggressive at removing them.
9660b57cec5SDimitry Andric   llvm::erase_if(sectionCommands, [&](BaseCommand *base) { return !base; });
9670b57cec5SDimitry Andric }
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric void LinkerScript::adjustSectionsAfterSorting() {
9700b57cec5SDimitry Andric   // Try and find an appropriate memory region to assign offsets in.
9710b57cec5SDimitry Andric   for (BaseCommand *base : sectionCommands) {
9720b57cec5SDimitry Andric     if (auto *sec = dyn_cast<OutputSection>(base)) {
9730b57cec5SDimitry Andric       if (!sec->lmaRegionName.empty()) {
9740b57cec5SDimitry Andric         if (MemoryRegion *m = memoryRegions.lookup(sec->lmaRegionName))
9750b57cec5SDimitry Andric           sec->lmaRegion = m;
9760b57cec5SDimitry Andric         else
9770b57cec5SDimitry Andric           error("memory region '" + sec->lmaRegionName + "' not declared");
9780b57cec5SDimitry Andric       }
9790b57cec5SDimitry Andric       sec->memRegion = findMemoryRegion(sec);
9800b57cec5SDimitry Andric     }
9810b57cec5SDimitry Andric   }
9820b57cec5SDimitry Andric 
9830b57cec5SDimitry Andric   // If output section command doesn't specify any segments,
9840b57cec5SDimitry Andric   // and we haven't previously assigned any section to segment,
9850b57cec5SDimitry Andric   // then we simply assign section to the very first load segment.
9860b57cec5SDimitry Andric   // Below is an example of such linker script:
9870b57cec5SDimitry Andric   // PHDRS { seg PT_LOAD; }
9880b57cec5SDimitry Andric   // SECTIONS { .aaa : { *(.aaa) } }
9890b57cec5SDimitry Andric   std::vector<StringRef> defPhdrs;
9900b57cec5SDimitry Andric   auto firstPtLoad = llvm::find_if(phdrsCommands, [](const PhdrsCommand &cmd) {
9910b57cec5SDimitry Andric     return cmd.type == PT_LOAD;
9920b57cec5SDimitry Andric   });
9930b57cec5SDimitry Andric   if (firstPtLoad != phdrsCommands.end())
9940b57cec5SDimitry Andric     defPhdrs.push_back(firstPtLoad->name);
9950b57cec5SDimitry Andric 
9960b57cec5SDimitry Andric   // Walk the commands and propagate the program headers to commands that don't
9970b57cec5SDimitry Andric   // explicitly specify them.
9980b57cec5SDimitry Andric   for (BaseCommand *base : sectionCommands) {
9990b57cec5SDimitry Andric     auto *sec = dyn_cast<OutputSection>(base);
10000b57cec5SDimitry Andric     if (!sec)
10010b57cec5SDimitry Andric       continue;
10020b57cec5SDimitry Andric 
10030b57cec5SDimitry Andric     if (sec->phdrs.empty()) {
10040b57cec5SDimitry Andric       // To match the bfd linker script behaviour, only propagate program
10050b57cec5SDimitry Andric       // headers to sections that are allocated.
10060b57cec5SDimitry Andric       if (sec->flags & SHF_ALLOC)
10070b57cec5SDimitry Andric         sec->phdrs = defPhdrs;
10080b57cec5SDimitry Andric     } else {
10090b57cec5SDimitry Andric       defPhdrs = sec->phdrs;
10100b57cec5SDimitry Andric     }
10110b57cec5SDimitry Andric   }
10120b57cec5SDimitry Andric }
10130b57cec5SDimitry Andric 
10140b57cec5SDimitry Andric static uint64_t computeBase(uint64_t min, bool allocateHeaders) {
10150b57cec5SDimitry Andric   // If there is no SECTIONS or if the linkerscript is explicit about program
10160b57cec5SDimitry Andric   // headers, do our best to allocate them.
10170b57cec5SDimitry Andric   if (!script->hasSectionsCommand || allocateHeaders)
10180b57cec5SDimitry Andric     return 0;
10190b57cec5SDimitry Andric   // Otherwise only allocate program headers if that would not add a page.
10200b57cec5SDimitry Andric   return alignDown(min, config->maxPageSize);
10210b57cec5SDimitry Andric }
10220b57cec5SDimitry Andric 
102385868e8aSDimitry Andric // When the SECTIONS command is used, try to find an address for the file and
102485868e8aSDimitry Andric // program headers output sections, which can be added to the first PT_LOAD
102585868e8aSDimitry Andric // segment when program headers are created.
10260b57cec5SDimitry Andric //
102785868e8aSDimitry Andric // We check if the headers fit below the first allocated section. If there isn't
102885868e8aSDimitry Andric // enough space for these sections, we'll remove them from the PT_LOAD segment,
102985868e8aSDimitry Andric // and we'll also remove the PT_PHDR segment.
10300b57cec5SDimitry Andric void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &phdrs) {
10310b57cec5SDimitry Andric   uint64_t min = std::numeric_limits<uint64_t>::max();
10320b57cec5SDimitry Andric   for (OutputSection *sec : outputSections)
10330b57cec5SDimitry Andric     if (sec->flags & SHF_ALLOC)
10340b57cec5SDimitry Andric       min = std::min<uint64_t>(min, sec->addr);
10350b57cec5SDimitry Andric 
10360b57cec5SDimitry Andric   auto it = llvm::find_if(
10370b57cec5SDimitry Andric       phdrs, [](const PhdrEntry *e) { return e->p_type == PT_LOAD; });
10380b57cec5SDimitry Andric   if (it == phdrs.end())
10390b57cec5SDimitry Andric     return;
10400b57cec5SDimitry Andric   PhdrEntry *firstPTLoad = *it;
10410b57cec5SDimitry Andric 
10420b57cec5SDimitry Andric   bool hasExplicitHeaders =
10430b57cec5SDimitry Andric       llvm::any_of(phdrsCommands, [](const PhdrsCommand &cmd) {
10440b57cec5SDimitry Andric         return cmd.hasPhdrs || cmd.hasFilehdr;
10450b57cec5SDimitry Andric       });
10460b57cec5SDimitry Andric   bool paged = !config->omagic && !config->nmagic;
10470b57cec5SDimitry Andric   uint64_t headerSize = getHeaderSize();
10480b57cec5SDimitry Andric   if ((paged || hasExplicitHeaders) &&
10490b57cec5SDimitry Andric       headerSize <= min - computeBase(min, hasExplicitHeaders)) {
10500b57cec5SDimitry Andric     min = alignDown(min - headerSize, config->maxPageSize);
10510b57cec5SDimitry Andric     Out::elfHeader->addr = min;
10520b57cec5SDimitry Andric     Out::programHeaders->addr = min + Out::elfHeader->size;
10530b57cec5SDimitry Andric     return;
10540b57cec5SDimitry Andric   }
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric   // Error if we were explicitly asked to allocate headers.
10570b57cec5SDimitry Andric   if (hasExplicitHeaders)
10580b57cec5SDimitry Andric     error("could not allocate headers");
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric   Out::elfHeader->ptLoad = nullptr;
10610b57cec5SDimitry Andric   Out::programHeaders->ptLoad = nullptr;
10620b57cec5SDimitry Andric   firstPTLoad->firstSec = findFirstSection(firstPTLoad);
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   llvm::erase_if(phdrs,
10650b57cec5SDimitry Andric                  [](const PhdrEntry *e) { return e->p_type == PT_PHDR; });
10660b57cec5SDimitry Andric }
10670b57cec5SDimitry Andric 
10680b57cec5SDimitry Andric LinkerScript::AddressState::AddressState() {
10690b57cec5SDimitry Andric   for (auto &mri : script->memoryRegions) {
10700b57cec5SDimitry Andric     MemoryRegion *mr = mri.second;
10710b57cec5SDimitry Andric     mr->curPos = mr->origin;
10720b57cec5SDimitry Andric   }
10730b57cec5SDimitry Andric }
10740b57cec5SDimitry Andric 
10750b57cec5SDimitry Andric // Here we assign addresses as instructed by linker script SECTIONS
10760b57cec5SDimitry Andric // sub-commands. Doing that allows us to use final VA values, so here
10770b57cec5SDimitry Andric // we also handle rest commands like symbol assignments and ASSERTs.
107885868e8aSDimitry Andric // Returns a symbol that has changed its section or value, or nullptr if no
107985868e8aSDimitry Andric // symbol has changed.
108085868e8aSDimitry Andric const Defined *LinkerScript::assignAddresses() {
108185868e8aSDimitry Andric   if (script->hasSectionsCommand) {
108285868e8aSDimitry Andric     // With a linker script, assignment of addresses to headers is covered by
108385868e8aSDimitry Andric     // allocateHeaders().
108485868e8aSDimitry Andric     dot = config->imageBase.getValueOr(0);
108585868e8aSDimitry Andric   } else {
108685868e8aSDimitry Andric     // Assign addresses to headers right now.
108785868e8aSDimitry Andric     dot = target->getImageBase();
108885868e8aSDimitry Andric     Out::elfHeader->addr = dot;
108985868e8aSDimitry Andric     Out::programHeaders->addr = dot + Out::elfHeader->size;
109085868e8aSDimitry Andric     dot += getHeaderSize();
109185868e8aSDimitry Andric   }
10920b57cec5SDimitry Andric 
109385868e8aSDimitry Andric   auto deleter = std::make_unique<AddressState>();
10940b57cec5SDimitry Andric   ctx = deleter.get();
10950b57cec5SDimitry Andric   errorOnMissingSection = true;
10960b57cec5SDimitry Andric   switchTo(aether);
10970b57cec5SDimitry Andric 
109885868e8aSDimitry Andric   SymbolAssignmentMap oldValues = getSymbolAssignmentValues(sectionCommands);
10990b57cec5SDimitry Andric   for (BaseCommand *base : sectionCommands) {
11000b57cec5SDimitry Andric     if (auto *cmd = dyn_cast<SymbolAssignment>(base)) {
11010b57cec5SDimitry Andric       cmd->addr = dot;
11020b57cec5SDimitry Andric       assignSymbol(cmd, false);
11030b57cec5SDimitry Andric       cmd->size = dot - cmd->addr;
11040b57cec5SDimitry Andric       continue;
11050b57cec5SDimitry Andric     }
11060b57cec5SDimitry Andric     assignOffsets(cast<OutputSection>(base));
11070b57cec5SDimitry Andric   }
110885868e8aSDimitry Andric 
11090b57cec5SDimitry Andric   ctx = nullptr;
111085868e8aSDimitry Andric   return getChangedSymbolAssignment(oldValues);
11110b57cec5SDimitry Andric }
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric // Creates program headers as instructed by PHDRS linker script command.
11140b57cec5SDimitry Andric std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
11150b57cec5SDimitry Andric   std::vector<PhdrEntry *> ret;
11160b57cec5SDimitry Andric 
11170b57cec5SDimitry Andric   // Process PHDRS and FILEHDR keywords because they are not
11180b57cec5SDimitry Andric   // real output sections and cannot be added in the following loop.
11190b57cec5SDimitry Andric   for (const PhdrsCommand &cmd : phdrsCommands) {
11200b57cec5SDimitry Andric     PhdrEntry *phdr = make<PhdrEntry>(cmd.type, cmd.flags ? *cmd.flags : PF_R);
11210b57cec5SDimitry Andric 
11220b57cec5SDimitry Andric     if (cmd.hasFilehdr)
11230b57cec5SDimitry Andric       phdr->add(Out::elfHeader);
11240b57cec5SDimitry Andric     if (cmd.hasPhdrs)
11250b57cec5SDimitry Andric       phdr->add(Out::programHeaders);
11260b57cec5SDimitry Andric 
11270b57cec5SDimitry Andric     if (cmd.lmaExpr) {
11280b57cec5SDimitry Andric       phdr->p_paddr = cmd.lmaExpr().getValue();
11290b57cec5SDimitry Andric       phdr->hasLMA = true;
11300b57cec5SDimitry Andric     }
11310b57cec5SDimitry Andric     ret.push_back(phdr);
11320b57cec5SDimitry Andric   }
11330b57cec5SDimitry Andric 
11340b57cec5SDimitry Andric   // Add output sections to program headers.
11350b57cec5SDimitry Andric   for (OutputSection *sec : outputSections) {
11360b57cec5SDimitry Andric     // Assign headers specified by linker script
11370b57cec5SDimitry Andric     for (size_t id : getPhdrIndices(sec)) {
11380b57cec5SDimitry Andric       ret[id]->add(sec);
11390b57cec5SDimitry Andric       if (!phdrsCommands[id].flags.hasValue())
11400b57cec5SDimitry Andric         ret[id]->p_flags |= sec->getPhdrFlags();
11410b57cec5SDimitry Andric     }
11420b57cec5SDimitry Andric   }
11430b57cec5SDimitry Andric   return ret;
11440b57cec5SDimitry Andric }
11450b57cec5SDimitry Andric 
11460b57cec5SDimitry Andric // Returns true if we should emit an .interp section.
11470b57cec5SDimitry Andric //
11480b57cec5SDimitry Andric // We usually do. But if PHDRS commands are given, and
11490b57cec5SDimitry Andric // no PT_INTERP is there, there's no place to emit an
11500b57cec5SDimitry Andric // .interp, so we don't do that in that case.
11510b57cec5SDimitry Andric bool LinkerScript::needsInterpSection() {
11520b57cec5SDimitry Andric   if (phdrsCommands.empty())
11530b57cec5SDimitry Andric     return true;
11540b57cec5SDimitry Andric   for (PhdrsCommand &cmd : phdrsCommands)
11550b57cec5SDimitry Andric     if (cmd.type == PT_INTERP)
11560b57cec5SDimitry Andric       return true;
11570b57cec5SDimitry Andric   return false;
11580b57cec5SDimitry Andric }
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric ExprValue LinkerScript::getSymbolValue(StringRef name, const Twine &loc) {
11610b57cec5SDimitry Andric   if (name == ".") {
11620b57cec5SDimitry Andric     if (ctx)
11630b57cec5SDimitry Andric       return {ctx->outSec, false, dot - ctx->outSec->addr, loc};
11640b57cec5SDimitry Andric     error(loc + ": unable to get location counter value");
11650b57cec5SDimitry Andric     return 0;
11660b57cec5SDimitry Andric   }
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric   if (Symbol *sym = symtab->find(name)) {
11690b57cec5SDimitry Andric     if (auto *ds = dyn_cast<Defined>(sym))
11700b57cec5SDimitry Andric       return {ds->section, false, ds->value, loc};
11710b57cec5SDimitry Andric     if (isa<SharedSymbol>(sym))
11720b57cec5SDimitry Andric       if (!errorOnMissingSection)
11730b57cec5SDimitry Andric         return {nullptr, false, 0, loc};
11740b57cec5SDimitry Andric   }
11750b57cec5SDimitry Andric 
11760b57cec5SDimitry Andric   error(loc + ": symbol not found: " + name);
11770b57cec5SDimitry Andric   return 0;
11780b57cec5SDimitry Andric }
11790b57cec5SDimitry Andric 
11800b57cec5SDimitry Andric // Returns the index of the segment named Name.
11810b57cec5SDimitry Andric static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> vec,
11820b57cec5SDimitry Andric                                      StringRef name) {
11830b57cec5SDimitry Andric   for (size_t i = 0; i < vec.size(); ++i)
11840b57cec5SDimitry Andric     if (vec[i].name == name)
11850b57cec5SDimitry Andric       return i;
11860b57cec5SDimitry Andric   return None;
11870b57cec5SDimitry Andric }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric // Returns indices of ELF headers containing specific section. Each index is a
11900b57cec5SDimitry Andric // zero based number of ELF header listed within PHDRS {} script block.
11910b57cec5SDimitry Andric std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *cmd) {
11920b57cec5SDimitry Andric   std::vector<size_t> ret;
11930b57cec5SDimitry Andric 
11940b57cec5SDimitry Andric   for (StringRef s : cmd->phdrs) {
11950b57cec5SDimitry Andric     if (Optional<size_t> idx = getPhdrIndex(phdrsCommands, s))
11960b57cec5SDimitry Andric       ret.push_back(*idx);
11970b57cec5SDimitry Andric     else if (s != "NONE")
11980b57cec5SDimitry Andric       error(cmd->location + ": section header '" + s +
11990b57cec5SDimitry Andric             "' is not listed in PHDRS");
12000b57cec5SDimitry Andric   }
12010b57cec5SDimitry Andric   return ret;
12020b57cec5SDimitry Andric }
120385868e8aSDimitry Andric 
120485868e8aSDimitry Andric } // namespace elf
120585868e8aSDimitry Andric } // namespace lld
1206