1f7c5fbb1SRui Ueyama //===- LinkerScript.cpp ---------------------------------------------------===// 2f7c5fbb1SRui Ueyama // 3f7c5fbb1SRui Ueyama // The LLVM Linker 4f7c5fbb1SRui Ueyama // 5f7c5fbb1SRui Ueyama // This file is distributed under the University of Illinois Open Source 6f7c5fbb1SRui Ueyama // License. See LICENSE.TXT for details. 7f7c5fbb1SRui Ueyama // 8f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===// 9f7c5fbb1SRui Ueyama // 10f7c5fbb1SRui Ueyama // This file contains the parser/evaluator of the linker script. 11f7c5fbb1SRui Ueyama // 12f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===// 13f7c5fbb1SRui Ueyama 14717677afSRui Ueyama #include "LinkerScript.h" 15f7c5fbb1SRui Ueyama #include "Config.h" 161ebc8ed7SRui Ueyama #include "InputSection.h" 179381eb10SRui Ueyama #include "Memory.h" 18652852c5SGeorge Rimar #include "OutputSections.h" 1993c9af42SRui Ueyama #include "Strings.h" 20f7c5fbb1SRui Ueyama #include "SymbolTable.h" 2155518e7dSRui Ueyama #include "Symbols.h" 223fb5a6dcSGeorge Rimar #include "SyntheticSections.h" 2355b169bfSRafael Espindola #include "Target.h" 2455b169bfSRafael Espindola #include "Threads.h" 25bbe38602SEugene Leviant #include "Writer.h" 2622886a28SEugene Zelenko #include "llvm/ADT/STLExtras.h" 2722886a28SEugene Zelenko #include "llvm/ADT/StringRef.h" 28264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h" 2922886a28SEugene Zelenko #include "llvm/Support/Casting.h" 3022886a28SEugene Zelenko #include "llvm/Support/Endian.h" 3122886a28SEugene Zelenko #include "llvm/Support/ErrorHandling.h" 32f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h" 33f03f3cc1SRui Ueyama #include "llvm/Support/Path.h" 3422886a28SEugene Zelenko #include <algorithm> 3522886a28SEugene Zelenko #include <cassert> 3622886a28SEugene Zelenko #include <cstddef> 3722886a28SEugene Zelenko #include <cstdint> 3822886a28SEugene Zelenko #include <iterator> 3922886a28SEugene Zelenko #include <limits> 4022886a28SEugene Zelenko #include <string> 4122886a28SEugene Zelenko #include <vector> 42f7c5fbb1SRui Ueyama 43f7c5fbb1SRui Ueyama using namespace llvm; 44652852c5SGeorge Rimar using namespace llvm::ELF; 451ebc8ed7SRui Ueyama using namespace llvm::object; 46e38cbab5SGeorge Rimar using namespace llvm::support::endian; 47f7c5fbb1SRui Ueyama using namespace lld; 48e0df00b9SRafael Espindola using namespace lld::elf; 49f7c5fbb1SRui Ueyama 50a34da938SRui Ueyama LinkerScript *elf::Script; 51a34da938SRui Ueyama 525d0ea70aSGeorge Rimar static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) { 535d0ea70aSGeorge Rimar if (OutputSection *OS = InputSec->getOutputSection()) 545d0ea70aSGeorge Rimar return OS->Addr; 555d0ea70aSGeorge Rimar error(Loc + ": unable to evaluate expression: input section " + 565d0ea70aSGeorge Rimar InputSec->Name + " has no output section assigned"); 575d0ea70aSGeorge Rimar return 0; 58608cf670SGeorge Rimar } 595d0ea70aSGeorge Rimar 605d0ea70aSGeorge Rimar uint64_t ExprValue::getValue() const { 615d0ea70aSGeorge Rimar if (Sec) 625d0ea70aSGeorge Rimar return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc), 635d0ea70aSGeorge Rimar Alignment); 643c6de1a6SPetr Hosek return alignTo(Val, Alignment); 6572dc195dSRafael Espindola } 6672dc195dSRafael Espindola 677ba5f47eSRafael Espindola uint64_t ExprValue::getSecAddr() const { 687ba5f47eSRafael Espindola if (Sec) 695d0ea70aSGeorge Rimar return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc); 707ba5f47eSRafael Espindola return 0; 717ba5f47eSRafael Espindola } 727ba5f47eSRafael Espindola 73a6acd23cSRafael Espindola uint64_t ExprValue::getSectionOffset() const { 748b250344SRafael Espindola // If the alignment is trivial, we don't have to compute the full 758b250344SRafael Espindola // value to know the offset. This allows this function to succeed in 768b250344SRafael Espindola // cases where the output section is not yet known. 778b250344SRafael Espindola if (Alignment == 1) 788b250344SRafael Espindola return Val; 79a6acd23cSRafael Espindola return getValue() - getSecAddr(); 80a6acd23cSRafael Espindola } 81a6acd23cSRafael Espindola 828c022ca7SRafael Espindola OutputSection *LinkerScript::createOutputSection(StringRef Name, 838c022ca7SRafael Espindola StringRef Location) { 848c022ca7SRafael Espindola OutputSection *&SecRef = NameToOutputSection[Name]; 858c022ca7SRafael Espindola OutputSection *Sec; 868c022ca7SRafael Espindola if (SecRef && SecRef->Location.empty()) { 8705c4f67cSRafael Espindola // There was a forward reference. 888c022ca7SRafael Espindola Sec = SecRef; 8905c4f67cSRafael Espindola } else { 908c022ca7SRafael Espindola Sec = make<OutputSection>(Name, SHT_PROGBITS, 0); 918c022ca7SRafael Espindola if (!SecRef) 928c022ca7SRafael Espindola SecRef = Sec; 9305c4f67cSRafael Espindola } 948c022ca7SRafael Espindola Sec->Location = Location; 958c022ca7SRafael Espindola return Sec; 96851dc1e8SGeorge Rimar } 97851dc1e8SGeorge Rimar 988c022ca7SRafael Espindola OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) { 998c022ca7SRafael Espindola OutputSection *&CmdRef = NameToOutputSection[Name]; 10005c4f67cSRafael Espindola if (!CmdRef) 1018c022ca7SRafael Espindola CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0); 10205c4f67cSRafael Espindola return CmdRef; 103d83ce1b4SGeorge Rimar } 104d83ce1b4SGeorge Rimar 105b8dd23f5SRui Ueyama void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) { 10672dc195dSRafael Espindola uint64_t Val = E().getValue(); 1078c804d97SGeorge Rimar if (Val < Dot && InSec) 1082ee2d2dcSGeorge Rimar error(Loc + ": unable to move location counter backward for: " + 109906e9a18SPeter Smith CurAddressState->OutSec->Name); 1104cd7352cSRafael Espindola Dot = Val; 11118d19687SRui Ueyama 1124cd7352cSRafael Espindola // Update to location counter means update to section size. 1134cd7352cSRafael Espindola if (InSec) 114906e9a18SPeter Smith CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr; 115679828ffSRafael Espindola } 116679828ffSRafael Espindola 11718d19687SRui Ueyama // This function is called from processCommands, while we are 11818d19687SRui Ueyama // fixing the output section layout. 119b8dd23f5SRui Ueyama void LinkerScript::addSymbol(SymbolAssignment *Cmd) { 1201602421cSRui Ueyama if (Cmd->Name == ".") 1218f1f3c40SMeador Inge return; 1228f1f3c40SMeador Inge 1238f1f3c40SMeador Inge // If a symbol was in PROVIDE(), we need to define it only when 1248f1f3c40SMeador Inge // it is a referenced undefined symbol. 125244ef981SRafael Espindola SymbolBody *B = Symtab->find(Cmd->Name); 1268f1f3c40SMeador Inge if (Cmd->Provide && (!B || B->isDefined())) 1278f1f3c40SMeador Inge return; 1288f1f3c40SMeador Inge 12918d19687SRui Ueyama // Define a symbol. 13018d19687SRui Ueyama Symbol *Sym; 13118d19687SRui Ueyama uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT; 13218d19687SRui Ueyama std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility, 13318d19687SRui Ueyama /*CanOmitFromDynSym*/ false, 13418d19687SRui Ueyama /*File*/ nullptr); 13518d19687SRui Ueyama Sym->Binding = STB_GLOBAL; 13618d19687SRui Ueyama ExprValue Value = Cmd->Expression(); 13718d19687SRui Ueyama SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec; 13818d19687SRui Ueyama 13918d19687SRui Ueyama // When this function is called, section addresses have not been 14018d19687SRui Ueyama // fixed yet. So, we may or may not know the value of the RHS 14118d19687SRui Ueyama // expression. 14218d19687SRui Ueyama // 14318d19687SRui Ueyama // For example, if an expression is `x = 42`, we know x is always 42. 14418d19687SRui Ueyama // However, if an expression is `x = .`, there's no way to know its 14518d19687SRui Ueyama // value at the moment. 14618d19687SRui Ueyama // 14718d19687SRui Ueyama // We want to set symbol values early if we can. This allows us to 14818d19687SRui Ueyama // use symbols as variables in linker scripts. Doing so allows us to 14918d19687SRui Ueyama // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`. 15018d19687SRui Ueyama uint64_t SymValue = Value.Sec ? 0 : Value.getValue(); 15118d19687SRui Ueyama 15218d19687SRui Ueyama replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false, 15318d19687SRui Ueyama Visibility, STT_NOTYPE, SymValue, 0, Sec); 15418d19687SRui Ueyama Cmd->Sym = cast<DefinedRegular>(Sym->body()); 15518d19687SRui Ueyama } 15618d19687SRui Ueyama 15718d19687SRui Ueyama // This function is called from assignAddresses, while we are 15818d19687SRui Ueyama // fixing the output section addresses. This function is supposed 15918d19687SRui Ueyama // to set the final value for a given symbol assignment. 16018d19687SRui Ueyama void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) { 16118d19687SRui Ueyama if (Cmd->Name == ".") { 16218d19687SRui Ueyama setDot(Cmd->Expression, Cmd->Location, InSec); 16318d19687SRui Ueyama return; 16418d19687SRui Ueyama } 16518d19687SRui Ueyama 16618d19687SRui Ueyama if (!Cmd->Sym) 16718d19687SRui Ueyama return; 16818d19687SRui Ueyama 16918d19687SRui Ueyama ExprValue V = Cmd->Expression(); 17018d19687SRui Ueyama if (V.isAbsolute()) { 17118d19687SRui Ueyama Cmd->Sym->Section = nullptr; 17218d19687SRui Ueyama Cmd->Sym->Value = V.getValue(); 17318d19687SRui Ueyama } else { 17418d19687SRui Ueyama Cmd->Sym->Section = V.Sec; 17518d19687SRui Ueyama Cmd->Sym->Value = V.getSectionOffset(); 17618d19687SRui Ueyama } 177ceabe80eSEugene Leviant } 178ceabe80eSEugene Leviant 179076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) { 180076fe157SGeorge Rimar return C->Kind == AssignmentKind; 181076fe157SGeorge Rimar } 182076fe157SGeorge Rimar 183eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) { 184eea3114fSGeorge Rimar return C->Kind == InputSectionKind; 185eea3114fSGeorge Rimar } 186eea3114fSGeorge Rimar 187eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) { 188eefa758eSGeorge Rimar return C->Kind == AssertKind; 189eefa758eSGeorge Rimar } 190eefa758eSGeorge Rimar 191e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) { 192e38cbab5SGeorge Rimar return C->Kind == BytesDataKind; 193e38cbab5SGeorge Rimar } 194e38cbab5SGeorge Rimar 1951e30f07cSDmitry Mikulin static std::string filename(InputFile *File) { 1961e30f07cSDmitry Mikulin if (!File) 197e0be2901SRui Ueyama return ""; 1981e30f07cSDmitry Mikulin if (File->ArchiveName.empty()) 1991e30f07cSDmitry Mikulin return File->getName(); 2001e30f07cSDmitry Mikulin return (File->ArchiveName + "(" + File->getName() + ")").str(); 201e0be2901SRui Ueyama } 202e0be2901SRui Ueyama 203b8dd23f5SRui Ueyama bool LinkerScript::shouldKeep(InputSectionBase *S) { 2041e30f07cSDmitry Mikulin std::string Filename = filename(S->File); 2057f1c266eSRui Ueyama for (InputSectionDescription *ID : KeptSections) 206f300ca21SDmitry Mikulin if (ID->FilePat.match(Filename)) 207cf43f179SEugene Leviant for (SectionPattern &P : ID->SectionPatterns) 208f91282e1SRui Ueyama if (P.SectionPat.match(S->Name)) 209eea3114fSGeorge Rimar return true; 210eea3114fSGeorge Rimar return false; 211eea3114fSGeorge Rimar } 212eea3114fSGeorge Rimar 213ea93fe00SRui Ueyama // A helper function for the SORT() command. 214c404d50dSRafael Espindola static std::function<bool(InputSectionBase *, InputSectionBase *)> 215be394db3SGeorge Rimar getComparator(SortSectionPolicy K) { 216be394db3SGeorge Rimar switch (K) { 217be394db3SGeorge Rimar case SortSectionPolicy::Alignment: 218ea93fe00SRui Ueyama return [](InputSectionBase *A, InputSectionBase *B) { 219ea93fe00SRui Ueyama // ">" is not a mistake. Sections with larger alignments are placed 220ea93fe00SRui Ueyama // before sections with smaller alignments in order to reduce the 221ea93fe00SRui Ueyama // amount of padding necessary. This is compatible with GNU. 222ea93fe00SRui Ueyama return A->Alignment > B->Alignment; 223ea93fe00SRui Ueyama }; 224be394db3SGeorge Rimar case SortSectionPolicy::Name: 225ea93fe00SRui Ueyama return [](InputSectionBase *A, InputSectionBase *B) { 226ea93fe00SRui Ueyama return A->Name < B->Name; 227ea93fe00SRui Ueyama }; 228be394db3SGeorge Rimar case SortSectionPolicy::Priority: 229ea93fe00SRui Ueyama return [](InputSectionBase *A, InputSectionBase *B) { 230ea93fe00SRui Ueyama return getPriority(A->Name) < getPriority(B->Name); 231ea93fe00SRui Ueyama }; 232be394db3SGeorge Rimar default: 233be394db3SGeorge Rimar llvm_unreachable("unknown sort policy"); 234be394db3SGeorge Rimar } 235742c3836SRui Ueyama } 2360702c4e8SGeorge Rimar 237ea93fe00SRui Ueyama // A helper function for the SORT() command. 238b4c9b81aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase *> Sections, 23906ae6836SGeorge Rimar ConstraintKind Kind) { 2408f66df92SGeorge Rimar if (Kind == ConstraintKind::NoConstraint) 2418f66df92SGeorge Rimar return true; 2422c7171bfSRui Ueyama 2432c7171bfSRui Ueyama bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) { 2442c7171bfSRui Ueyama return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE; 24506ae6836SGeorge Rimar }); 2462c7171bfSRui Ueyama 247e746e52cSRafael Espindola return (IsRW && Kind == ConstraintKind::ReadWrite) || 248e746e52cSRafael Espindola (!IsRW && Kind == ConstraintKind::ReadOnly); 24906ae6836SGeorge Rimar } 25006ae6836SGeorge Rimar 2516a1aa8d9SRafael Espindola static void sortSections(InputSection **Begin, InputSection **End, 252ee924709SRui Ueyama SortSectionPolicy K) { 253ee924709SRui Ueyama if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None) 25407171f21SGeorge Rimar std::stable_sort(Begin, End, getComparator(K)); 255ee924709SRui Ueyama } 256ee924709SRui Ueyama 257d6bcde38SGeorge Rimar static void sortBySymbolOrder(InputSection **Begin, InputSection **End) { 258d6bcde38SGeorge Rimar if (Config->SymbolOrderingFile.empty()) 259d6bcde38SGeorge Rimar return; 260696a7f9aSGeorge Rimar static llvm::DenseMap<SectionBase *, int> Order = buildSectionOrder(); 261d6bcde38SGeorge Rimar MutableArrayRef<InputSection *> In(Begin, End - Begin); 262d6bcde38SGeorge Rimar sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); }); 263d6bcde38SGeorge Rimar } 264d6bcde38SGeorge Rimar 265d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches. 2666a1aa8d9SRafael Espindola std::vector<InputSection *> 26772e107f3SRui Ueyama LinkerScript::computeInputSections(const InputSectionDescription *Cmd) { 2686a1aa8d9SRafael Espindola std::vector<InputSection *> Ret; 2698c6a5aafSRui Ueyama 27072e107f3SRui Ueyama // Collects all sections that satisfy constraints of Cmd. 27172e107f3SRui Ueyama for (const SectionPattern &Pat : Cmd->SectionPatterns) { 27272e107f3SRui Ueyama size_t SizeBefore = Ret.size(); 27372e107f3SRui Ueyama 27472e107f3SRui Ueyama for (InputSectionBase *Sec : InputSections) { 27572e107f3SRui Ueyama if (Sec->Assigned) 2768c6a5aafSRui Ueyama continue; 27772e107f3SRui Ueyama 278e39709b2SRafael Espindola if (!Sec->Live) { 279e39709b2SRafael Espindola reportDiscarded(Sec); 280e39709b2SRafael Espindola continue; 281e39709b2SRafael Espindola } 282e39709b2SRafael Espindola 283908a3d34SRafael Espindola // For -emit-relocs we have to ignore entries like 284908a3d34SRafael Espindola // .rela.dyn : { *(.rela.data) } 285908a3d34SRafael Espindola // which are common because they are in the default bfd script. 28672e107f3SRui Ueyama if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA) 287908a3d34SRafael Espindola continue; 2888c6a5aafSRui Ueyama 2891e30f07cSDmitry Mikulin std::string Filename = filename(Sec->File); 29072e107f3SRui Ueyama if (!Cmd->FilePat.match(Filename) || 29172e107f3SRui Ueyama Pat.ExcludedFilePat.match(Filename) || 29272e107f3SRui Ueyama !Pat.SectionPat.match(Sec->Name)) 293e0be2901SRui Ueyama continue; 29472e107f3SRui Ueyama 2956a1aa8d9SRafael Espindola Ret.push_back(cast<InputSection>(Sec)); 29672e107f3SRui Ueyama Sec->Assigned = true; 297f94efdddSRui Ueyama } 298d3190795SRafael Espindola 299ee924709SRui Ueyama // Sort sections as instructed by SORT-family commands and --sort-section 300ee924709SRui Ueyama // option. Because SORT-family commands can be nested at most two depth 301ee924709SRui Ueyama // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command 302ee924709SRui Ueyama // line option is respected even if a SORT command is given, the exact 303ee924709SRui Ueyama // behavior we have here is a bit complicated. Here are the rules. 304ee924709SRui Ueyama // 305ee924709SRui Ueyama // 1. If two SORT commands are given, --sort-section is ignored. 306ee924709SRui Ueyama // 2. If one SORT command is given, and if it is not SORT_NONE, 307ee924709SRui Ueyama // --sort-section is handled as an inner SORT command. 308ee924709SRui Ueyama // 3. If one SORT command is given, and if it is SORT_NONE, don't sort. 309ee924709SRui Ueyama // 4. If no SORT command is given, sort according to --sort-section. 310d6bcde38SGeorge Rimar // 5. If no SORT commands are given and --sort-section is not specified, 311d6bcde38SGeorge Rimar // apply sorting provided by --symbol-ordering-file if any exist. 3126a1aa8d9SRafael Espindola InputSection **Begin = Ret.data() + SizeBefore; 3136a1aa8d9SRafael Espindola InputSection **End = Ret.data() + Ret.size(); 314d6bcde38SGeorge Rimar if (Pat.SortOuter == SortSectionPolicy::Default && 315d6bcde38SGeorge Rimar Config->SortSection == SortSectionPolicy::Default) { 316d6bcde38SGeorge Rimar sortBySymbolOrder(Begin, End); 317d6bcde38SGeorge Rimar continue; 318d6bcde38SGeorge Rimar } 31907171f21SGeorge Rimar if (Pat.SortOuter != SortSectionPolicy::None) { 32007171f21SGeorge Rimar if (Pat.SortInner == SortSectionPolicy::Default) 32107171f21SGeorge Rimar sortSections(Begin, End, Config->SortSection); 322ee924709SRui Ueyama else 32307171f21SGeorge Rimar sortSections(Begin, End, Pat.SortInner); 32407171f21SGeorge Rimar sortSections(Begin, End, Pat.SortOuter); 32507171f21SGeorge Rimar } 326ee924709SRui Ueyama } 32772e107f3SRui Ueyama return Ret; 328be94e1b6SRafael Espindola } 329be94e1b6SRafael Espindola 330b8dd23f5SRui Ueyama void LinkerScript::discard(ArrayRef<InputSectionBase *> V) { 331b4c9b81aSRafael Espindola for (InputSectionBase *S : V) { 332be94e1b6SRafael Espindola S->Live = false; 3331e30f07cSDmitry Mikulin if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab || 3341e30f07cSDmitry Mikulin S == InX::DynStrTab) 3352af64b0bSRafael Espindola error("discarding " + S->Name + " section is not allowed"); 336647c1685SGeorge Rimar discard(S->DependentSections); 337be94e1b6SRafael Espindola } 338be94e1b6SRafael Espindola } 339be94e1b6SRafael Espindola 340b4c9b81aSRafael Espindola std::vector<InputSectionBase *> 3418c022ca7SRafael Espindola LinkerScript::createInputSectionList(OutputSection &OutCmd) { 342b4c9b81aSRafael Espindola std::vector<InputSectionBase *> Ret; 343e7f912cdSRui Ueyama 3448f99f73cSRui Ueyama for (BaseCommand *Base : OutCmd.Commands) { 3458f99f73cSRui Ueyama auto *Cmd = dyn_cast<InputSectionDescription>(Base); 3467c3ff2ebSRafael Espindola if (!Cmd) 3470b9ce6a4SRui Ueyama continue; 34872e107f3SRui Ueyama 34972e107f3SRui Ueyama Cmd->Sections = computeInputSections(Cmd); 350e4c8b9b7SRafael Espindola Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end()); 3510b9ce6a4SRui Ueyama } 352e71a3f8aSRafael Espindola 3530b9ce6a4SRui Ueyama return Ret; 3540b9ce6a4SRui Ueyama } 3550b9ce6a4SRui Ueyama 356b8dd23f5SRui Ueyama void LinkerScript::processCommands(OutputSectionFactory &Factory) { 3575616adf6SRafael Espindola // A symbol can be assigned before any section is mentioned in the linker 3585616adf6SRafael Espindola // script. In an DSO, the symbol values are addresses, so the only important 3595616adf6SRafael Espindola // section values are: 3605616adf6SRafael Espindola // * SHN_UNDEF 3615616adf6SRafael Espindola // * SHN_ABS 3625616adf6SRafael Espindola // * Any value meaning a regular section. 3635616adf6SRafael Espindola // To handle that, create a dummy aether section that fills the void before 3645616adf6SRafael Espindola // the linker scripts switches to another section. It has an index of one 3655616adf6SRafael Espindola // which will map to whatever the first actual section is. 3665616adf6SRafael Espindola Aether = make<OutputSection>("", 0, SHF_ALLOC); 3675616adf6SRafael Espindola Aether->SectionIndex = 1; 368ac27de9dSRui Ueyama auto State = make_unique<AddressState>(); 36918d19687SRui Ueyama 370c1ace40bSPeter Smith // CurAddressState captures the local AddressState and makes it accessible 371c1ace40bSPeter Smith // deliberately. This is needed as there are some cases where we cannot just 372c1ace40bSPeter Smith // thread the current state through to a lambda function created by the 373c1ace40bSPeter Smith // script parser. 374906e9a18SPeter Smith CurAddressState = State.get(); 375906e9a18SPeter Smith CurAddressState->OutSec = Aether; 3765616adf6SRafael Espindola 377ac27de9dSRui Ueyama for (size_t I = 0; I < Commands.size(); ++I) { 3780b1b695aSRui Ueyama // Handle symbol assignments outside of any output section. 379ac27de9dSRui Ueyama if (auto *Cmd = dyn_cast<SymbolAssignment>(Commands[I])) { 3804cd7352cSRafael Espindola addSymbol(Cmd); 3812ab5f73dSRui Ueyama continue; 3822ab5f73dSRui Ueyama } 3830b1b695aSRui Ueyama 384ac27de9dSRui Ueyama if (auto *Sec = dyn_cast<OutputSection>(Commands[I])) { 3858c022ca7SRafael Espindola std::vector<InputSectionBase *> V = createInputSectionList(*Sec); 3867bd37870SRafael Espindola 3870b1b695aSRui Ueyama // The output section name `/DISCARD/' is special. 3880b1b695aSRui Ueyama // Any input section assigned to it is discarded. 3898c022ca7SRafael Espindola if (Sec->Name == "/DISCARD/") { 3907bd37870SRafael Espindola discard(V); 39148c3f1ceSRui Ueyama continue; 39248c3f1ceSRui Ueyama } 3930b9ce6a4SRui Ueyama 3940b1b695aSRui Ueyama // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive 3950b1b695aSRui Ueyama // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input 3960b1b695aSRui Ueyama // sections satisfy a given constraint. If not, a directive is handled 39707d7c42cSGeorge Rimar // as if it wasn't present from the beginning. 3980b1b695aSRui Ueyama // 3990b1b695aSRui Ueyama // Because we'll iterate over Commands many more times, the easiest 40007d7c42cSGeorge Rimar // way to "make it as if it wasn't present" is to just remove it. 4018c022ca7SRafael Espindola if (!matchConstraints(V, Sec->Constraint)) { 402b4c9b81aSRafael Espindola for (InputSectionBase *S : V) 403f94efdddSRui Ueyama S->Assigned = false; 404ac27de9dSRui Ueyama Commands.erase(Commands.begin() + I); 40507d7c42cSGeorge Rimar --I; 4067c3ff2ebSRafael Espindola continue; 4077c3ff2ebSRafael Espindola } 4087c3ff2ebSRafael Espindola 4090b1b695aSRui Ueyama // A directive may contain symbol definitions like this: 4100b1b695aSRui Ueyama // ".foo : { ...; bar = .; }". Handle them. 4118c022ca7SRafael Espindola for (BaseCommand *Base : Sec->Commands) 4128f99f73cSRui Ueyama if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base)) 4134cd7352cSRafael Espindola addSymbol(OutCmd); 4147c3ff2ebSRafael Espindola 4150b1b695aSRui Ueyama // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign 4160b1b695aSRui Ueyama // is given, input sections are aligned to that value, whether the 4170b1b695aSRui Ueyama // given value is larger or smaller than the original section alignment. 4188c022ca7SRafael Espindola if (Sec->SubalignExpr) { 4198c022ca7SRafael Espindola uint32_t Subalign = Sec->SubalignExpr().getValue(); 420b4c9b81aSRafael Espindola for (InputSectionBase *S : V) 4210b1b695aSRui Ueyama S->Alignment = Subalign; 42220d03194SEugene Leviant } 4230b1b695aSRui Ueyama 4240b1b695aSRui Ueyama // Add input sections to an output section. 425d86a4e50SGeorge Rimar for (InputSectionBase *S : V) 4260e2bfb1eSRui Ueyama Sec->addSection(cast<InputSection>(S)); 427c54d5b16SRui Ueyama 428660c9ab9SRafael Espindola assert(Sec->SectionIndex == INT_MAX); 429660c9ab9SRafael Espindola Sec->SectionIndex = I; 4308c022ca7SRafael Espindola if (Sec->Noload) 431fbb0463fSGeorge Rimar Sec->Type = SHT_NOBITS; 43248c3f1ceSRui Ueyama } 4334aa2ef5bSRafael Espindola } 434c1ace40bSPeter Smith CurAddressState = nullptr; 435db24d9c3SGeorge Rimar } 436e63d81bdSEugene Leviant 43702ed7575SRafael Espindola void LinkerScript::fabricateDefaultCommands() { 438cbfe9e94SPeter Smith // Define start address 439761f0b66SRui Ueyama uint64_t StartAddr = UINT64_MAX; 440cbfe9e94SPeter Smith 441c60b4510SPeter Smith // The Sections with -T<section> have been sorted in order of ascending 442c60b4510SPeter Smith // address. We must lower StartAddr if the lowest -T<section address> as 443c60b4510SPeter Smith // calls to setDot() must be monotonically increasing. 444c60b4510SPeter Smith for (auto &KV : Config->SectionStartMap) 445c60b4510SPeter Smith StartAddr = std::min(StartAddr, KV.second); 446c60b4510SPeter Smith 447f5db0b36SRui Ueyama auto Expr = [=] { 448b5ca92efSJames Henderson return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize()); 449f5db0b36SRui Ueyama }; 450ac27de9dSRui Ueyama Commands.insert(Commands.begin(), make<SymbolAssignment>(".", Expr, "")); 451cbfe9e94SPeter Smith } 452cbfe9e94SPeter Smith 453d2f225fdSRui Ueyama static OutputSection *findByName(ArrayRef<BaseCommand *> Vec, 454d2f225fdSRui Ueyama StringRef Name) { 455d2f225fdSRui Ueyama for (BaseCommand *Base : Vec) 456d2f225fdSRui Ueyama if (auto *Sec = dyn_cast<OutputSection>(Base)) 457d2f225fdSRui Ueyama if (Sec->Name == Name) 458d2f225fdSRui Ueyama return Sec; 459d2f225fdSRui Ueyama return nullptr; 460d2f225fdSRui Ueyama } 461d2f225fdSRui Ueyama 4620b1b695aSRui Ueyama // Add sections that didn't match any sections command. 463b8dd23f5SRui Ueyama void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) { 464ac27de9dSRui Ueyama unsigned End = Commands.size(); 465d2f225fdSRui Ueyama 4664f013bb3SRafael Espindola for (InputSectionBase *S : InputSections) { 467db5e56f7SRafael Espindola if (!S->Live || S->Parent) 4684f013bb3SRafael Espindola continue; 469d2f225fdSRui Ueyama 4704f013bb3SRafael Espindola StringRef Name = getOutputSectionName(S->Name); 471347c70d7SGeorge Rimar log(toString(S) + " is being placed in '" + Name + "'"); 472d2f225fdSRui Ueyama 473ac27de9dSRui Ueyama if (OutputSection *Sec = 474ac27de9dSRui Ueyama findByName(makeArrayRef(Commands).slice(0, End), Name)) { 4750e2bfb1eSRui Ueyama Sec->addSection(cast<InputSection>(S)); 476c54d5b16SRui Ueyama continue; 477660c9ab9SRafael Espindola } 478c54d5b16SRui Ueyama 479c54d5b16SRui Ueyama if (OutputSection *OS = Factory.addInputSec(S, Name)) 480ac27de9dSRui Ueyama Script->Commands.push_back(OS); 481c54d5b16SRui Ueyama assert(S->getOutputSection()->SectionIndex == INT_MAX); 482d7faa916SRafael Espindola } 4834f013bb3SRafael Espindola } 484e63d81bdSEugene Leviant 4857c4eafa3SRafael Espindola uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) { 486906e9a18SPeter Smith bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) && 487906e9a18SPeter Smith CurAddressState->OutSec->Type == SHT_NOBITS; 488906e9a18SPeter Smith uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot; 4897c4eafa3SRafael Espindola Start = alignTo(Start, Align); 4907c4eafa3SRafael Espindola uint64_t End = Start + Size; 4917c4eafa3SRafael Espindola 4927c4eafa3SRafael Espindola if (IsTbss) 493906e9a18SPeter Smith CurAddressState->ThreadBssOffset = End - Dot; 4947c4eafa3SRafael Espindola else 4957c4eafa3SRafael Espindola Dot = End; 4967c4eafa3SRafael Espindola return End; 497a940e539SRafael Espindola } 498a940e539SRafael Espindola 499b8dd23f5SRui Ueyama void LinkerScript::output(InputSection *S) { 500f694d33fSGeorge Rimar uint64_t Before = advance(0, 1); 5017c4eafa3SRafael Espindola uint64_t Pos = advance(S->getSize(), S->Alignment); 502906e9a18SPeter Smith S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr; 503d3190795SRafael Espindola 504d3190795SRafael Espindola // Update output section size after adding each section. This is so that 505d3190795SRafael Espindola // SIZEOF works correctly in the case below: 506d3190795SRafael Espindola // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) } 507906e9a18SPeter Smith CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr; 508d3190795SRafael Espindola 509b889744eSMeador Inge // If there is a memory region associated with this input section, then 510b889744eSMeador Inge // place the section in that region and update the region index. 511906e9a18SPeter Smith if (CurAddressState->MemRegion) { 512906e9a18SPeter Smith uint64_t &CurOffset = 513906e9a18SPeter Smith CurAddressState->MemRegionOffset[CurAddressState->MemRegion]; 514f694d33fSGeorge Rimar CurOffset += Pos - Before; 515906e9a18SPeter Smith uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin; 516906e9a18SPeter Smith if (CurSize > CurAddressState->MemRegion->Length) { 517906e9a18SPeter Smith uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length; 518906e9a18SPeter Smith error("section '" + CurAddressState->OutSec->Name + 519906e9a18SPeter Smith "' will not fit in region '" + CurAddressState->MemRegion->Name + 520906e9a18SPeter Smith "': overflowed by " + Twine(OverflowAmt) + " bytes"); 521b889744eSMeador Inge } 522b889744eSMeador Inge } 5232de509c3SRui Ueyama } 524ceabe80eSEugene Leviant 525b8dd23f5SRui Ueyama void LinkerScript::switchTo(OutputSection *Sec) { 526906e9a18SPeter Smith if (CurAddressState->OutSec == Sec) 527d3190795SRafael Espindola return; 528d3190795SRafael Espindola 529906e9a18SPeter Smith CurAddressState->OutSec = Sec; 530906e9a18SPeter Smith CurAddressState->OutSec->Addr = 531906e9a18SPeter Smith advance(0, CurAddressState->OutSec->Alignment); 532b71d6f7aSEugene Leviant 533b71d6f7aSEugene Leviant // If neither AT nor AT> is specified for an allocatable section, the linker 534b71d6f7aSEugene Leviant // will set the LMA such that the difference between VMA and LMA for the 535b71d6f7aSEugene Leviant // section is the same as the preceding output section in the same region 536b71d6f7aSEugene Leviant // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html 537906e9a18SPeter Smith if (CurAddressState->LMAOffset) 538906e9a18SPeter Smith CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset(); 539d3190795SRafael Espindola } 540d3190795SRafael Espindola 541b8dd23f5SRui Ueyama void LinkerScript::process(BaseCommand &Base) { 5422e081a4fSRui Ueyama // This handles the assignments to symbol or to the dot. 5432e081a4fSRui Ueyama if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) { 5442e081a4fSRui Ueyama assignSymbol(Cmd, true); 545d3190795SRafael Espindola return; 54697403d15SEugene Leviant } 547e38cbab5SGeorge Rimar 548e38cbab5SGeorge Rimar // Handle BYTE(), SHORT(), LONG(), or QUAD(). 5492e081a4fSRui Ueyama if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) { 550906e9a18SPeter Smith Cmd->Offset = Dot - CurAddressState->OutSec->Addr; 5512e081a4fSRui Ueyama Dot += Cmd->Size; 552906e9a18SPeter Smith CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr; 553e38cbab5SGeorge Rimar return; 554e38cbab5SGeorge Rimar } 555e38cbab5SGeorge Rimar 5562e081a4fSRui Ueyama // Handle ASSERT(). 5572e081a4fSRui Ueyama if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) { 5582e081a4fSRui Ueyama Cmd->Expression(); 559b2d99d6aSMeador Inge return; 560b2d99d6aSMeador Inge } 561b2d99d6aSMeador Inge 5622e081a4fSRui Ueyama // Handle a single input section description command. 5632e081a4fSRui Ueyama // It calculates and assigns the offsets for each section and also 564e38cbab5SGeorge Rimar // updates the output section size. 5652e081a4fSRui Ueyama auto &Cmd = cast<InputSectionDescription>(Base); 566a85e8ddaSRafael Espindola for (InputSection *Sec : Cmd.Sections) { 5673fb5a6dcSGeorge Rimar // We tentatively added all synthetic sections at the beginning and removed 5683fb5a6dcSGeorge Rimar // empty ones afterwards (because there is no way to know whether they were 5693fb5a6dcSGeorge Rimar // going be empty or not other than actually running linker scripts.) 5703fb5a6dcSGeorge Rimar // We need to ignore remains of empty sections. 5712e081a4fSRui Ueyama if (auto *S = dyn_cast<SyntheticSection>(Sec)) 5722e081a4fSRui Ueyama if (S->empty()) 5733fb5a6dcSGeorge Rimar continue; 5743fb5a6dcSGeorge Rimar 5752e081a4fSRui Ueyama if (!Sec->Live) 57678ef645fSGeorge Rimar continue; 577906e9a18SPeter Smith assert(CurAddressState->OutSec == Sec->getParent()); 578a85e8ddaSRafael Espindola output(Sec); 579ceabe80eSEugene Leviant } 580ceabe80eSEugene Leviant } 581ceabe80eSEugene Leviant 582b889744eSMeador Inge // This function searches for a memory region to place the given output 583b889744eSMeador Inge // section in. If found, a pointer to the appropriate memory region is 584b889744eSMeador Inge // returned. Otherwise, a nullptr is returned. 5858c022ca7SRafael Espindola MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) { 586b889744eSMeador Inge // If a memory region name was specified in the output section command, 587b889744eSMeador Inge // then try to find that region first. 5888c022ca7SRafael Espindola if (!Sec->MemoryRegionName.empty()) { 589ac27de9dSRui Ueyama auto It = MemoryRegions.find(Sec->MemoryRegionName); 590ac27de9dSRui Ueyama if (It != MemoryRegions.end()) 5915f37541cSGeorge Rimar return It->second; 5928c022ca7SRafael Espindola error("memory region '" + Sec->MemoryRegionName + "' not declared"); 593b889744eSMeador Inge return nullptr; 594b889744eSMeador Inge } 595b889744eSMeador Inge 596d7c5400fSRui Ueyama // If at least one memory region is defined, all sections must 597d7c5400fSRui Ueyama // belong to some memory region. Otherwise, we don't need to do 598d7c5400fSRui Ueyama // anything for memory regions. 599ac27de9dSRui Ueyama if (MemoryRegions.empty()) 600b889744eSMeador Inge return nullptr; 601b889744eSMeador Inge 602b889744eSMeador Inge // See if a region can be found by matching section flags. 603ac27de9dSRui Ueyama for (auto &Pair : MemoryRegions) { 6045f37541cSGeorge Rimar MemoryRegion *M = Pair.second; 6055f37541cSGeorge Rimar if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0) 6065f37541cSGeorge Rimar return M; 607b889744eSMeador Inge } 608b889744eSMeador Inge 609b889744eSMeador Inge // Otherwise, no suitable region was found. 610b889744eSMeador Inge if (Sec->Flags & SHF_ALLOC) 611b889744eSMeador Inge error("no memory region specified for section '" + Sec->Name + "'"); 612b889744eSMeador Inge return nullptr; 613b889744eSMeador Inge } 614b889744eSMeador Inge 6150b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section 6160b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }"). 6178c022ca7SRafael Espindola void LinkerScript::assignOffsets(OutputSection *Sec) { 618dece2808SRafael Espindola if (!(Sec->Flags & SHF_ALLOC)) 619dece2808SRafael Espindola Dot = 0; 6208c022ca7SRafael Espindola else if (Sec->AddrExpr) 6218c022ca7SRafael Espindola setDot(Sec->AddrExpr, Sec->Location, false); 622679828ffSRafael Espindola 623c2dffe3aSGeorge Rimar CurAddressState->MemRegion = Sec->MemRegion; 624c2dffe3aSGeorge Rimar if (CurAddressState->MemRegion) 625c2dffe3aSGeorge Rimar Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion]; 626c2dffe3aSGeorge Rimar 6278c022ca7SRafael Espindola if (Sec->LMAExpr) { 6280c1c8085SGeorge Rimar uint64_t D = Dot; 6298c022ca7SRafael Espindola CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; }; 6305784e96fSEugene Leviant } 6315784e96fSEugene Leviant 632b889744eSMeador Inge switchTo(Sec); 6330b1b695aSRui Ueyama 634d86a4e50SGeorge Rimar // We do not support custom layout for compressed debug sectons. 635d86a4e50SGeorge Rimar // At this point we already know their size and have compressed content. 636906e9a18SPeter Smith if (CurAddressState->OutSec->Flags & SHF_COMPRESSED) 637d86a4e50SGeorge Rimar return; 638d86a4e50SGeorge Rimar 6398c022ca7SRafael Espindola for (BaseCommand *C : Sec->Commands) 640de8d9897SRafael Espindola process(*C); 641d3190795SRafael Espindola } 642d3190795SRafael Espindola 643b8dd23f5SRui Ueyama void LinkerScript::removeEmptyCommands() { 6446d38e4dbSRafael Espindola // It is common practice to use very generic linker scripts. So for any 6456d38e4dbSRafael Espindola // given run some of the output sections in the script will be empty. 6466d38e4dbSRafael Espindola // We could create corresponding empty output sections, but that would 6476d38e4dbSRafael Espindola // clutter the output. 6486d38e4dbSRafael Espindola // We instead remove trivially empty sections. The bfd linker seems even 6496d38e4dbSRafael Espindola // more aggressive at removing them. 650ac27de9dSRui Ueyama llvm::erase_if(Commands, [&](BaseCommand *Base) { 6518c022ca7SRafael Espindola if (auto *Sec = dyn_cast<OutputSection>(Base)) 6528c022ca7SRafael Espindola return !Sec->Live; 6530b1b695aSRui Ueyama return false; 6546d38e4dbSRafael Espindola }); 65507fe6129SRafael Espindola } 65607fe6129SRafael Espindola 6578c022ca7SRafael Espindola static bool isAllSectionDescription(const OutputSection &Cmd) { 6588f99f73cSRui Ueyama for (BaseCommand *Base : Cmd.Commands) 6598f99f73cSRui Ueyama if (!isa<InputSectionDescription>(*Base)) 6606a53737cSRafael Espindola return false; 6616a53737cSRafael Espindola return true; 6626a53737cSRafael Espindola } 6636d38e4dbSRafael Espindola 664b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsBeforeSorting() { 6659546fffbSRafael Espindola // If the output section contains only symbol assignments, create a 6669546fffbSRafael Espindola // corresponding output section. The bfd linker seems to only create them if 6679546fffbSRafael Espindola // '.' is assigned to, but creating these section should not have any bad 6689546fffbSRafael Espindola // consequeces and gives us a section to put the symbol in. 6690c1c8085SGeorge Rimar uint64_t Flags = SHF_ALLOC; 670660c9ab9SRafael Espindola 671ac27de9dSRui Ueyama for (BaseCommand *Cmd : Commands) { 6728962db91SGeorge Rimar auto *Sec = dyn_cast<OutputSection>(Cmd); 6738c022ca7SRafael Espindola if (!Sec) 6749546fffbSRafael Espindola continue; 6758c022ca7SRafael Espindola if (Sec->Live) { 6762b074553SRafael Espindola Flags = Sec->Flags; 6779546fffbSRafael Espindola continue; 6789546fffbSRafael Espindola } 6799546fffbSRafael Espindola 6808c022ca7SRafael Espindola if (isAllSectionDescription(*Sec)) 6816a53737cSRafael Espindola continue; 6826a53737cSRafael Espindola 6838c022ca7SRafael Espindola Sec->Live = true; 6848c022ca7SRafael Espindola Sec->Flags = Flags; 6859546fffbSRafael Espindola } 686f7a17448SRafael Espindola } 687f7a17448SRafael Espindola 688b8dd23f5SRui Ueyama void LinkerScript::adjustSectionsAfterSorting() { 689feed7506SRafael Espindola // Try and find an appropriate memory region to assign offsets in. 690ac27de9dSRui Ueyama for (BaseCommand *Base : Commands) { 6918c022ca7SRafael Espindola if (auto *Sec = dyn_cast<OutputSection>(Base)) { 692ba45584cSGeorge Rimar if (!Sec->Live) 693ba45584cSGeorge Rimar continue; 6948c022ca7SRafael Espindola Sec->MemRegion = findMemoryRegion(Sec); 695d1960dc0SRafael Espindola // Handle align (e.g. ".foo : ALIGN(16) { ... }"). 6968c022ca7SRafael Espindola if (Sec->AlignExpr) 6978befefb2SRui Ueyama Sec->Alignment = 6988befefb2SRui Ueyama std::max<uint32_t>(Sec->Alignment, Sec->AlignExpr().getValue()); 699d1960dc0SRafael Espindola } 700d1960dc0SRafael Espindola } 701feed7506SRafael Espindola 702f7a17448SRafael Espindola // If output section command doesn't specify any segments, 703f7a17448SRafael Espindola // and we haven't previously assigned any section to segment, 704f7a17448SRafael Espindola // then we simply assign section to the very first load segment. 705f7a17448SRafael Espindola // Below is an example of such linker script: 706f7a17448SRafael Espindola // PHDRS { seg PT_LOAD; } 707f7a17448SRafael Espindola // SECTIONS { .aaa : { *(.aaa) } } 708f7a17448SRafael Espindola std::vector<StringRef> DefPhdrs; 709f7a17448SRafael Espindola auto FirstPtLoad = 710ac27de9dSRui Ueyama std::find_if(PhdrsCommands.begin(), PhdrsCommands.end(), 711f7a17448SRafael Espindola [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; }); 712ac27de9dSRui Ueyama if (FirstPtLoad != PhdrsCommands.end()) 713f7a17448SRafael Espindola DefPhdrs.push_back(FirstPtLoad->Name); 714f7a17448SRafael Espindola 715f7a17448SRafael Espindola // Walk the commands and propagate the program headers to commands that don't 716f7a17448SRafael Espindola // explicitly specify them. 717ac27de9dSRui Ueyama for (BaseCommand *Base : Commands) { 7188c022ca7SRafael Espindola auto *Sec = dyn_cast<OutputSection>(Base); 7198c022ca7SRafael Espindola if (!Sec) 720f7a17448SRafael Espindola continue; 7218f99f73cSRui Ueyama 7228c022ca7SRafael Espindola if (Sec->Phdrs.empty()) { 723a020d348SAndrew Ng // To match the bfd linker script behaviour, only propagate program 724a020d348SAndrew Ng // headers to sections that are allocated. 7258c022ca7SRafael Espindola if (Sec->Flags & SHF_ALLOC) 7268c022ca7SRafael Espindola Sec->Phdrs = DefPhdrs; 727a020d348SAndrew Ng } else { 7288c022ca7SRafael Espindola DefPhdrs = Sec->Phdrs; 729f7a17448SRafael Espindola } 730a020d348SAndrew Ng } 7319546fffbSRafael Espindola } 7329546fffbSRafael Espindola 733582ede89SGeorge Rimar static OutputSection *findFirstSection(PhdrEntry *Load) { 734582ede89SGeorge Rimar for (OutputSection *Sec : OutputSections) 735582ede89SGeorge Rimar if (Sec->PtLoad == Load) 736582ede89SGeorge Rimar return Sec; 737582ede89SGeorge Rimar return nullptr; 738582ede89SGeorge Rimar } 739582ede89SGeorge Rimar 740b93c5b9fSPetr Hosek // Try to find an address for the file and program headers output sections, 741b93c5b9fSPetr Hosek // which were unconditionally added to the first PT_LOAD segment earlier. 742b93c5b9fSPetr Hosek // 743b93c5b9fSPetr Hosek // When using the default layout, we check if the headers fit below the first 744b93c5b9fSPetr Hosek // allocated section. When using a linker script, we also check if the headers 745b93c5b9fSPetr Hosek // are covered by the output section. This allows omitting the headers by not 746b93c5b9fSPetr Hosek // leaving enough space for them in the linker script; this pattern is common 747b93c5b9fSPetr Hosek // in embedded systems. 748b93c5b9fSPetr Hosek // 749b93c5b9fSPetr Hosek // If there isn't enough space for these sections, we'll remove them from the 750b93c5b9fSPetr Hosek // PT_LOAD segment, and we'll also remove the PT_PHDR segment. 751aa354187SGeorge Rimar void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) { 7525aedebffSPeter Smith uint64_t Min = std::numeric_limits<uint64_t>::max(); 7538c022ca7SRafael Espindola for (OutputSection *Sec : OutputSections) 7545aedebffSPeter Smith if (Sec->Flags & SHF_ALLOC) 7555aedebffSPeter Smith Min = std::min<uint64_t>(Min, Sec->Addr); 7565aedebffSPeter Smith 757aa354187SGeorge Rimar auto It = llvm::find_if( 758aa354187SGeorge Rimar Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; }); 759aa354187SGeorge Rimar if (It == Phdrs.end()) 760d971e703SGeorge Rimar return; 761aa354187SGeorge Rimar PhdrEntry *FirstPTLoad = *It; 76202ed7575SRafael Espindola 76302ed7575SRafael Espindola uint64_t HeaderSize = getHeaderSize(); 764b93c5b9fSPetr Hosek // When linker script with SECTIONS is being used, don't output headers 765b93c5b9fSPetr Hosek // unless there's a space for them. 766*a323e2a7SRui Ueyama uint64_t Base = HasSectionsCommand ? alignDown(Min, Config->MaxPageSize) : 0; 767b93c5b9fSPetr Hosek if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) { 7681f0fe88aSRafael Espindola Min = alignDown(Min - HeaderSize, Config->MaxPageSize); 76902ed7575SRafael Espindola Out::ElfHeader->Addr = Min; 77002ed7575SRafael Espindola Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size; 771d971e703SGeorge Rimar return; 77202ed7575SRafael Espindola } 77302ed7575SRafael Espindola 774582ede89SGeorge Rimar Out::ElfHeader->PtLoad = nullptr; 775582ede89SGeorge Rimar Out::ProgramHeaders->PtLoad = nullptr; 7766823c5f0SGeorge Rimar FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad); 77702ed7575SRafael Espindola 77860608a8aSGeorge Rimar llvm::erase_if(Phdrs, 77960608a8aSGeorge Rimar [](const PhdrEntry *E) { return E->p_type == PT_PHDR; }); 78002ed7575SRafael Espindola } 78102ed7575SRafael Espindola 782ac27de9dSRui Ueyama LinkerScript::AddressState::AddressState() { 783ac27de9dSRui Ueyama for (auto &MRI : Script->MemoryRegions) { 7845f37541cSGeorge Rimar const MemoryRegion *MR = MRI.second; 785906e9a18SPeter Smith MemRegionOffset[MR] = MR->Origin; 786906e9a18SPeter Smith } 787906e9a18SPeter Smith } 788906e9a18SPeter Smith 7897c18c28cSRui Ueyama // Assign addresses as instructed by linker script SECTIONS sub-commands. 790b5ca92efSJames Henderson void LinkerScript::assignAddresses() { 791b5ca92efSJames Henderson // By default linker scripts use an initial value of 0 for '.', but prefer 792b5ca92efSJames Henderson // -image-base if set. 793b5ca92efSJames Henderson Dot = Config->ImageBase ? *Config->ImageBase : 0; 794ac27de9dSRui Ueyama auto State = make_unique<AddressState>(); 79518d19687SRui Ueyama 796c1ace40bSPeter Smith // CurAddressState captures the local AddressState and makes it accessible 797c1ace40bSPeter Smith // deliberately. This is needed as there are some cases where we cannot just 798c1ace40bSPeter Smith // thread the current state through to a lambda function created by the 799c1ace40bSPeter Smith // script parser. 800906e9a18SPeter Smith CurAddressState = State.get(); 80172dc195dSRafael Espindola ErrorOnMissingSection = true; 80206f4743aSRafael Espindola switchTo(Aether); 80306f4743aSRafael Espindola 804ac27de9dSRui Ueyama for (BaseCommand *Base : Commands) { 8058f99f73cSRui Ueyama if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) { 806d379f735SRui Ueyama assignSymbol(Cmd, false); 80705ef4cffSRui Ueyama continue; 808652852c5SGeorge Rimar } 809652852c5SGeorge Rimar 8108f99f73cSRui Ueyama if (auto *Cmd = dyn_cast<AssertCommand>(Base)) { 8114595df94SRafael Espindola Cmd->Expression(); 812eefa758eSGeorge Rimar continue; 813eefa758eSGeorge Rimar } 814eefa758eSGeorge Rimar 8158c022ca7SRafael Espindola assignOffsets(cast<OutputSection>(Base)); 816a14b13d8SGeorge Rimar } 817c1ace40bSPeter Smith CurAddressState = nullptr; 818fb8978fcSDima Stepanov } 819652852c5SGeorge Rimar 820464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command. 821aa354187SGeorge Rimar std::vector<PhdrEntry *> LinkerScript::createPhdrs() { 822aa354187SGeorge Rimar std::vector<PhdrEntry *> Ret; 823bbe38602SEugene Leviant 824464daadcSRui Ueyama // Process PHDRS and FILEHDR keywords because they are not 825464daadcSRui Ueyama // real output sections and cannot be added in the following loop. 826ac27de9dSRui Ueyama for (const PhdrsCommand &Cmd : PhdrsCommands) { 8270ae2c24cSRui Ueyama PhdrEntry *Phdr = make<PhdrEntry>(Cmd.Type, Cmd.Flags ? *Cmd.Flags : PF_R); 828bbe38602SEugene Leviant 829bbe38602SEugene Leviant if (Cmd.HasFilehdr) 830aa354187SGeorge Rimar Phdr->add(Out::ElfHeader); 831bbe38602SEugene Leviant if (Cmd.HasPhdrs) 832aa354187SGeorge Rimar Phdr->add(Out::ProgramHeaders); 83356b21c86SEugene Leviant 83456b21c86SEugene Leviant if (Cmd.LMAExpr) { 835aa354187SGeorge Rimar Phdr->p_paddr = Cmd.LMAExpr().getValue(); 836aa354187SGeorge Rimar Phdr->HasLMA = true; 83756b21c86SEugene Leviant } 838aa354187SGeorge Rimar Ret.push_back(Phdr); 839bbe38602SEugene Leviant } 840bbe38602SEugene Leviant 841464daadcSRui Ueyama // Add output sections to program headers. 8428c022ca7SRafael Espindola for (OutputSection *Sec : OutputSections) { 843bbe38602SEugene Leviant // Assign headers specified by linker script 8448c022ca7SRafael Espindola for (size_t Id : getPhdrIndices(Sec)) { 845aa354187SGeorge Rimar Ret[Id]->add(Sec); 846ac27de9dSRui Ueyama if (!PhdrsCommands[Id].Flags.hasValue()) 847aa354187SGeorge Rimar Ret[Id]->p_flags |= Sec->getPhdrFlags(); 848bbe38602SEugene Leviant } 849bbe38602SEugene Leviant } 850edebbdf1SRui Ueyama return Ret; 851bbe38602SEugene Leviant } 852bbe38602SEugene Leviant 853e03ba023SRui Ueyama // Returns true if we should emit an .interp section. 854e03ba023SRui Ueyama // 855e03ba023SRui Ueyama // We usually do. But if PHDRS commands are given, and 856e03ba023SRui Ueyama // no PT_INTERP is there, there's no place to emit an 857e03ba023SRui Ueyama // .interp, so we don't do that in that case. 858e03ba023SRui Ueyama bool LinkerScript::needsInterpSection() { 859ac27de9dSRui Ueyama if (PhdrsCommands.empty()) 860e03ba023SRui Ueyama return true; 861ac27de9dSRui Ueyama for (PhdrsCommand &Cmd : PhdrsCommands) 862e31d9886SRui Ueyama if (Cmd.Type == PT_INTERP) 863e31d9886SRui Ueyama return true; 864e03ba023SRui Ueyama return false; 865f9bc3bd2SEugene Leviant } 866f9bc3bd2SEugene Leviant 867b8dd23f5SRui Ueyama ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) { 8687e5b0a59SGeorge Rimar if (S == ".") { 8697e5b0a59SGeorge Rimar if (CurAddressState) 8704fbe3518SRui Ueyama return {CurAddressState->OutSec, false, 8714fbe3518SRui Ueyama Dot - CurAddressState->OutSec->Addr, Loc}; 8727e5b0a59SGeorge Rimar error(Loc + ": unable to get location counter value"); 8737e5b0a59SGeorge Rimar return 0; 8747e5b0a59SGeorge Rimar } 875244ef981SRafael Espindola if (SymbolBody *B = Symtab->find(S)) { 87672dc195dSRafael Espindola if (auto *D = dyn_cast<DefinedRegular>(B)) 8774fbe3518SRui Ueyama return {D->Section, false, D->Value, Loc}; 87830f16b23SPetr Hosek if (auto *C = dyn_cast<DefinedCommon>(B)) 8794fbe3518SRui Ueyama return {C->Section, false, 0, Loc}; 88072dc195dSRafael Espindola } 881f6aeed36SEugene Leviant error(Loc + ": symbol not found: " + S); 882884e786dSGeorge Rimar return 0; 883884e786dSGeorge Rimar } 884884e786dSGeorge Rimar 885656be311SRui Ueyama // Returns the index of the segment named Name. 886656be311SRui Ueyama static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> Vec, 887656be311SRui Ueyama StringRef Name) { 888656be311SRui Ueyama for (size_t I = 0; I < Vec.size(); ++I) 889656be311SRui Ueyama if (Vec[I].Name == Name) 890656be311SRui Ueyama return I; 891656be311SRui Ueyama return None; 892656be311SRui Ueyama } 893656be311SRui Ueyama 8942c923c2cSRafael Espindola // Returns indices of ELF headers containing specific section. Each index is a 8952c923c2cSRafael Espindola // zero based number of ELF header listed within PHDRS {} script block. 8968c022ca7SRafael Espindola std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) { 89729c5a2a9SRui Ueyama std::vector<size_t> Ret; 898656be311SRui Ueyama 899656be311SRui Ueyama for (StringRef S : Cmd->Phdrs) { 900ac27de9dSRui Ueyama if (Optional<size_t> Idx = getPhdrIndex(PhdrsCommands, S)) 90187223574SRui Ueyama Ret.push_back(*Idx); 902656be311SRui Ueyama else if (S != "NONE") 903656be311SRui Ueyama error(Cmd->Location + ": section header '" + S + 904656be311SRui Ueyama "' is not listed in PHDRS"); 905bbe38602SEugene Leviant } 906656be311SRui Ueyama return Ret; 90729c5a2a9SRui Ueyama } 908