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" 16f7c5fbb1SRui Ueyama #include "Driver.h" 171ebc8ed7SRui Ueyama #include "InputSection.h" 189381eb10SRui Ueyama #include "Memory.h" 19652852c5SGeorge Rimar #include "OutputSections.h" 20e77b5bf6SAdhemerval Zanella #include "ScriptParser.h" 2193c9af42SRui Ueyama #include "Strings.h" 22f7c5fbb1SRui Ueyama #include "SymbolTable.h" 2355518e7dSRui Ueyama #include "Symbols.h" 243fb5a6dcSGeorge Rimar #include "SyntheticSections.h" 25467c4d55SEugene Leviant #include "Target.h" 26bbe38602SEugene Leviant #include "Writer.h" 2722886a28SEugene Zelenko #include "llvm/ADT/STLExtras.h" 288c6a5aafSRui Ueyama #include "llvm/ADT/SmallString.h" 2922886a28SEugene Zelenko #include "llvm/ADT/StringRef.h" 30960504b9SRui Ueyama #include "llvm/ADT/StringSwitch.h" 3122886a28SEugene Zelenko #include "llvm/Support/Casting.h" 32652852c5SGeorge Rimar #include "llvm/Support/ELF.h" 3322886a28SEugene Zelenko #include "llvm/Support/Endian.h" 3422886a28SEugene Zelenko #include "llvm/Support/ErrorHandling.h" 35f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h" 3622886a28SEugene Zelenko #include "llvm/Support/MathExtras.h" 37f03f3cc1SRui Ueyama #include "llvm/Support/Path.h" 3822886a28SEugene Zelenko #include <algorithm> 3922886a28SEugene Zelenko #include <cassert> 4022886a28SEugene Zelenko #include <cstddef> 4122886a28SEugene Zelenko #include <cstdint> 4222886a28SEugene Zelenko #include <iterator> 4322886a28SEugene Zelenko #include <limits> 4422886a28SEugene Zelenko #include <memory> 4522886a28SEugene Zelenko #include <string> 4622886a28SEugene Zelenko #include <tuple> 4722886a28SEugene Zelenko #include <vector> 48f7c5fbb1SRui Ueyama 49f7c5fbb1SRui Ueyama using namespace llvm; 50652852c5SGeorge Rimar using namespace llvm::ELF; 511ebc8ed7SRui Ueyama using namespace llvm::object; 52e38cbab5SGeorge Rimar using namespace llvm::support::endian; 53f7c5fbb1SRui Ueyama using namespace lld; 54e0df00b9SRafael Espindola using namespace lld::elf; 55f7c5fbb1SRui Ueyama 56884e786dSGeorge Rimar LinkerScriptBase *elf::ScriptBase; 5707320e40SRui Ueyama ScriptConfiguration *elf::ScriptConfig; 58717677afSRui Ueyama 596c55f0e3SGeorge Rimar template <class ELFT> static void addRegular(SymbolAssignment *Cmd) { 603dabfc6bSRafael Espindola uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT; 611bdaf3e3SRui Ueyama Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE, 62463984d4SGeorge Rimar 0, 0, STB_GLOBAL, nullptr, nullptr); 631602421cSRui Ueyama Cmd->Sym = Sym->body(); 6420d03194SEugene Leviant 6520d03194SEugene Leviant // If we have no SECTIONS then we don't have '.' and don't call 6620d03194SEugene Leviant // assignAddresses(). We calculate symbol value immediately in this case. 6720d03194SEugene Leviant if (!ScriptConfig->HasSections) 6820d03194SEugene Leviant cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0); 69ceabe80eSEugene Leviant } 70ceabe80eSEugene Leviant 710c70d3ccSRui Ueyama template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) { 72afaa9343SEugene Leviant // If we have SECTIONS block then output sections haven't been created yet. 73afaa9343SEugene Leviant const OutputSectionBase *Sec = 74afaa9343SEugene Leviant ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section(); 75e1937bb5SGeorge Rimar Symbol *Sym = Symtab<ELFT>::X->addSynthetic( 76afaa9343SEugene Leviant Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT); 771602421cSRui Ueyama Cmd->Sym = Sym->body(); 78afaa9343SEugene Leviant 79afaa9343SEugene Leviant // If we already know section then we can calculate symbol value immediately. 80afaa9343SEugene Leviant if (Sec) 81*4f2f50dcSRui Ueyama cast<DefinedSynthetic>(Cmd->Sym)->Value = Cmd->Expression(0) - Sec->Addr; 82ceabe80eSEugene Leviant } 83ceabe80eSEugene Leviant 8422375f24SRui Ueyama static bool isUnderSysroot(StringRef Path) { 8522375f24SRui Ueyama if (Config->Sysroot == "") 8622375f24SRui Ueyama return false; 8722375f24SRui Ueyama for (; !Path.empty(); Path = sys::path::parent_path(Path)) 8822375f24SRui Ueyama if (sys::fs::equivalent(Config->Sysroot, Path)) 8922375f24SRui Ueyama return true; 9022375f24SRui Ueyama return false; 9122375f24SRui Ueyama } 9222375f24SRui Ueyama 93db741e72SEugene Leviant template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) { 942f831dcaSRafael Espindola if (Cmd->Expression.IsAbsolute()) 95db741e72SEugene Leviant addRegular<ELFT>(Cmd); 96db741e72SEugene Leviant else 97db741e72SEugene Leviant addSynthetic<ELFT>(Cmd); 98db741e72SEugene Leviant } 991602421cSRui Ueyama // If a symbol was in PROVIDE(), we need to define it only when 1001602421cSRui Ueyama // it is an undefined symbol. 1011602421cSRui Ueyama template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) { 1021602421cSRui Ueyama if (Cmd->Name == ".") 103ceabe80eSEugene Leviant return false; 1041602421cSRui Ueyama if (!Cmd->Provide) 105ceabe80eSEugene Leviant return true; 1061602421cSRui Ueyama SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name); 1071602421cSRui Ueyama return B && B->isUndefined(); 108ceabe80eSEugene Leviant } 109ceabe80eSEugene Leviant 110076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) { 111076fe157SGeorge Rimar return C->Kind == AssignmentKind; 112076fe157SGeorge Rimar } 113076fe157SGeorge Rimar 114076fe157SGeorge Rimar bool OutputSectionCommand::classof(const BaseCommand *C) { 115076fe157SGeorge Rimar return C->Kind == OutputSectionKind; 116076fe157SGeorge Rimar } 117076fe157SGeorge Rimar 118eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) { 119eea3114fSGeorge Rimar return C->Kind == InputSectionKind; 120eea3114fSGeorge Rimar } 121eea3114fSGeorge Rimar 122eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) { 123eefa758eSGeorge Rimar return C->Kind == AssertKind; 124eefa758eSGeorge Rimar } 125eefa758eSGeorge Rimar 126e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) { 127e38cbab5SGeorge Rimar return C->Kind == BytesDataKind; 128e38cbab5SGeorge Rimar } 129e38cbab5SGeorge Rimar 13022886a28SEugene Zelenko template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default; 13122886a28SEugene Zelenko template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default; 132f34d0e08SRui Ueyama 133e0be2901SRui Ueyama template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) { 134e0be2901SRui Ueyama if (S->getFile()) 135e0be2901SRui Ueyama return sys::path::filename(S->getFile()->getName()); 136e0be2901SRui Ueyama return ""; 137e0be2901SRui Ueyama } 138e0be2901SRui Ueyama 13907320e40SRui Ueyama template <class ELFT> 14007320e40SRui Ueyama bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) { 141e0be2901SRui Ueyama for (InputSectionDescription *ID : Opt.KeptSections) 142e0be2901SRui Ueyama if (ID->FilePat.match(basename(S))) 143cf43f179SEugene Leviant for (SectionPattern &P : ID->SectionPatterns) 144f91282e1SRui Ueyama if (P.SectionPat.match(S->Name)) 145eea3114fSGeorge Rimar return true; 146eea3114fSGeorge Rimar return false; 147eea3114fSGeorge Rimar } 148eea3114fSGeorge Rimar 149575208caSGeorge Rimar static bool comparePriority(InputSectionData *A, InputSectionData *B) { 150575208caSGeorge Rimar return getPriority(A->Name) < getPriority(B->Name); 151575208caSGeorge Rimar } 152575208caSGeorge Rimar 153c0028d3dSRafael Espindola static bool compareName(InputSectionData *A, InputSectionData *B) { 154042a3f20SRafael Espindola return A->Name < B->Name; 1550702c4e8SGeorge Rimar } 156742c3836SRui Ueyama 157c0028d3dSRafael Espindola static bool compareAlignment(InputSectionData *A, InputSectionData *B) { 158742c3836SRui Ueyama // ">" is not a mistake. Larger alignments are placed before smaller 159742c3836SRui Ueyama // alignments in order to reduce the amount of padding necessary. 160742c3836SRui Ueyama // This is compatible with GNU. 161742c3836SRui Ueyama return A->Alignment > B->Alignment; 162742c3836SRui Ueyama } 163742c3836SRui Ueyama 164c0028d3dSRafael Espindola static std::function<bool(InputSectionData *, InputSectionData *)> 165be394db3SGeorge Rimar getComparator(SortSectionPolicy K) { 166be394db3SGeorge Rimar switch (K) { 167be394db3SGeorge Rimar case SortSectionPolicy::Alignment: 168c0028d3dSRafael Espindola return compareAlignment; 169be394db3SGeorge Rimar case SortSectionPolicy::Name: 170be394db3SGeorge Rimar return compareName; 171be394db3SGeorge Rimar case SortSectionPolicy::Priority: 172be394db3SGeorge Rimar return comparePriority; 173be394db3SGeorge Rimar default: 174be394db3SGeorge Rimar llvm_unreachable("unknown sort policy"); 175be394db3SGeorge Rimar } 176742c3836SRui Ueyama } 1770702c4e8SGeorge Rimar 17848c3f1ceSRui Ueyama template <class ELFT> 179e71a3f8aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections, 18006ae6836SGeorge Rimar ConstraintKind Kind) { 1818f66df92SGeorge Rimar if (Kind == ConstraintKind::NoConstraint) 1828f66df92SGeorge Rimar return true; 183e746e52cSRafael Espindola bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) { 184d3190795SRafael Espindola auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2); 1851854a8ebSRafael Espindola return Sec->Flags & SHF_WRITE; 18606ae6836SGeorge Rimar }); 187e746e52cSRafael Espindola return (IsRW && Kind == ConstraintKind::ReadWrite) || 188e746e52cSRafael Espindola (!IsRW && Kind == ConstraintKind::ReadOnly); 18906ae6836SGeorge Rimar } 19006ae6836SGeorge Rimar 19107171f21SGeorge Rimar static void sortSections(InputSectionData **Begin, InputSectionData **End, 192ee924709SRui Ueyama SortSectionPolicy K) { 193ee924709SRui Ueyama if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None) 19407171f21SGeorge Rimar std::stable_sort(Begin, End, getComparator(K)); 195ee924709SRui Ueyama } 196ee924709SRui Ueyama 197d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches. 198be94e1b6SRafael Espindola template <class ELFT> 199e71a3f8aSRafael Espindola void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) { 2004dc07becSRui Ueyama // Collects all sections that satisfy constraints of I 2014dc07becSRui Ueyama // and attach them to I. 2024dc07becSRui Ueyama for (SectionPattern &Pat : I->SectionPatterns) { 20307171f21SGeorge Rimar size_t SizeBefore = I->Sections.size(); 2048c6a5aafSRui Ueyama 2058c6a5aafSRui Ueyama for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) { 206f94efdddSRui Ueyama if (!S->Live || S->Assigned) 2078c6a5aafSRui Ueyama continue; 2088c6a5aafSRui Ueyama 209e0be2901SRui Ueyama StringRef Filename = basename(S); 210e0be2901SRui Ueyama if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename)) 211e0be2901SRui Ueyama continue; 212e0be2901SRui Ueyama if (!Pat.SectionPat.match(S->Name)) 213e0be2901SRui Ueyama continue; 214d3190795SRafael Espindola I->Sections.push_back(S); 215f94efdddSRui Ueyama S->Assigned = true; 216f94efdddSRui Ueyama } 217d3190795SRafael Espindola 218ee924709SRui Ueyama // Sort sections as instructed by SORT-family commands and --sort-section 219ee924709SRui Ueyama // option. Because SORT-family commands can be nested at most two depth 220ee924709SRui Ueyama // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command 221ee924709SRui Ueyama // line option is respected even if a SORT command is given, the exact 222ee924709SRui Ueyama // behavior we have here is a bit complicated. Here are the rules. 223ee924709SRui Ueyama // 224ee924709SRui Ueyama // 1. If two SORT commands are given, --sort-section is ignored. 225ee924709SRui Ueyama // 2. If one SORT command is given, and if it is not SORT_NONE, 226ee924709SRui Ueyama // --sort-section is handled as an inner SORT command. 227ee924709SRui Ueyama // 3. If one SORT command is given, and if it is SORT_NONE, don't sort. 228ee924709SRui Ueyama // 4. If no SORT command is given, sort according to --sort-section. 22907171f21SGeorge Rimar InputSectionData **Begin = I->Sections.data() + SizeBefore; 23007171f21SGeorge Rimar InputSectionData **End = I->Sections.data() + I->Sections.size(); 23107171f21SGeorge Rimar if (Pat.SortOuter != SortSectionPolicy::None) { 23207171f21SGeorge Rimar if (Pat.SortInner == SortSectionPolicy::Default) 23307171f21SGeorge Rimar sortSections(Begin, End, Config->SortSection); 234ee924709SRui Ueyama else 23507171f21SGeorge Rimar sortSections(Begin, End, Pat.SortInner); 23607171f21SGeorge Rimar sortSections(Begin, End, Pat.SortOuter); 23707171f21SGeorge Rimar } 238ee924709SRui Ueyama } 239be94e1b6SRafael Espindola } 240be94e1b6SRafael Espindola 241be94e1b6SRafael Espindola template <class ELFT> 242be94e1b6SRafael Espindola void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) { 243be94e1b6SRafael Espindola for (InputSectionBase<ELFT> *S : V) { 244be94e1b6SRafael Espindola S->Live = false; 245be94e1b6SRafael Espindola reportDiscarded(S); 246be94e1b6SRafael Espindola } 247be94e1b6SRafael Espindola } 248be94e1b6SRafael Espindola 24906ae6836SGeorge Rimar template <class ELFT> 2500b9ce6a4SRui Ueyama std::vector<InputSectionBase<ELFT> *> 25106ae6836SGeorge Rimar LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) { 2520b9ce6a4SRui Ueyama std::vector<InputSectionBase<ELFT> *> Ret; 253e7f912cdSRui Ueyama 25406ae6836SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) { 2557c3ff2ebSRafael Espindola auto *Cmd = dyn_cast<InputSectionDescription>(Base.get()); 2567c3ff2ebSRafael Espindola if (!Cmd) 2570b9ce6a4SRui Ueyama continue; 258e71a3f8aSRafael Espindola computeInputSections(Cmd); 259d3190795SRafael Espindola for (InputSectionData *S : Cmd->Sections) 260d3190795SRafael Espindola Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S)); 2610b9ce6a4SRui Ueyama } 262e71a3f8aSRafael Espindola 2630b9ce6a4SRui Ueyama return Ret; 2640b9ce6a4SRui Ueyama } 2650b9ce6a4SRui Ueyama 266e5d3ca50SPetr Hosek template <class ELFT> 26710897f18SRafael Espindola static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C, 26810897f18SRafael Espindola StringRef OutsecName) { 26910897f18SRafael Espindola // When using linker script the merge rules are different. 27010897f18SRafael Espindola // Unfortunately, linker scripts are name based. This means that expressions 27110897f18SRafael Espindola // like *(.foo*) can refer to multiple input sections that would normally be 27210897f18SRafael Espindola // placed in different output sections. We cannot put them in different 27310897f18SRafael Espindola // output sections or we would produce wrong results for 27410897f18SRafael Espindola // start = .; *(.foo.*) end = .; *(.bar) 27510897f18SRafael Espindola // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to 27610897f18SRafael Espindola // another. The problem is that there is no way to layout those output 27710897f18SRafael Espindola // sections such that the .foo sections are the only thing between the 27810897f18SRafael Espindola // start and end symbols. 27910897f18SRafael Espindola 28010897f18SRafael Espindola // An extra annoyance is that we cannot simply disable merging of the contents 28110897f18SRafael Espindola // of SHF_MERGE sections, but our implementation requires one output section 28210897f18SRafael Espindola // per "kind" (string or not, which size/aligment). 28310897f18SRafael Espindola // Fortunately, creating symbols in the middle of a merge section is not 28410897f18SRafael Espindola // supported by bfd or gold, so we can just create multiple section in that 28510897f18SRafael Espindola // case. 28610897f18SRafael Espindola typedef typename ELFT::uint uintX_t; 2871854a8ebSRafael Espindola uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS); 28810897f18SRafael Espindola 28910897f18SRafael Espindola uintX_t Alignment = 0; 29010897f18SRafael Espindola if (isa<MergeInputSection<ELFT>>(C)) 2911854a8ebSRafael Espindola Alignment = std::max<uintX_t>(C->Alignment, C->Entsize); 29210897f18SRafael Espindola 29310897f18SRafael Espindola return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment}; 29410897f18SRafael Espindola } 29510897f18SRafael Espindola 29610897f18SRafael Espindola template <class ELFT> 29720d03194SEugene Leviant void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory, 29820d03194SEugene Leviant InputSectionBase<ELFT> *Sec, 29920d03194SEugene Leviant StringRef Name) { 300e08e78dfSRafael Espindola OutputSectionBase *OutSec; 30128c1597aSRafael Espindola bool IsNew; 30210897f18SRafael Espindola std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec); 30328c1597aSRafael Espindola if (IsNew) 30428c1597aSRafael Espindola OutputSections->push_back(OutSec); 30520d03194SEugene Leviant OutSec->addSection(Sec); 30620d03194SEugene Leviant } 30720d03194SEugene Leviant 30820d03194SEugene Leviant template <class ELFT> 30920d03194SEugene Leviant void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) { 3107c3ff2ebSRafael Espindola for (unsigned I = 0; I < Opt.Commands.size(); ++I) { 3117c3ff2ebSRafael Espindola auto Iter = Opt.Commands.begin() + I; 3127c3ff2ebSRafael Espindola const std::unique_ptr<BaseCommand> &Base1 = *Iter; 3130b1b695aSRui Ueyama 3140b1b695aSRui Ueyama // Handle symbol assignments outside of any output section. 3152ab5f73dSRui Ueyama if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) { 3162ab5f73dSRui Ueyama if (shouldDefine<ELFT>(Cmd)) 317b0de56b5SRafael Espindola addSymbol<ELFT>(Cmd); 3182ab5f73dSRui Ueyama continue; 3192ab5f73dSRui Ueyama } 3200b1b695aSRui Ueyama 32120d03194SEugene Leviant if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) { 32220d03194SEugene Leviant // If we don't have SECTIONS then output sections have already been 323194470cdSGeorge Rimar // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses 32420d03194SEugene Leviant // will not be called, so ASSERT should be evaluated now. 32520d03194SEugene Leviant if (!Opt.HasSections) 32620d03194SEugene Leviant Cmd->Expression(0); 32720d03194SEugene Leviant continue; 32820d03194SEugene Leviant } 3292ab5f73dSRui Ueyama 330ceabe80eSEugene Leviant if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) { 3317bd37870SRafael Espindola std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd); 3327bd37870SRafael Espindola 3330b1b695aSRui Ueyama // The output section name `/DISCARD/' is special. 3340b1b695aSRui Ueyama // Any input section assigned to it is discarded. 33548c3f1ceSRui Ueyama if (Cmd->Name == "/DISCARD/") { 3367bd37870SRafael Espindola discard(V); 33748c3f1ceSRui Ueyama continue; 33848c3f1ceSRui Ueyama } 3390b9ce6a4SRui Ueyama 3400b1b695aSRui Ueyama // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive 3410b1b695aSRui Ueyama // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input 3420b1b695aSRui Ueyama // sections satisfy a given constraint. If not, a directive is handled 3430b1b695aSRui Ueyama // as if it wasn't present from the beginning. 3440b1b695aSRui Ueyama // 3450b1b695aSRui Ueyama // Because we'll iterate over Commands many more times, the easiest 3460b1b695aSRui Ueyama // way to "make it as if it wasn't present" is to just remove it. 3477c3ff2ebSRafael Espindola if (!matchConstraints<ELFT>(V, Cmd->Constraint)) { 3487c3ff2ebSRafael Espindola for (InputSectionBase<ELFT> *S : V) 349f94efdddSRui Ueyama S->Assigned = false; 3507c3ff2ebSRafael Espindola Opt.Commands.erase(Iter); 351dfbbbc86SGeorge Rimar --I; 3527c3ff2ebSRafael Espindola continue; 3537c3ff2ebSRafael Espindola } 3547c3ff2ebSRafael Espindola 3550b1b695aSRui Ueyama // A directive may contain symbol definitions like this: 3560b1b695aSRui Ueyama // ".foo : { ...; bar = .; }". Handle them. 3577c3ff2ebSRafael Espindola for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands) 3587c3ff2ebSRafael Espindola if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) 3597c3ff2ebSRafael Espindola if (shouldDefine<ELFT>(OutCmd)) 3607c3ff2ebSRafael Espindola addSymbol<ELFT>(OutCmd); 3617c3ff2ebSRafael Espindola 3620b1b695aSRui Ueyama // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign 3630b1b695aSRui Ueyama // is given, input sections are aligned to that value, whether the 3640b1b695aSRui Ueyama // given value is larger or smaller than the original section alignment. 3650b1b695aSRui Ueyama if (Cmd->SubalignExpr) { 3660b1b695aSRui Ueyama uint32_t Subalign = Cmd->SubalignExpr(0); 3670b1b695aSRui Ueyama for (InputSectionBase<ELFT> *S : V) 3680b1b695aSRui Ueyama S->Alignment = Subalign; 36920d03194SEugene Leviant } 3700b1b695aSRui Ueyama 3710b1b695aSRui Ueyama // Add input sections to an output section. 3720b1b695aSRui Ueyama for (InputSectionBase<ELFT> *S : V) 3730b1b695aSRui Ueyama addSection(Factory, S, Cmd->Name); 374eea3114fSGeorge Rimar } 37548c3f1ceSRui Ueyama } 376db24d9c3SGeorge Rimar } 377e63d81bdSEugene Leviant 3780b1b695aSRui Ueyama // Add sections that didn't match any sections command. 37920d03194SEugene Leviant template <class ELFT> 38093c64025SGeorge Rimar void LinkerScript<ELFT>::addOrphanSections( 38193c64025SGeorge Rimar OutputSectionFactory<ELFT> &Factory) { 3828c6a5aafSRui Ueyama for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) 3838f9026baSRafael Espindola if (S->Live && !S->OutSec) 38455518e7dSRui Ueyama addSection(Factory, S, getOutputSectionName(S->Name)); 385e63d81bdSEugene Leviant } 386e63d81bdSEugene Leviant 387db741e72SEugene Leviant // Sets value of a section-defined symbol. Two kinds of 388db741e72SEugene Leviant // symbols are processed: synthetic symbols, whose value 389db741e72SEugene Leviant // is an offset from beginning of section and regular 390db741e72SEugene Leviant // symbols whose value is absolute. 391db741e72SEugene Leviant template <class ELFT> 392afaa9343SEugene Leviant static void assignSectionSymbol(SymbolAssignment *Cmd, 393498ed714SRafael Espindola typename ELFT::uint Value) { 394db741e72SEugene Leviant if (!Cmd->Sym) 395db741e72SEugene Leviant return; 396db741e72SEugene Leviant 397*4f2f50dcSRui Ueyama if (auto *Body = dyn_cast<DefinedSynthetic>(Cmd->Sym)) { 398afaa9343SEugene Leviant Body->Section = Cmd->Expression.Section(); 399afaa9343SEugene Leviant Body->Value = Cmd->Expression(Value) - Body->Section->Addr; 400db741e72SEugene Leviant return; 401db741e72SEugene Leviant } 402db741e72SEugene Leviant auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym); 403498ed714SRafael Espindola Body->Value = Cmd->Expression(Value); 404db741e72SEugene Leviant } 405db741e72SEugene Leviant 406e08e78dfSRafael Espindola template <class ELFT> static bool isTbss(OutputSectionBase *Sec) { 40704a2e348SRafael Espindola return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS; 408a940e539SRafael Espindola } 409a940e539SRafael Espindola 410d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) { 411d3190795SRafael Espindola if (!AlreadyOutputIS.insert(S).second) 412ceabe80eSEugene Leviant return; 413e08e78dfSRafael Espindola bool IsTbss = isTbss<ELFT>(CurOutSec); 414d3190795SRafael Espindola 415d3190795SRafael Espindola uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot; 416d3190795SRafael Espindola Pos = alignTo(Pos, S->Alignment); 41704a2e348SRafael Espindola S->OutSecOff = Pos - CurOutSec->Addr; 418d3190795SRafael Espindola Pos += S->getSize(); 419d3190795SRafael Espindola 420d3190795SRafael Espindola // Update output section size after adding each section. This is so that 421d3190795SRafael Espindola // SIZEOF works correctly in the case below: 422d3190795SRafael Espindola // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) } 42304a2e348SRafael Espindola CurOutSec->Size = Pos - CurOutSec->Addr; 424d3190795SRafael Espindola 4257252ae52SRafael Espindola if (IsTbss) 4267252ae52SRafael Espindola ThreadBssOffset = Pos - Dot; 4277252ae52SRafael Espindola else 428d3190795SRafael Espindola Dot = Pos; 4292de509c3SRui Ueyama } 430ceabe80eSEugene Leviant 431d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::flush() { 43265499b90SRafael Espindola if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second) 43365499b90SRafael Espindola return; 43465499b90SRafael Espindola if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) { 435d3190795SRafael Espindola for (InputSection<ELFT> *I : OutSec->Sections) 436d3190795SRafael Espindola output(I); 43765499b90SRafael Espindola } else { 43804a2e348SRafael Espindola Dot += CurOutSec->Size; 439d3190795SRafael Espindola } 440d3190795SRafael Espindola } 44197403d15SEugene Leviant 442d3190795SRafael Espindola template <class ELFT> 443e08e78dfSRafael Espindola void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) { 444d3190795SRafael Espindola if (CurOutSec == Sec) 445d3190795SRafael Espindola return; 446d3190795SRafael Espindola if (AlreadyOutputOS.count(Sec)) 447d3190795SRafael Espindola return; 448d3190795SRafael Espindola 449d3190795SRafael Espindola flush(); 450d3190795SRafael Espindola CurOutSec = Sec; 451d3190795SRafael Espindola 45204a2e348SRafael Espindola Dot = alignTo(Dot, CurOutSec->Addralign); 453e08e78dfSRafael Espindola CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot; 454b71d6f7aSEugene Leviant 455b71d6f7aSEugene Leviant // If neither AT nor AT> is specified for an allocatable section, the linker 456b71d6f7aSEugene Leviant // will set the LMA such that the difference between VMA and LMA for the 457b71d6f7aSEugene Leviant // section is the same as the preceding output section in the same region 458b71d6f7aSEugene Leviant // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html 459b71d6f7aSEugene Leviant CurOutSec->setLMAOffset(LMAOffset); 460d3190795SRafael Espindola } 461d3190795SRafael Espindola 462d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) { 463e38cbab5SGeorge Rimar // This handles the assignments to symbol or to a location counter (.) 464d3190795SRafael Espindola if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) { 46597403d15SEugene Leviant if (AssignCmd->Name == ".") { 46697403d15SEugene Leviant // Update to location counter means update to section size. 46714460e02SGeorge Rimar uintX_t Val = AssignCmd->Expression(Dot); 46814460e02SGeorge Rimar if (Val < Dot) 46914460e02SGeorge Rimar error("unable to move location counter backward for: " + 47014460e02SGeorge Rimar CurOutSec->Name); 47114460e02SGeorge Rimar Dot = Val; 47204a2e348SRafael Espindola CurOutSec->Size = Dot - CurOutSec->Addr; 473d3190795SRafael Espindola return; 47497403d15SEugene Leviant } 475afaa9343SEugene Leviant assignSectionSymbol<ELFT>(AssignCmd, Dot); 476d3190795SRafael Espindola return; 47797403d15SEugene Leviant } 478e38cbab5SGeorge Rimar 479e38cbab5SGeorge Rimar // Handle BYTE(), SHORT(), LONG(), or QUAD(). 480e38cbab5SGeorge Rimar if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) { 48104a2e348SRafael Espindola DataCmd->Offset = Dot - CurOutSec->Addr; 482e38cbab5SGeorge Rimar Dot += DataCmd->Size; 48304a2e348SRafael Espindola CurOutSec->Size = Dot - CurOutSec->Addr; 484e38cbab5SGeorge Rimar return; 485e38cbab5SGeorge Rimar } 486e38cbab5SGeorge Rimar 487b2d99d6aSMeador Inge if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) { 488b2d99d6aSMeador Inge AssertCmd->Expression(Dot); 489b2d99d6aSMeador Inge return; 490b2d99d6aSMeador Inge } 491b2d99d6aSMeador Inge 492e38cbab5SGeorge Rimar // It handles single input section description command, 493e38cbab5SGeorge Rimar // calculates and assigns the offsets for each section and also 494e38cbab5SGeorge Rimar // updates the output section size. 495d3190795SRafael Espindola auto &ICmd = cast<InputSectionDescription>(Base); 496d3190795SRafael Espindola for (InputSectionData *ID : ICmd.Sections) { 4973fb5a6dcSGeorge Rimar // We tentatively added all synthetic sections at the beginning and removed 4983fb5a6dcSGeorge Rimar // empty ones afterwards (because there is no way to know whether they were 4993fb5a6dcSGeorge Rimar // going be empty or not other than actually running linker scripts.) 5003fb5a6dcSGeorge Rimar // We need to ignore remains of empty sections. 5013fb5a6dcSGeorge Rimar if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID)) 5023fb5a6dcSGeorge Rimar if (Sec->empty()) 5033fb5a6dcSGeorge Rimar continue; 5043fb5a6dcSGeorge Rimar 505d3190795SRafael Espindola auto *IB = static_cast<InputSectionBase<ELFT> *>(ID); 506d3190795SRafael Espindola switchTo(IB->OutSec); 507d3190795SRafael Espindola if (auto *I = dyn_cast<InputSection<ELFT>>(IB)) 508d3190795SRafael Espindola output(I); 50965499b90SRafael Espindola else 51065499b90SRafael Espindola flush(); 511ceabe80eSEugene Leviant } 512ceabe80eSEugene Leviant } 513ceabe80eSEugene Leviant 5148f66df92SGeorge Rimar template <class ELFT> 515e08e78dfSRafael Espindola static std::vector<OutputSectionBase *> 516e08e78dfSRafael Espindola findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) { 517e08e78dfSRafael Espindola std::vector<OutputSectionBase *> Ret; 518e08e78dfSRafael Espindola for (OutputSectionBase *Sec : Sections) 5199257764dSEugene Leviant if (Sec->getName() == Name) 520a14b13d8SGeorge Rimar Ret.push_back(Sec); 521a14b13d8SGeorge Rimar return Ret; 5228f66df92SGeorge Rimar } 5238f66df92SGeorge Rimar 5240b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section 5250b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }"). 526d3190795SRafael Espindola template <class ELFT> 527d3190795SRafael Espindola void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) { 528b71d6f7aSEugene Leviant if (Cmd->LMAExpr) 529b71d6f7aSEugene Leviant LMAOffset = Cmd->LMAExpr(Dot) - Dot; 530e08e78dfSRafael Espindola std::vector<OutputSectionBase *> Sections = 531e08e78dfSRafael Espindola findSections<ELFT>(Cmd->Name, *OutputSections); 532d3190795SRafael Espindola if (Sections.empty()) 533d3190795SRafael Espindola return; 534d3190795SRafael Espindola switchTo(Sections[0]); 5350b1b695aSRui Ueyama 536d3190795SRafael Espindola // Find the last section output location. We will output orphan sections 537d3190795SRafael Espindola // there so that end symbols point to the correct location. 538d3190795SRafael Espindola auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(), 539d3190795SRafael Espindola [](const std::unique_ptr<BaseCommand> &Cmd) { 540d3190795SRafael Espindola return !isa<SymbolAssignment>(*Cmd); 541d3190795SRafael Espindola }) 542d3190795SRafael Espindola .base(); 543d3190795SRafael Espindola for (auto I = Cmd->Commands.begin(); I != E; ++I) 544d3190795SRafael Espindola process(**I); 545e08e78dfSRafael Espindola for (OutputSectionBase *Base : Sections) 546d3190795SRafael Espindola switchTo(Base); 5472506cb4dSEugene Leviant flush(); 548b31dd370SGeorge Rimar std::for_each(E, Cmd->Commands.end(), 549b31dd370SGeorge Rimar [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); }); 550d3190795SRafael Espindola } 551d3190795SRafael Espindola 55207fe6129SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() { 5536d38e4dbSRafael Espindola // It is common practice to use very generic linker scripts. So for any 5546d38e4dbSRafael Espindola // given run some of the output sections in the script will be empty. 5556d38e4dbSRafael Espindola // We could create corresponding empty output sections, but that would 5566d38e4dbSRafael Espindola // clutter the output. 5576d38e4dbSRafael Espindola // We instead remove trivially empty sections. The bfd linker seems even 5586d38e4dbSRafael Espindola // more aggressive at removing them. 5596d38e4dbSRafael Espindola auto Pos = std::remove_if( 5606d38e4dbSRafael Espindola Opt.Commands.begin(), Opt.Commands.end(), 5616d38e4dbSRafael Espindola [&](const std::unique_ptr<BaseCommand> &Base) { 5620b1b695aSRui Ueyama if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get())) 5636a53737cSRafael Espindola return findSections<ELFT>(Cmd->Name, *OutputSections).empty(); 5640b1b695aSRui Ueyama return false; 5656d38e4dbSRafael Espindola }); 5666d38e4dbSRafael Espindola Opt.Commands.erase(Pos, Opt.Commands.end()); 56707fe6129SRafael Espindola } 56807fe6129SRafael Espindola 5696a53737cSRafael Espindola static bool isAllSectionDescription(const OutputSectionCommand &Cmd) { 5706a53737cSRafael Espindola for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands) 5716a53737cSRafael Espindola if (!isa<InputSectionDescription>(*I)) 5726a53737cSRafael Espindola return false; 5736a53737cSRafael Espindola return true; 5746a53737cSRafael Espindola } 5756d38e4dbSRafael Espindola 5766a53737cSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() { 5779546fffbSRafael Espindola // If the output section contains only symbol assignments, create a 5789546fffbSRafael Espindola // corresponding output section. The bfd linker seems to only create them if 5799546fffbSRafael Espindola // '.' is assigned to, but creating these section should not have any bad 5809546fffbSRafael Espindola // consequeces and gives us a section to put the symbol in. 5819546fffbSRafael Espindola uintX_t Flags = SHF_ALLOC; 582f93b8c29SRafael Espindola uint32_t Type = SHT_NOBITS; 5839546fffbSRafael Espindola for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 5849546fffbSRafael Espindola auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 5859546fffbSRafael Espindola if (!Cmd) 5869546fffbSRafael Espindola continue; 587e08e78dfSRafael Espindola std::vector<OutputSectionBase *> Secs = 588e08e78dfSRafael Espindola findSections<ELFT>(Cmd->Name, *OutputSections); 5899546fffbSRafael Espindola if (!Secs.empty()) { 59004a2e348SRafael Espindola Flags = Secs[0]->Flags; 59104a2e348SRafael Espindola Type = Secs[0]->Type; 5929546fffbSRafael Espindola continue; 5939546fffbSRafael Espindola } 5949546fffbSRafael Espindola 5956a53737cSRafael Espindola if (isAllSectionDescription(*Cmd)) 5966a53737cSRafael Espindola continue; 5976a53737cSRafael Espindola 59895642b95SRui Ueyama auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags); 5999546fffbSRafael Espindola OutputSections->push_back(OutSec); 6009546fffbSRafael Espindola } 601f7a17448SRafael Espindola } 602f7a17448SRafael Espindola 603f7a17448SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() { 604f7a17448SRafael Espindola placeOrphanSections(); 605f7a17448SRafael Espindola 606f7a17448SRafael Espindola // If output section command doesn't specify any segments, 607f7a17448SRafael Espindola // and we haven't previously assigned any section to segment, 608f7a17448SRafael Espindola // then we simply assign section to the very first load segment. 609f7a17448SRafael Espindola // Below is an example of such linker script: 610f7a17448SRafael Espindola // PHDRS { seg PT_LOAD; } 611f7a17448SRafael Espindola // SECTIONS { .aaa : { *(.aaa) } } 612f7a17448SRafael Espindola std::vector<StringRef> DefPhdrs; 613f7a17448SRafael Espindola auto FirstPtLoad = 614f7a17448SRafael Espindola std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(), 615f7a17448SRafael Espindola [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; }); 616f7a17448SRafael Espindola if (FirstPtLoad != Opt.PhdrsCommands.end()) 617f7a17448SRafael Espindola DefPhdrs.push_back(FirstPtLoad->Name); 618f7a17448SRafael Espindola 619f7a17448SRafael Espindola // Walk the commands and propagate the program headers to commands that don't 620f7a17448SRafael Espindola // explicitly specify them. 621f7a17448SRafael Espindola for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 622f7a17448SRafael Espindola auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 623f7a17448SRafael Espindola if (!Cmd) 624f7a17448SRafael Espindola continue; 625f7a17448SRafael Espindola if (Cmd->Phdrs.empty()) 626f7a17448SRafael Espindola Cmd->Phdrs = DefPhdrs; 627f7a17448SRafael Espindola else 628f7a17448SRafael Espindola DefPhdrs = Cmd->Phdrs; 629f7a17448SRafael Espindola } 6306a53737cSRafael Espindola 6316a53737cSRafael Espindola removeEmptyCommands(); 6329546fffbSRafael Espindola } 6339546fffbSRafael Espindola 63415c57951SRafael Espindola // When placing orphan sections, we want to place them after symbol assignments 63515c57951SRafael Espindola // so that an orphan after 63615c57951SRafael Espindola // begin_foo = .; 63715c57951SRafael Espindola // foo : { *(foo) } 63815c57951SRafael Espindola // end_foo = .; 63915c57951SRafael Espindola // doesn't break the intended meaning of the begin/end symbols. 64015c57951SRafael Espindola // We don't want to go over sections since Writer<ELFT>::sortSections is the 64115c57951SRafael Espindola // one in charge of deciding the order of the sections. 64215c57951SRafael Espindola // We don't want to go over alignments, since doing so in 64315c57951SRafael Espindola // rx_sec : { *(rx_sec) } 64415c57951SRafael Espindola // . = ALIGN(0x1000); 64515c57951SRafael Espindola // /* The RW PT_LOAD starts here*/ 64615c57951SRafael Espindola // rw_sec : { *(rw_sec) } 64715c57951SRafael Espindola // would mean that the RW PT_LOAD would become unaligned. 6485fcc99c2SRafael Espindola static bool shouldSkip(const BaseCommand &Cmd) { 64915c57951SRafael Espindola if (isa<OutputSectionCommand>(Cmd)) 65015c57951SRafael Espindola return false; 65115c57951SRafael Espindola const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd); 65215c57951SRafael Espindola if (!Assign) 65315c57951SRafael Espindola return true; 6545fcc99c2SRafael Espindola return Assign->Name != "."; 65515c57951SRafael Espindola } 65615c57951SRafael Espindola 657337f903cSRafael Espindola // Orphan sections are sections present in the input files which are not 658337f903cSRafael Espindola // explicitly placed into the output file by the linker script. This just 659337f903cSRafael Espindola // places them in the order already decided in OutputSections. 66093c64025SGeorge Rimar template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() { 661aab6d5c5SRafael Espindola // The OutputSections are already in the correct order. 662aab6d5c5SRafael Espindola // This loops creates or moves commands as needed so that they are in the 663aab6d5c5SRafael Espindola // correct order. 664aab6d5c5SRafael Espindola int CmdIndex = 0; 6655fcc99c2SRafael Espindola 6665fcc99c2SRafael Espindola // As a horrible special case, skip the first . assignment if it is before any 6675fcc99c2SRafael Espindola // section. We do this because it is common to set a load address by starting 6685fcc99c2SRafael Espindola // the script with ". = 0xabcd" and the expectation is that every section is 6695fcc99c2SRafael Espindola // after that. 6705fcc99c2SRafael Espindola auto FirstSectionOrDotAssignment = 6715fcc99c2SRafael Espindola std::find_if(Opt.Commands.begin(), Opt.Commands.end(), 6725fcc99c2SRafael Espindola [](const std::unique_ptr<BaseCommand> &Cmd) { 6735fcc99c2SRafael Espindola if (isa<OutputSectionCommand>(*Cmd)) 6745fcc99c2SRafael Espindola return true; 6755fcc99c2SRafael Espindola const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get()); 6765fcc99c2SRafael Espindola if (!Assign) 6775fcc99c2SRafael Espindola return false; 6785fcc99c2SRafael Espindola return Assign->Name == "."; 6795fcc99c2SRafael Espindola }); 6805fcc99c2SRafael Espindola if (FirstSectionOrDotAssignment != Opt.Commands.end()) { 6815fcc99c2SRafael Espindola CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin(); 6825fcc99c2SRafael Espindola if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment)) 6835fcc99c2SRafael Espindola ++CmdIndex; 6845fcc99c2SRafael Espindola } 6855fcc99c2SRafael Espindola 686e08e78dfSRafael Espindola for (OutputSectionBase *Sec : *OutputSections) { 687652852c5SGeorge Rimar StringRef Name = Sec->getName(); 688aab6d5c5SRafael Espindola 689aab6d5c5SRafael Espindola // Find the last spot where we can insert a command and still get the 69015c57951SRafael Espindola // correct result. 691aab6d5c5SRafael Espindola auto CmdIter = Opt.Commands.begin() + CmdIndex; 692aab6d5c5SRafael Espindola auto E = Opt.Commands.end(); 6935fcc99c2SRafael Espindola while (CmdIter != E && shouldSkip(**CmdIter)) { 694aab6d5c5SRafael Espindola ++CmdIter; 695aab6d5c5SRafael Espindola ++CmdIndex; 696aab6d5c5SRafael Espindola } 697aab6d5c5SRafael Espindola 698aab6d5c5SRafael Espindola auto Pos = 699aab6d5c5SRafael Espindola std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) { 700aab6d5c5SRafael Espindola auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 701aab6d5c5SRafael Espindola return Cmd && Cmd->Name == Name; 702aab6d5c5SRafael Espindola }); 703aab6d5c5SRafael Espindola if (Pos == E) { 704aab6d5c5SRafael Espindola Opt.Commands.insert(CmdIter, 705aab6d5c5SRafael Espindola llvm::make_unique<OutputSectionCommand>(Name)); 706aab6d5c5SRafael Espindola ++CmdIndex; 70715c57951SRafael Espindola continue; 70815c57951SRafael Espindola } 70915c57951SRafael Espindola 71015c57951SRafael Espindola // Continue from where we found it. 71115c57951SRafael Espindola CmdIndex = (Pos - Opt.Commands.begin()) + 1; 712652852c5SGeorge Rimar } 713337f903cSRafael Espindola } 714337f903cSRafael Espindola 715337f903cSRafael Espindola template <class ELFT> 71617cb7c0aSRafael Espindola void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) { 7177c18c28cSRui Ueyama // Assign addresses as instructed by linker script SECTIONS sub-commands. 718be607334SRafael Espindola Dot = 0; 719652852c5SGeorge Rimar 720076fe157SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 721076fe157SGeorge Rimar if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) { 7228d083e6aSRui Ueyama if (Cmd->Name == ".") { 7238d083e6aSRui Ueyama Dot = Cmd->Expression(Dot); 7248d083e6aSRui Ueyama } else if (Cmd->Sym) { 725afaa9343SEugene Leviant assignSectionSymbol<ELFT>(Cmd, Dot); 7268d083e6aSRui Ueyama } 72705ef4cffSRui Ueyama continue; 728652852c5SGeorge Rimar } 729652852c5SGeorge Rimar 730eefa758eSGeorge Rimar if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) { 731eefa758eSGeorge Rimar Cmd->Expression(Dot); 732eefa758eSGeorge Rimar continue; 733eefa758eSGeorge Rimar } 734eefa758eSGeorge Rimar 735076fe157SGeorge Rimar auto *Cmd = cast<OutputSectionCommand>(Base.get()); 73658e5c4dcSGeorge Rimar if (Cmd->AddrExpr) 73758e5c4dcSGeorge Rimar Dot = Cmd->AddrExpr(Dot); 738d3190795SRafael Espindola assignOffsets(Cmd); 739a14b13d8SGeorge Rimar } 740467c4d55SEugene Leviant 741aab6d5c5SRafael Espindola uintX_t MinVA = std::numeric_limits<uintX_t>::max(); 742e08e78dfSRafael Espindola for (OutputSectionBase *Sec : *OutputSections) { 74304a2e348SRafael Espindola if (Sec->Flags & SHF_ALLOC) 744e08e78dfSRafael Espindola MinVA = std::min<uint64_t>(MinVA, Sec->Addr); 745aab6d5c5SRafael Espindola else 74604a2e348SRafael Espindola Sec->Addr = 0; 747aab6d5c5SRafael Espindola } 748aab6d5c5SRafael Espindola 7490d4b6d5cSRafael Espindola uintX_t HeaderSize = getHeaderSize(); 7501c57007eSRafael Espindola // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders 7511c57007eSRafael Espindola // now that we know we have space. 7525967c973SRafael Espindola if (HeaderSize <= MinVA && !hasPhdrsCommands()) 7535967c973SRafael Espindola allocateHeaders<ELFT>(Phdrs, *OutputSections); 7541c57007eSRafael Espindola 75564c32d6fSRafael Espindola // ELF and Program headers need to be right before the first section in 756b91e7118SGeorge Rimar // memory. Set their addresses accordingly. 75728d5f059SRafael Espindola MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize); 75804a2e348SRafael Espindola Out<ELFT>::ElfHeader->Addr = MinVA; 75904a2e348SRafael Espindola Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA; 760fb8978fcSDima Stepanov } 761652852c5SGeorge Rimar 762464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command. 76317cb7c0aSRafael Espindola template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() { 76417cb7c0aSRafael Espindola std::vector<PhdrEntry> Ret; 765bbe38602SEugene Leviant 766464daadcSRui Ueyama // Process PHDRS and FILEHDR keywords because they are not 767464daadcSRui Ueyama // real output sections and cannot be added in the following loop. 768bbe38602SEugene Leviant for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) { 769edebbdf1SRui Ueyama Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags); 77017cb7c0aSRafael Espindola PhdrEntry &Phdr = Ret.back(); 771bbe38602SEugene Leviant 772bbe38602SEugene Leviant if (Cmd.HasFilehdr) 773adca245fSRui Ueyama Phdr.add(Out<ELFT>::ElfHeader); 774bbe38602SEugene Leviant if (Cmd.HasPhdrs) 775adca245fSRui Ueyama Phdr.add(Out<ELFT>::ProgramHeaders); 77656b21c86SEugene Leviant 77756b21c86SEugene Leviant if (Cmd.LMAExpr) { 77817cb7c0aSRafael Espindola Phdr.p_paddr = Cmd.LMAExpr(0); 77956b21c86SEugene Leviant Phdr.HasLMA = true; 78056b21c86SEugene Leviant } 781bbe38602SEugene Leviant } 782bbe38602SEugene Leviant 783464daadcSRui Ueyama // Add output sections to program headers. 784e08e78dfSRafael Espindola for (OutputSectionBase *Sec : *OutputSections) { 78504a2e348SRafael Espindola if (!(Sec->Flags & SHF_ALLOC)) 786bbe38602SEugene Leviant break; 787bbe38602SEugene Leviant 788bbe38602SEugene Leviant // Assign headers specified by linker script 789f7a17448SRafael Espindola for (size_t Id : getPhdrIndices(Sec->getName())) { 790edebbdf1SRui Ueyama Ret[Id].add(Sec); 791865bf863SEugene Leviant if (Opt.PhdrsCommands[Id].Flags == UINT_MAX) 79217cb7c0aSRafael Espindola Ret[Id].p_flags |= Sec->getPhdrFlags(); 793bbe38602SEugene Leviant } 794bbe38602SEugene Leviant } 795edebbdf1SRui Ueyama return Ret; 796bbe38602SEugene Leviant } 797bbe38602SEugene Leviant 798f9bc3bd2SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() { 799f9bc3bd2SEugene Leviant // Ignore .interp section in case we have PHDRS specification 800f9bc3bd2SEugene Leviant // and PT_INTERP isn't listed. 801f9bc3bd2SEugene Leviant return !Opt.PhdrsCommands.empty() && 802f9bc3bd2SEugene Leviant llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) { 803f9bc3bd2SEugene Leviant return Cmd.Type == PT_INTERP; 804f9bc3bd2SEugene Leviant }) == Opt.PhdrsCommands.end(); 805f9bc3bd2SEugene Leviant } 806f9bc3bd2SEugene Leviant 80793c64025SGeorge Rimar template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) { 808f6c3ccefSGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) 809f6c3ccefSGeorge Rimar if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get())) 810f6c3ccefSGeorge Rimar if (Cmd->Name == Name) 811f6c3ccefSGeorge Rimar return Cmd->Filler; 81216068aebSRui Ueyama return 0; 813e2ee72b5SGeorge Rimar } 814e2ee72b5SGeorge Rimar 815e38cbab5SGeorge Rimar template <class ELFT> 816e38cbab5SGeorge Rimar static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) { 817e38cbab5SGeorge Rimar const endianness E = ELFT::TargetEndianness; 818e38cbab5SGeorge Rimar 819e38cbab5SGeorge Rimar switch (Size) { 820e38cbab5SGeorge Rimar case 1: 821e38cbab5SGeorge Rimar *Buf = (uint8_t)Data; 822e38cbab5SGeorge Rimar break; 823e38cbab5SGeorge Rimar case 2: 824e38cbab5SGeorge Rimar write16<E>(Buf, Data); 825e38cbab5SGeorge Rimar break; 826e38cbab5SGeorge Rimar case 4: 827e38cbab5SGeorge Rimar write32<E>(Buf, Data); 828e38cbab5SGeorge Rimar break; 829e38cbab5SGeorge Rimar case 8: 830e38cbab5SGeorge Rimar write64<E>(Buf, Data); 831e38cbab5SGeorge Rimar break; 832e38cbab5SGeorge Rimar default: 833e38cbab5SGeorge Rimar llvm_unreachable("unsupported Size argument"); 834e38cbab5SGeorge Rimar } 835e38cbab5SGeorge Rimar } 836e38cbab5SGeorge Rimar 837e38cbab5SGeorge Rimar template <class ELFT> 838e38cbab5SGeorge Rimar void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) { 839e38cbab5SGeorge Rimar int I = getSectionIndex(Name); 840e38cbab5SGeorge Rimar if (I == INT_MAX) 841e38cbab5SGeorge Rimar return; 842e38cbab5SGeorge Rimar 8436e68c5e5SRui Ueyama auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()); 8446e68c5e5SRui Ueyama for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands) 8456e68c5e5SRui Ueyama if (auto *Data = dyn_cast<BytesDataCommand>(Base.get())) 84695c7d8d2SMeador Inge writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size); 847e38cbab5SGeorge Rimar } 848e38cbab5SGeorge Rimar 849b71d6f7aSEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) { 8508ceadb38SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) 8518ceadb38SGeorge Rimar if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get())) 852b71d6f7aSEugene Leviant if (Cmd->LMAExpr && Cmd->Name == Name) 853b71d6f7aSEugene Leviant return true; 854b71d6f7aSEugene Leviant return false; 8558ceadb38SGeorge Rimar } 8568ceadb38SGeorge Rimar 857c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script 858c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they 859c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script, 860c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file. 861076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) { 8626e68c5e5SRui Ueyama for (int I = 0, E = Opt.Commands.size(); I != E; ++I) 8636e68c5e5SRui Ueyama if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get())) 864076fe157SGeorge Rimar if (Cmd->Name == Name) 865f510fa6bSRui Ueyama return I; 866f510fa6bSRui Ueyama return INT_MAX; 86771b26e94SGeorge Rimar } 86871b26e94SGeorge Rimar 869bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() { 870bbe38602SEugene Leviant return !Opt.PhdrsCommands.empty(); 871bbe38602SEugene Leviant } 872bbe38602SEugene Leviant 8739e69450eSGeorge Rimar template <class ELFT> 874ed30ce7aSEugene Leviant const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc, 875ed30ce7aSEugene Leviant StringRef Name) { 876afaa9343SEugene Leviant static OutputSectionBase FakeSec("", 0, 0); 87796659df0SGeorge Rimar 878e08e78dfSRafael Espindola for (OutputSectionBase *Sec : *OutputSections) 879b71d6f7aSEugene Leviant if (Sec->getName() == Name) 880afaa9343SEugene Leviant return Sec; 881ed30ce7aSEugene Leviant 882ed30ce7aSEugene Leviant error(Loc + ": undefined section " + Name); 883afaa9343SEugene Leviant return &FakeSec; 88436fac7f0SEugene Leviant } 88536fac7f0SEugene Leviant 886edf75e79SRui Ueyama // This function is essentially the same as getOutputSection(Name)->Size, 887edf75e79SRui Ueyama // but it won't print out an error message if a given section is not found. 888edf75e79SRui Ueyama // 889edf75e79SRui Ueyama // Linker script does not create an output section if its content is empty. 890edf75e79SRui Ueyama // We want to allow SIZEOF(.foo) where .foo is a section which happened to 891edf75e79SRui Ueyama // be empty. That is why this function is different from getOutputSection(). 892edf75e79SRui Ueyama template <class ELFT> 893edf75e79SRui Ueyama uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) { 894edf75e79SRui Ueyama for (OutputSectionBase *Sec : *OutputSections) 895edf75e79SRui Ueyama if (Sec->getName() == Name) 896edf75e79SRui Ueyama return Sec->Size; 897edf75e79SRui Ueyama return 0; 898edf75e79SRui Ueyama } 899edf75e79SRui Ueyama 900884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() { 9010d4b6d5cSRafael Espindola return elf::getHeaderSize<ELFT>(); 902e32a3598SGeorge Rimar } 903e32a3598SGeorge Rimar 904884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) { 905884e786dSGeorge Rimar if (SymbolBody *B = Symtab<ELFT>::X->find(S)) 906884e786dSGeorge Rimar return B->getVA<ELFT>(); 907884e786dSGeorge Rimar error("symbol not found: " + S); 908884e786dSGeorge Rimar return 0; 909884e786dSGeorge Rimar } 910884e786dSGeorge Rimar 911f34f45fdSGeorge Rimar template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) { 912f34f45fdSGeorge Rimar return Symtab<ELFT>::X->find(S) != nullptr; 913f34f45fdSGeorge Rimar } 914f34f45fdSGeorge Rimar 9152f831dcaSRafael Espindola template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) { 9162f831dcaSRafael Espindola SymbolBody *Sym = Symtab<ELFT>::X->find(S); 9172f831dcaSRafael Espindola auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym); 9182f831dcaSRafael Espindola return DR && !DR->Section; 9192f831dcaSRafael Espindola } 9202f831dcaSRafael Espindola 921afaa9343SEugene Leviant // Gets section symbol belongs to. Symbol "." doesn't belong to any 922afaa9343SEugene Leviant // specific section but isn't absolute at the same time, so we try 923afaa9343SEugene Leviant // to find suitable section for it as well. 924afaa9343SEugene Leviant template <class ELFT> 925afaa9343SEugene Leviant const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) { 926afaa9343SEugene Leviant SymbolBody *Sym = Symtab<ELFT>::X->find(S); 927afaa9343SEugene Leviant if (!Sym) { 928afaa9343SEugene Leviant if (OutputSections->empty()) 929afaa9343SEugene Leviant return nullptr; 930afaa9343SEugene Leviant return CurOutSec ? CurOutSec : (*OutputSections)[0]; 931afaa9343SEugene Leviant } 932afaa9343SEugene Leviant 933afaa9343SEugene Leviant if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym)) 934afaa9343SEugene Leviant return DR->Section ? DR->Section->OutSec : nullptr; 935*4f2f50dcSRui Ueyama if (auto *DS = dyn_cast_or_null<DefinedSynthetic>(Sym)) 936afaa9343SEugene Leviant return DS->Section; 937afaa9343SEugene Leviant 938afaa9343SEugene Leviant return nullptr; 939afaa9343SEugene Leviant } 940afaa9343SEugene Leviant 941bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified 942bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within 943bbe38602SEugene Leviant // PHDRS {} script block. 944bbe38602SEugene Leviant template <class ELFT> 945edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) { 946076fe157SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 947076fe157SGeorge Rimar auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 948edebbdf1SRui Ueyama if (!Cmd || Cmd->Name != SectionName) 94931d842f5SGeorge Rimar continue; 95031d842f5SGeorge Rimar 95129c5a2a9SRui Ueyama std::vector<size_t> Ret; 95229c5a2a9SRui Ueyama for (StringRef PhdrName : Cmd->Phdrs) 9532a942c4bSEugene Leviant Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName)); 95429c5a2a9SRui Ueyama return Ret; 955bbe38602SEugene Leviant } 95631d842f5SGeorge Rimar return {}; 95731d842f5SGeorge Rimar } 958bbe38602SEugene Leviant 95929c5a2a9SRui Ueyama template <class ELFT> 9602a942c4bSEugene Leviant size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) { 96129c5a2a9SRui Ueyama size_t I = 0; 96229c5a2a9SRui Ueyama for (PhdrsCommand &Cmd : Opt.PhdrsCommands) { 96329c5a2a9SRui Ueyama if (Cmd.Name == PhdrName) 96429c5a2a9SRui Ueyama return I; 96529c5a2a9SRui Ueyama ++I; 96629c5a2a9SRui Ueyama } 9672a942c4bSEugene Leviant error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS"); 96829c5a2a9SRui Ueyama return 0; 96929c5a2a9SRui Ueyama } 97029c5a2a9SRui Ueyama 97103ff0166SEugene Leviant class elf::ScriptParser final : public ScriptParserBase { 972c3794e58SGeorge Rimar typedef void (ScriptParser::*Handler)(); 973c3794e58SGeorge Rimar 974f7c5fbb1SRui Ueyama public: 97522375f24SRui Ueyama ScriptParser(MemoryBufferRef MB) 97622375f24SRui Ueyama : ScriptParserBase(MB), 97722375f24SRui Ueyama IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {} 978f23b2320SGeorge Rimar 97920b6598cSGeorge Rimar void readLinkerScript(); 98020b6598cSGeorge Rimar void readVersionScript(); 981d0ebd84cSRafael Espindola void readDynamicList(); 982f7c5fbb1SRui Ueyama 983f7c5fbb1SRui Ueyama private: 98452a1509eSRui Ueyama void addFile(StringRef Path); 98552a1509eSRui Ueyama 986f7c5fbb1SRui Ueyama void readAsNeeded(); 98790c5099eSDenis Protivensky void readEntry(); 98883f406cfSGeorge Rimar void readExtern(); 989f7c5fbb1SRui Ueyama void readGroup(); 99031aa1f83SRui Ueyama void readInclude(); 991ee59282bSRui Ueyama void readOutput(); 9929159ce93SDavide Italiano void readOutputArch(); 993f7c5fbb1SRui Ueyama void readOutputFormat(); 994bbe38602SEugene Leviant void readPhdrs(); 99568a39a65SDavide Italiano void readSearchDir(); 9968e3b38abSDenis Protivensky void readSections(); 99795769b4aSRui Ueyama void readVersion(); 99895769b4aSRui Ueyama void readVersionScriptCommand(); 9998e3b38abSDenis Protivensky 1000113cdec9SRui Ueyama SymbolAssignment *readAssignment(StringRef Name); 1001e38cbab5SGeorge Rimar BytesDataCommand *readBytesDataCommand(StringRef Tok); 100216068aebSRui Ueyama uint32_t readFill(); 100310416564SRui Ueyama OutputSectionCommand *readOutputSectionDescription(StringRef OutSec); 100416068aebSRui Ueyama uint32_t readOutputSectionFiller(StringRef Tok); 1005bbe38602SEugene Leviant std::vector<StringRef> readOutputSectionPhdrs(); 1006a2496cbeSGeorge Rimar InputSectionDescription *readInputSectionDescription(StringRef Tok); 1007db688454SEugene Leviant StringMatcher readFilePatterns(); 100807171f21SGeorge Rimar std::vector<SectionPattern> readInputSectionsList(); 1009a2496cbeSGeorge Rimar InputSectionDescription *readInputSectionRules(StringRef FilePattern); 1010bbe38602SEugene Leviant unsigned readPhdrType(); 1011be394db3SGeorge Rimar SortSectionPolicy readSortKind(); 1012a35e39caSPetr Hosek SymbolAssignment *readProvideHidden(bool Provide, bool Hidden); 1013c96da110SRafael Espindola SymbolAssignment *readProvideOrAssignment(StringRef Tok); 101403fc010eSGeorge Rimar void readSort(); 1015eefa758eSGeorge Rimar Expr readAssert(); 1016708019c4SRui Ueyama 1017708019c4SRui Ueyama Expr readExpr(); 1018708019c4SRui Ueyama Expr readExpr1(Expr Lhs, int MinPrec); 1019b71d6f7aSEugene Leviant StringRef readParenLiteral(); 1020708019c4SRui Ueyama Expr readPrimary(); 1021708019c4SRui Ueyama Expr readTernary(Expr Cond); 10226ad7dfccSRui Ueyama Expr readParenExpr(); 1023f7c5fbb1SRui Ueyama 102420b6598cSGeorge Rimar // For parsing version script. 102512450b20SRui Ueyama std::vector<SymbolVersion> readVersionExtern(); 102612450b20SRui Ueyama void readAnonymousDeclaration(); 102795769b4aSRui Ueyama void readVersionDeclaration(StringRef VerStr); 102812450b20SRui Ueyama std::vector<SymbolVersion> readSymbols(); 102920b6598cSGeorge Rimar 103007320e40SRui Ueyama ScriptConfiguration &Opt = *ScriptConfig; 103116b0cc9eSSimon Atanasyan bool IsUnderSysroot; 1032f7c5fbb1SRui Ueyama }; 1033f7c5fbb1SRui Ueyama 1034d0ebd84cSRafael Espindola void ScriptParser::readDynamicList() { 1035d0ebd84cSRafael Espindola expect("{"); 1036d0ebd84cSRafael Espindola readAnonymousDeclaration(); 1037d0ebd84cSRafael Espindola if (!atEOF()) 1038d0ebd84cSRafael Espindola setError("EOF expected, but got " + next()); 1039d0ebd84cSRafael Espindola } 1040d0ebd84cSRafael Espindola 104120b6598cSGeorge Rimar void ScriptParser::readVersionScript() { 104295769b4aSRui Ueyama readVersionScriptCommand(); 104320b6598cSGeorge Rimar if (!atEOF()) 104495769b4aSRui Ueyama setError("EOF expected, but got " + next()); 104595769b4aSRui Ueyama } 104695769b4aSRui Ueyama 104795769b4aSRui Ueyama void ScriptParser::readVersionScriptCommand() { 104883043f23SRui Ueyama if (consume("{")) { 104912450b20SRui Ueyama readAnonymousDeclaration(); 105020b6598cSGeorge Rimar return; 105120b6598cSGeorge Rimar } 105220b6598cSGeorge Rimar 105395769b4aSRui Ueyama while (!atEOF() && !Error && peek() != "}") { 105420b6598cSGeorge Rimar StringRef VerStr = next(); 105520b6598cSGeorge Rimar if (VerStr == "{") { 105695769b4aSRui Ueyama setError("anonymous version definition is used in " 105795769b4aSRui Ueyama "combination with other version definitions"); 105820b6598cSGeorge Rimar return; 105920b6598cSGeorge Rimar } 106020b6598cSGeorge Rimar expect("{"); 106195769b4aSRui Ueyama readVersionDeclaration(VerStr); 106220b6598cSGeorge Rimar } 106320b6598cSGeorge Rimar } 106420b6598cSGeorge Rimar 106595769b4aSRui Ueyama void ScriptParser::readVersion() { 106695769b4aSRui Ueyama expect("{"); 106795769b4aSRui Ueyama readVersionScriptCommand(); 106895769b4aSRui Ueyama expect("}"); 106995769b4aSRui Ueyama } 107095769b4aSRui Ueyama 107120b6598cSGeorge Rimar void ScriptParser::readLinkerScript() { 1072f7c5fbb1SRui Ueyama while (!atEOF()) { 1073f7c5fbb1SRui Ueyama StringRef Tok = next(); 1074a27eeccaSRui Ueyama if (Tok == ";") 1075a27eeccaSRui Ueyama continue; 1076a27eeccaSRui Ueyama 107720d03194SEugene Leviant if (Tok == "ASSERT") { 107820d03194SEugene Leviant Opt.Commands.emplace_back(new AssertCommand(readAssert())); 107920d03194SEugene Leviant } else if (Tok == "ENTRY") { 1080a27eeccaSRui Ueyama readEntry(); 1081a27eeccaSRui Ueyama } else if (Tok == "EXTERN") { 1082a27eeccaSRui Ueyama readExtern(); 1083a27eeccaSRui Ueyama } else if (Tok == "GROUP" || Tok == "INPUT") { 1084a27eeccaSRui Ueyama readGroup(); 1085a27eeccaSRui Ueyama } else if (Tok == "INCLUDE") { 1086a27eeccaSRui Ueyama readInclude(); 1087a27eeccaSRui Ueyama } else if (Tok == "OUTPUT") { 1088a27eeccaSRui Ueyama readOutput(); 1089a27eeccaSRui Ueyama } else if (Tok == "OUTPUT_ARCH") { 1090a27eeccaSRui Ueyama readOutputArch(); 1091a27eeccaSRui Ueyama } else if (Tok == "OUTPUT_FORMAT") { 1092a27eeccaSRui Ueyama readOutputFormat(); 1093a27eeccaSRui Ueyama } else if (Tok == "PHDRS") { 1094a27eeccaSRui Ueyama readPhdrs(); 1095a27eeccaSRui Ueyama } else if (Tok == "SEARCH_DIR") { 1096a27eeccaSRui Ueyama readSearchDir(); 1097a27eeccaSRui Ueyama } else if (Tok == "SECTIONS") { 1098a27eeccaSRui Ueyama readSections(); 1099a27eeccaSRui Ueyama } else if (Tok == "VERSION") { 1100a27eeccaSRui Ueyama readVersion(); 1101c96da110SRafael Espindola } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) { 11020df80befSPetr Hosek Opt.Commands.emplace_back(Cmd); 1103e5d3ca50SPetr Hosek } else { 11045761042dSGeorge Rimar setError("unknown directive: " + Tok); 1105f7c5fbb1SRui Ueyama } 1106f7c5fbb1SRui Ueyama } 1107e5d3ca50SPetr Hosek } 1108f7c5fbb1SRui Ueyama 1109717677afSRui Ueyama void ScriptParser::addFile(StringRef S) { 111016b0cc9eSSimon Atanasyan if (IsUnderSysroot && S.startswith("/")) { 11115af1687fSJustin Bogner SmallString<128> PathData; 11125af1687fSJustin Bogner StringRef Path = (Config->Sysroot + S).toStringRef(PathData); 111316b0cc9eSSimon Atanasyan if (sys::fs::exists(Path)) { 11145af1687fSJustin Bogner Driver->addFile(Saver.save(Path)); 111516b0cc9eSSimon Atanasyan return; 111616b0cc9eSSimon Atanasyan } 111716b0cc9eSSimon Atanasyan } 111816b0cc9eSSimon Atanasyan 1119f03f3cc1SRui Ueyama if (sys::path::is_absolute(S)) { 112052a1509eSRui Ueyama Driver->addFile(S); 112152a1509eSRui Ueyama } else if (S.startswith("=")) { 112252a1509eSRui Ueyama if (Config->Sysroot.empty()) 112352a1509eSRui Ueyama Driver->addFile(S.substr(1)); 112452a1509eSRui Ueyama else 112552a1509eSRui Ueyama Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1))); 112652a1509eSRui Ueyama } else if (S.startswith("-l")) { 112721eecb4fSRui Ueyama Driver->addLibrary(S.substr(2)); 1128a1b8fc3bSSimon Atanasyan } else if (sys::fs::exists(S)) { 1129a1b8fc3bSSimon Atanasyan Driver->addFile(S); 113052a1509eSRui Ueyama } else { 1131061f9286SRui Ueyama if (Optional<std::string> Path = findFromSearchPaths(S)) 1132061f9286SRui Ueyama Driver->addFile(Saver.save(*Path)); 1133025d59b1SRui Ueyama else 1134061f9286SRui Ueyama setError("unable to find " + S); 113552a1509eSRui Ueyama } 113652a1509eSRui Ueyama } 113752a1509eSRui Ueyama 1138717677afSRui Ueyama void ScriptParser::readAsNeeded() { 1139f7c5fbb1SRui Ueyama expect("("); 114035da9b6eSRui Ueyama bool Orig = Config->AsNeeded; 114135da9b6eSRui Ueyama Config->AsNeeded = true; 114283043f23SRui Ueyama while (!Error && !consume(")")) 1143cd574a5eSGeorge Rimar addFile(unquote(next())); 114435da9b6eSRui Ueyama Config->AsNeeded = Orig; 1145f7c5fbb1SRui Ueyama } 1146f7c5fbb1SRui Ueyama 1147717677afSRui Ueyama void ScriptParser::readEntry() { 114890c5099eSDenis Protivensky // -e <symbol> takes predecence over ENTRY(<symbol>). 114990c5099eSDenis Protivensky expect("("); 115090c5099eSDenis Protivensky StringRef Tok = next(); 115190c5099eSDenis Protivensky if (Config->Entry.empty()) 115290c5099eSDenis Protivensky Config->Entry = Tok; 115390c5099eSDenis Protivensky expect(")"); 115490c5099eSDenis Protivensky } 115590c5099eSDenis Protivensky 1156717677afSRui Ueyama void ScriptParser::readExtern() { 115783f406cfSGeorge Rimar expect("("); 115883043f23SRui Ueyama while (!Error && !consume(")")) 1159a2acc931SRui Ueyama Config->Undefined.push_back(next()); 116083f406cfSGeorge Rimar } 116183f406cfSGeorge Rimar 1162717677afSRui Ueyama void ScriptParser::readGroup() { 1163f7c5fbb1SRui Ueyama expect("("); 116483043f23SRui Ueyama while (!Error && !consume(")")) { 1165f7c5fbb1SRui Ueyama StringRef Tok = next(); 1166a2acc931SRui Ueyama if (Tok == "AS_NEEDED") 1167f7c5fbb1SRui Ueyama readAsNeeded(); 1168a2acc931SRui Ueyama else 1169cd574a5eSGeorge Rimar addFile(unquote(Tok)); 1170f7c5fbb1SRui Ueyama } 1171f7c5fbb1SRui Ueyama } 1172f7c5fbb1SRui Ueyama 1173717677afSRui Ueyama void ScriptParser::readInclude() { 117431aa1f83SRui Ueyama StringRef Tok = next(); 1175cd574a5eSGeorge Rimar auto MBOrErr = MemoryBuffer::getFile(unquote(Tok)); 1176025d59b1SRui Ueyama if (!MBOrErr) { 11775761042dSGeorge Rimar setError("cannot open " + Tok); 1178025d59b1SRui Ueyama return; 1179025d59b1SRui Ueyama } 118031aa1f83SRui Ueyama std::unique_ptr<MemoryBuffer> &MB = *MBOrErr; 11814fb6e79cSGeorge Rimar tokenize({Saver.save(MB->getBuffer()), unquote(Tok)}); 118231aa1f83SRui Ueyama } 118331aa1f83SRui Ueyama 1184717677afSRui Ueyama void ScriptParser::readOutput() { 1185ee59282bSRui Ueyama // -o <file> takes predecence over OUTPUT(<file>). 1186ee59282bSRui Ueyama expect("("); 1187ee59282bSRui Ueyama StringRef Tok = next(); 1188ee59282bSRui Ueyama if (Config->OutputFile.empty()) 1189cd574a5eSGeorge Rimar Config->OutputFile = unquote(Tok); 1190ee59282bSRui Ueyama expect(")"); 1191ee59282bSRui Ueyama } 1192ee59282bSRui Ueyama 1193717677afSRui Ueyama void ScriptParser::readOutputArch() { 11949159ce93SDavide Italiano // Error checking only for now. 11959159ce93SDavide Italiano expect("("); 11965424e7c7SJustin Bogner skip(); 11979159ce93SDavide Italiano expect(")"); 11989159ce93SDavide Italiano } 11999159ce93SDavide Italiano 1200717677afSRui Ueyama void ScriptParser::readOutputFormat() { 1201f7c5fbb1SRui Ueyama // Error checking only for now. 1202f7c5fbb1SRui Ueyama expect("("); 12035424e7c7SJustin Bogner skip(); 12046836c618SDavide Italiano StringRef Tok = next(); 12056836c618SDavide Italiano if (Tok == ")") 12066836c618SDavide Italiano return; 1207025d59b1SRui Ueyama if (Tok != ",") { 12085761042dSGeorge Rimar setError("unexpected token: " + Tok); 1209025d59b1SRui Ueyama return; 1210025d59b1SRui Ueyama } 12115424e7c7SJustin Bogner skip(); 12126836c618SDavide Italiano expect(","); 12135424e7c7SJustin Bogner skip(); 1214f7c5fbb1SRui Ueyama expect(")"); 1215f7c5fbb1SRui Ueyama } 1216f7c5fbb1SRui Ueyama 1217bbe38602SEugene Leviant void ScriptParser::readPhdrs() { 1218bbe38602SEugene Leviant expect("{"); 121983043f23SRui Ueyama while (!Error && !consume("}")) { 1220bbe38602SEugene Leviant StringRef Tok = next(); 122156b21c86SEugene Leviant Opt.PhdrsCommands.push_back( 122256b21c86SEugene Leviant {Tok, PT_NULL, false, false, UINT_MAX, nullptr}); 1223bbe38602SEugene Leviant PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back(); 1224bbe38602SEugene Leviant 1225bbe38602SEugene Leviant PhdrCmd.Type = readPhdrType(); 1226bbe38602SEugene Leviant do { 1227bbe38602SEugene Leviant Tok = next(); 1228bbe38602SEugene Leviant if (Tok == ";") 1229bbe38602SEugene Leviant break; 1230bbe38602SEugene Leviant if (Tok == "FILEHDR") 1231bbe38602SEugene Leviant PhdrCmd.HasFilehdr = true; 1232bbe38602SEugene Leviant else if (Tok == "PHDRS") 1233bbe38602SEugene Leviant PhdrCmd.HasPhdrs = true; 123456b21c86SEugene Leviant else if (Tok == "AT") 123556b21c86SEugene Leviant PhdrCmd.LMAExpr = readParenExpr(); 1236865bf863SEugene Leviant else if (Tok == "FLAGS") { 1237865bf863SEugene Leviant expect("("); 1238eb685cd7SRafael Espindola // Passing 0 for the value of dot is a bit of a hack. It means that 1239eb685cd7SRafael Espindola // we accept expressions like ".|1". 1240eb685cd7SRafael Espindola PhdrCmd.Flags = readExpr()(0); 1241865bf863SEugene Leviant expect(")"); 1242865bf863SEugene Leviant } else 1243bbe38602SEugene Leviant setError("unexpected header attribute: " + Tok); 1244bbe38602SEugene Leviant } while (!Error); 1245bbe38602SEugene Leviant } 1246bbe38602SEugene Leviant } 1247bbe38602SEugene Leviant 1248717677afSRui Ueyama void ScriptParser::readSearchDir() { 124968a39a65SDavide Italiano expect("("); 125086c5fb82SRui Ueyama StringRef Tok = next(); 12516c7ad13fSRui Ueyama if (!Config->Nostdlib) 1252cd574a5eSGeorge Rimar Config->SearchPaths.push_back(unquote(Tok)); 125368a39a65SDavide Italiano expect(")"); 125468a39a65SDavide Italiano } 125568a39a65SDavide Italiano 1256717677afSRui Ueyama void ScriptParser::readSections() { 1257e05336ffSEugene Leviant Opt.HasSections = true; 125818a30962SGeorge Rimar // -no-rosegment is used to avoid placing read only non-executable sections in 125918a30962SGeorge Rimar // their own segment. We do the same if SECTIONS command is present in linker 126018a30962SGeorge Rimar // script. See comment for computeFlags(). 126118a30962SGeorge Rimar Config->SingleRoRx = true; 126218a30962SGeorge Rimar 12638e3b38abSDenis Protivensky expect("{"); 126483043f23SRui Ueyama while (!Error && !consume("}")) { 1265113cdec9SRui Ueyama StringRef Tok = next(); 1266c96da110SRafael Espindola BaseCommand *Cmd = readProvideOrAssignment(Tok); 1267ceabe80eSEugene Leviant if (!Cmd) { 1268ceabe80eSEugene Leviant if (Tok == "ASSERT") 1269eefa758eSGeorge Rimar Cmd = new AssertCommand(readAssert()); 1270ceabe80eSEugene Leviant else 127110416564SRui Ueyama Cmd = readOutputSectionDescription(Tok); 12728e3b38abSDenis Protivensky } 127310416564SRui Ueyama Opt.Commands.emplace_back(Cmd); 1274652852c5SGeorge Rimar } 1275708019c4SRui Ueyama } 12768e3b38abSDenis Protivensky 1277708019c4SRui Ueyama static int precedence(StringRef Op) { 1278708019c4SRui Ueyama return StringSwitch<int>(Op) 12790120e3f2SRui Ueyama .Cases("*", "/", 5) 12800120e3f2SRui Ueyama .Cases("+", "-", 4) 12810120e3f2SRui Ueyama .Cases("<<", ">>", 3) 12829c4ac5f2SRui Ueyama .Cases("<", "<=", ">", ">=", "==", "!=", 2) 12830120e3f2SRui Ueyama .Cases("&", "|", 1) 1284708019c4SRui Ueyama .Default(-1); 1285708019c4SRui Ueyama } 1286708019c4SRui Ueyama 1287db688454SEugene Leviant StringMatcher ScriptParser::readFilePatterns() { 128810416564SRui Ueyama std::vector<StringRef> V; 128983043f23SRui Ueyama while (!Error && !consume(")")) 129010416564SRui Ueyama V.push_back(next()); 1291f91282e1SRui Ueyama return StringMatcher(V); 12920702c4e8SGeorge Rimar } 12930702c4e8SGeorge Rimar 1294be394db3SGeorge Rimar SortSectionPolicy ScriptParser::readSortKind() { 129583043f23SRui Ueyama if (consume("SORT") || consume("SORT_BY_NAME")) 1296be394db3SGeorge Rimar return SortSectionPolicy::Name; 129783043f23SRui Ueyama if (consume("SORT_BY_ALIGNMENT")) 1298be394db3SGeorge Rimar return SortSectionPolicy::Alignment; 129983043f23SRui Ueyama if (consume("SORT_BY_INIT_PRIORITY")) 1300be394db3SGeorge Rimar return SortSectionPolicy::Priority; 130183043f23SRui Ueyama if (consume("SORT_NONE")) 1302be394db3SGeorge Rimar return SortSectionPolicy::None; 1303b2a0abdfSRui Ueyama return SortSectionPolicy::Default; 1304be394db3SGeorge Rimar } 1305be394db3SGeorge Rimar 1306395281cfSGeorge Rimar // Method reads a list of sequence of excluded files and section globs given in 1307395281cfSGeorge Rimar // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+ 1308395281cfSGeorge Rimar // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3) 1309af03be19SGeorge Rimar // The semantics of that is next: 1310af03be19SGeorge Rimar // * Include .foo.1 from every file. 1311af03be19SGeorge Rimar // * Include .foo.2 from every file but a.o 1312af03be19SGeorge Rimar // * Include .foo.3 from every file but b.o 131307171f21SGeorge Rimar std::vector<SectionPattern> ScriptParser::readInputSectionsList() { 131407171f21SGeorge Rimar std::vector<SectionPattern> Ret; 1315601e9898SGeorge Rimar while (!Error && peek() != ")") { 1316f91282e1SRui Ueyama StringMatcher ExcludeFilePat; 131783043f23SRui Ueyama if (consume("EXCLUDE_FILE")) { 1318395281cfSGeorge Rimar expect("("); 1319f91282e1SRui Ueyama ExcludeFilePat = readFilePatterns(); 1320395281cfSGeorge Rimar } 1321395281cfSGeorge Rimar 1322601e9898SGeorge Rimar std::vector<StringRef> V; 1323601e9898SGeorge Rimar while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE") 1324395281cfSGeorge Rimar V.push_back(next()); 1325601e9898SGeorge Rimar 1326601e9898SGeorge Rimar if (!V.empty()) 1327f91282e1SRui Ueyama Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)}); 1328601e9898SGeorge Rimar else 1329601e9898SGeorge Rimar setError("section pattern is expected"); 1330395281cfSGeorge Rimar } 133107171f21SGeorge Rimar return Ret; 1332395281cfSGeorge Rimar } 1333395281cfSGeorge Rimar 1334f8f6f1e7SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a 1335f8f6f1e7SRui Ueyama // list of glob patterns for input sections. The grammar is as follows. 1336f8f6f1e7SRui Ueyama // 1337f8f6f1e7SRui Ueyama // <patterns> ::= <section-list> 1338f8f6f1e7SRui Ueyama // | <sort> "(" <section-list> ")" 1339f8f6f1e7SRui Ueyama // | <sort> "(" <sort> "(" <section-list> ")" ")" 1340f8f6f1e7SRui Ueyama // 1341f8f6f1e7SRui Ueyama // <sort> ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT" 1342f8f6f1e7SRui Ueyama // | "SORT_BY_INIT_PRIORITY" | "SORT_NONE" 1343f8f6f1e7SRui Ueyama // 1344f8f6f1e7SRui Ueyama // <section-list> is parsed by readInputSectionsList(). 1345a2496cbeSGeorge Rimar InputSectionDescription * 1346a2496cbeSGeorge Rimar ScriptParser::readInputSectionRules(StringRef FilePattern) { 1347c91930a1SGeorge Rimar auto *Cmd = new InputSectionDescription(FilePattern); 13480ed42b0cSDavide Italiano expect("("); 1349f373dd76SRui Ueyama while (!Error && !consume(")")) { 135007171f21SGeorge Rimar SortSectionPolicy Outer = readSortKind(); 135107171f21SGeorge Rimar SortSectionPolicy Inner = SortSectionPolicy::Default; 135207171f21SGeorge Rimar std::vector<SectionPattern> V; 135307171f21SGeorge Rimar if (Outer != SortSectionPolicy::Default) { 13540702c4e8SGeorge Rimar expect("("); 135507171f21SGeorge Rimar Inner = readSortKind(); 135607171f21SGeorge Rimar if (Inner != SortSectionPolicy::Default) { 1357350ece4eSGeorge Rimar expect("("); 135807171f21SGeorge Rimar V = readInputSectionsList(); 13590702c4e8SGeorge Rimar expect(")"); 1360350ece4eSGeorge Rimar } else { 136107171f21SGeorge Rimar V = readInputSectionsList(); 1362350ece4eSGeorge Rimar } 1363350ece4eSGeorge Rimar expect(")"); 136407171f21SGeorge Rimar } else { 136507171f21SGeorge Rimar V = readInputSectionsList(); 13660659800eSGeorge Rimar } 13670702c4e8SGeorge Rimar 136807171f21SGeorge Rimar for (SectionPattern &Pat : V) { 136907171f21SGeorge Rimar Pat.SortInner = Inner; 137007171f21SGeorge Rimar Pat.SortOuter = Outer; 137107171f21SGeorge Rimar } 137207171f21SGeorge Rimar 137307171f21SGeorge Rimar std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns)); 137407171f21SGeorge Rimar } 137510416564SRui Ueyama return Cmd; 13760659800eSGeorge Rimar } 13770659800eSGeorge Rimar 1378a2496cbeSGeorge Rimar InputSectionDescription * 1379a2496cbeSGeorge Rimar ScriptParser::readInputSectionDescription(StringRef Tok) { 13800659800eSGeorge Rimar // Input section wildcard can be surrounded by KEEP. 13810659800eSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep 1382a2496cbeSGeorge Rimar if (Tok == "KEEP") { 1383e7282797SDavide Italiano expect("("); 1384a2496cbeSGeorge Rimar StringRef FilePattern = next(); 1385a2496cbeSGeorge Rimar InputSectionDescription *Cmd = readInputSectionRules(FilePattern); 13860ed42b0cSDavide Italiano expect(")"); 1387cf43f179SEugene Leviant Opt.KeptSections.push_back(Cmd); 138810416564SRui Ueyama return Cmd; 138910416564SRui Ueyama } 1390a2496cbeSGeorge Rimar return readInputSectionRules(Tok); 13910659800eSGeorge Rimar } 13920659800eSGeorge Rimar 139303fc010eSGeorge Rimar void ScriptParser::readSort() { 139403fc010eSGeorge Rimar expect("("); 139503fc010eSGeorge Rimar expect("CONSTRUCTORS"); 139603fc010eSGeorge Rimar expect(")"); 139703fc010eSGeorge Rimar } 139803fc010eSGeorge Rimar 1399eefa758eSGeorge Rimar Expr ScriptParser::readAssert() { 1400eefa758eSGeorge Rimar expect("("); 1401eefa758eSGeorge Rimar Expr E = readExpr(); 1402eefa758eSGeorge Rimar expect(","); 1403cd574a5eSGeorge Rimar StringRef Msg = unquote(next()); 1404eefa758eSGeorge Rimar expect(")"); 1405eefa758eSGeorge Rimar return [=](uint64_t Dot) { 1406eefa758eSGeorge Rimar uint64_t V = E(Dot); 1407eefa758eSGeorge Rimar if (!V) 1408eefa758eSGeorge Rimar error(Msg); 1409eefa758eSGeorge Rimar return V; 1410eefa758eSGeorge Rimar }; 1411eefa758eSGeorge Rimar } 1412eefa758eSGeorge Rimar 141325150e8bSRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an 141425150e8bSRui Ueyama // alias for =fillexp section attribute, which is different from 141525150e8bSRui Ueyama // what GNU linkers do. 141625150e8bSRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html 141716068aebSRui Ueyama uint32_t ScriptParser::readFill() { 1418ff1f29e0SGeorge Rimar expect("("); 141916068aebSRui Ueyama uint32_t V = readOutputSectionFiller(next()); 1420ff1f29e0SGeorge Rimar expect(")"); 1421ff1f29e0SGeorge Rimar expect(";"); 1422ff1f29e0SGeorge Rimar return V; 1423ff1f29e0SGeorge Rimar } 1424ff1f29e0SGeorge Rimar 142510416564SRui Ueyama OutputSectionCommand * 142610416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) { 1427076fe157SGeorge Rimar OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec); 14282a942c4bSEugene Leviant Cmd->Location = getCurrentLocation(); 142958e5c4dcSGeorge Rimar 143058e5c4dcSGeorge Rimar // Read an address expression. 143158e5c4dcSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address 143258e5c4dcSGeorge Rimar if (peek() != ":") 143358e5c4dcSGeorge Rimar Cmd->AddrExpr = readExpr(); 143458e5c4dcSGeorge Rimar 14358e3b38abSDenis Protivensky expect(":"); 1436246f681eSDavide Italiano 143783043f23SRui Ueyama if (consume("AT")) 1438b71d6f7aSEugene Leviant Cmd->LMAExpr = readParenExpr(); 143983043f23SRui Ueyama if (consume("ALIGN")) 14406ad7dfccSRui Ueyama Cmd->AlignExpr = readParenExpr(); 144183043f23SRui Ueyama if (consume("SUBALIGN")) 1442db24d9c3SGeorge Rimar Cmd->SubalignExpr = readParenExpr(); 1443630c6179SGeorge Rimar 1444246f681eSDavide Italiano // Parse constraints. 144583043f23SRui Ueyama if (consume("ONLY_IF_RO")) 1446efc4066bSRui Ueyama Cmd->Constraint = ConstraintKind::ReadOnly; 144783043f23SRui Ueyama if (consume("ONLY_IF_RW")) 1448efc4066bSRui Ueyama Cmd->Constraint = ConstraintKind::ReadWrite; 14498e3b38abSDenis Protivensky expect("{"); 14508ec77e64SRui Ueyama 145183043f23SRui Ueyama while (!Error && !consume("}")) { 1452ceabe80eSEugene Leviant StringRef Tok = next(); 1453b2d99d6aSMeador Inge if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) { 1454ceabe80eSEugene Leviant Cmd->Commands.emplace_back(Assignment); 1455b2d99d6aSMeador Inge } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) { 1456e38cbab5SGeorge Rimar Cmd->Commands.emplace_back(Data); 1457b2d99d6aSMeador Inge } else if (Tok == "ASSERT") { 1458b2d99d6aSMeador Inge Cmd->Commands.emplace_back(new AssertCommand(readAssert())); 1459b2d99d6aSMeador Inge expect(";"); 1460b2d99d6aSMeador Inge } else if (Tok == "FILL") { 1461ff1f29e0SGeorge Rimar Cmd->Filler = readFill(); 1462b2d99d6aSMeador Inge } else if (Tok == "SORT") { 146303fc010eSGeorge Rimar readSort(); 1464b2d99d6aSMeador Inge } else if (peek() == "(") { 1465a2496cbeSGeorge Rimar Cmd->Commands.emplace_back(readInputSectionDescription(Tok)); 1466b2d99d6aSMeador Inge } else { 1467ceabe80eSEugene Leviant setError("unknown command " + Tok); 14688e3b38abSDenis Protivensky } 1469b2d99d6aSMeador Inge } 1470076fe157SGeorge Rimar Cmd->Phdrs = readOutputSectionPhdrs(); 14714ebc5620SGeorge Rimar 147283043f23SRui Ueyama if (consume("=")) 14734ebc5620SGeorge Rimar Cmd->Filler = readOutputSectionFiller(next()); 14744ebc5620SGeorge Rimar else if (peek().startswith("=")) 1475ff1f29e0SGeorge Rimar Cmd->Filler = readOutputSectionFiller(next().drop_front()); 14764ebc5620SGeorge Rimar 147710416564SRui Ueyama return Cmd; 1478f71caa2bSRui Ueyama } 14798ec77e64SRui Ueyama 14802c8f1f04SRui Ueyama // Read "=<number>" where <number> is an octal/decimal/hexadecimal number. 14812c8f1f04SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html 14822c8f1f04SRui Ueyama // 14832c8f1f04SRui Ueyama // ld.gold is not fully compatible with ld.bfd. ld.bfd handles 14842c8f1f04SRui Ueyama // hexstrings as blobs of arbitrary sizes, while ld.gold handles them 14852c8f1f04SRui Ueyama // as 32-bit big-endian values. We will do the same as ld.gold does 14862c8f1f04SRui Ueyama // because it's simpler than what ld.bfd does. 148716068aebSRui Ueyama uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) { 1488965827d6SRui Ueyama uint32_t V; 148916068aebSRui Ueyama if (!Tok.getAsInteger(0, V)) 149016068aebSRui Ueyama return V; 1491965827d6SRui Ueyama setError("invalid filler expression: " + Tok); 149216068aebSRui Ueyama return 0; 14938e3b38abSDenis Protivensky } 14948e3b38abSDenis Protivensky 1495a35e39caSPetr Hosek SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) { 1496a31c91b1SEugene Leviant expect("("); 1497174e0a16SRui Ueyama SymbolAssignment *Cmd = readAssignment(next()); 1498a35e39caSPetr Hosek Cmd->Provide = Provide; 1499174e0a16SRui Ueyama Cmd->Hidden = Hidden; 1500a31c91b1SEugene Leviant expect(")"); 1501a31c91b1SEugene Leviant expect(";"); 150210416564SRui Ueyama return Cmd; 1503eda81a1bSEugene Leviant } 1504eda81a1bSEugene Leviant 1505c96da110SRafael Espindola SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) { 1506ceabe80eSEugene Leviant SymbolAssignment *Cmd = nullptr; 1507ceabe80eSEugene Leviant if (peek() == "=" || peek() == "+=") { 1508ceabe80eSEugene Leviant Cmd = readAssignment(Tok); 1509ceabe80eSEugene Leviant expect(";"); 1510ceabe80eSEugene Leviant } else if (Tok == "PROVIDE") { 1511a35e39caSPetr Hosek Cmd = readProvideHidden(true, false); 1512a35e39caSPetr Hosek } else if (Tok == "HIDDEN") { 1513a35e39caSPetr Hosek Cmd = readProvideHidden(false, true); 1514ceabe80eSEugene Leviant } else if (Tok == "PROVIDE_HIDDEN") { 1515a35e39caSPetr Hosek Cmd = readProvideHidden(true, true); 1516ceabe80eSEugene Leviant } 1517ceabe80eSEugene Leviant return Cmd; 1518ceabe80eSEugene Leviant } 1519ceabe80eSEugene Leviant 152030835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) { 152130835ea4SGeorge Rimar if (S == ".") 152230835ea4SGeorge Rimar return Dot; 1523884e786dSGeorge Rimar return ScriptBase->getSymbolValue(S); 1524e32a3598SGeorge Rimar } 1525e32a3598SGeorge Rimar 15262f831dcaSRafael Espindola static bool isAbsolute(StringRef S) { 15272f831dcaSRafael Espindola if (S == ".") 15282f831dcaSRafael Espindola return false; 15292f831dcaSRafael Espindola return ScriptBase->isAbsolute(S); 15302f831dcaSRafael Espindola } 15312f831dcaSRafael Espindola 153230835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) { 153330835ea4SGeorge Rimar StringRef Op = next(); 1534db741e72SEugene Leviant Expr E; 153530835ea4SGeorge Rimar assert(Op == "=" || Op == "+="); 153683043f23SRui Ueyama if (consume("ABSOLUTE")) { 15377c1381a0SRui Ueyama // The RHS may be something like "ABSOLUTE(.) & 0xff". 15387c1381a0SRui Ueyama // Call readExpr1 to read the whole expression. 15397c1381a0SRui Ueyama E = readExpr1(readParenExpr(), 0); 1540009d1742SRui Ueyama E.IsAbsolute = [] { return true; }; 1541db741e72SEugene Leviant } else { 1542db741e72SEugene Leviant E = readExpr(); 1543db741e72SEugene Leviant } 154430835ea4SGeorge Rimar if (Op == "+=") 154530835ea4SGeorge Rimar E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); }; 1546f661393aSRafael Espindola return new SymbolAssignment(Name, E); 154730835ea4SGeorge Rimar } 154830835ea4SGeorge Rimar 154930835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker 155030835ea4SGeorge Rimar // script expression. 155130835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); } 155230835ea4SGeorge Rimar 155336c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) { 155436c1cd23SRui Ueyama if (Op == "*") 155536c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) * R(Dot); }; 155636c1cd23SRui Ueyama if (Op == "/") { 155736c1cd23SRui Ueyama return [=](uint64_t Dot) -> uint64_t { 155836c1cd23SRui Ueyama uint64_t RHS = R(Dot); 155936c1cd23SRui Ueyama if (RHS == 0) { 156036c1cd23SRui Ueyama error("division by zero"); 156136c1cd23SRui Ueyama return 0; 156236c1cd23SRui Ueyama } 156336c1cd23SRui Ueyama return L(Dot) / RHS; 156436c1cd23SRui Ueyama }; 156536c1cd23SRui Ueyama } 156636c1cd23SRui Ueyama if (Op == "+") 15672f831dcaSRafael Espindola return {[=](uint64_t Dot) { return L(Dot) + R(Dot); }, 1568009d1742SRui Ueyama [=] { return L.IsAbsolute() && R.IsAbsolute(); }, 1569009d1742SRui Ueyama [=] { 1570afaa9343SEugene Leviant const OutputSectionBase *S = L.Section(); 1571afaa9343SEugene Leviant return S ? S : R.Section(); 1572afaa9343SEugene Leviant }}; 157336c1cd23SRui Ueyama if (Op == "-") 157436c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) - R(Dot); }; 1575c8ccd1f1SGeorge Rimar if (Op == "<<") 1576c8ccd1f1SGeorge Rimar return [=](uint64_t Dot) { return L(Dot) << R(Dot); }; 1577c8ccd1f1SGeorge Rimar if (Op == ">>") 1578c8ccd1f1SGeorge Rimar return [=](uint64_t Dot) { return L(Dot) >> R(Dot); }; 157936c1cd23SRui Ueyama if (Op == "<") 158036c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) < R(Dot); }; 158136c1cd23SRui Ueyama if (Op == ">") 158236c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) > R(Dot); }; 158336c1cd23SRui Ueyama if (Op == ">=") 158436c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) >= R(Dot); }; 158536c1cd23SRui Ueyama if (Op == "<=") 158636c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) <= R(Dot); }; 158736c1cd23SRui Ueyama if (Op == "==") 158836c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) == R(Dot); }; 158936c1cd23SRui Ueyama if (Op == "!=") 159036c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) != R(Dot); }; 159136c1cd23SRui Ueyama if (Op == "&") 159236c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) & R(Dot); }; 1593cc3dd629SRafael Espindola if (Op == "|") 1594cc3dd629SRafael Espindola return [=](uint64_t Dot) { return L(Dot) | R(Dot); }; 159536c1cd23SRui Ueyama llvm_unreachable("invalid operator"); 159636c1cd23SRui Ueyama } 159736c1cd23SRui Ueyama 1598708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function 1599708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator. 1600708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) { 1601708019c4SRui Ueyama while (!atEOF() && !Error) { 1602708019c4SRui Ueyama // Read an operator and an expression. 160346247b85SRui Ueyama if (consume("?")) 1604708019c4SRui Ueyama return readTernary(Lhs); 160546247b85SRui Ueyama StringRef Op1 = peek(); 1606708019c4SRui Ueyama if (precedence(Op1) < MinPrec) 1607a31c91b1SEugene Leviant break; 16085424e7c7SJustin Bogner skip(); 1609708019c4SRui Ueyama Expr Rhs = readPrimary(); 1610708019c4SRui Ueyama 1611708019c4SRui Ueyama // Evaluate the remaining part of the expression first if the 1612708019c4SRui Ueyama // next operator has greater precedence than the previous one. 1613708019c4SRui Ueyama // For example, if we have read "+" and "3", and if the next 1614708019c4SRui Ueyama // operator is "*", then we'll evaluate 3 * ... part first. 1615708019c4SRui Ueyama while (!atEOF()) { 1616708019c4SRui Ueyama StringRef Op2 = peek(); 1617708019c4SRui Ueyama if (precedence(Op2) <= precedence(Op1)) 1618eda81a1bSEugene Leviant break; 1619708019c4SRui Ueyama Rhs = readExpr1(Rhs, precedence(Op2)); 1620eda81a1bSEugene Leviant } 1621708019c4SRui Ueyama 1622708019c4SRui Ueyama Lhs = combine(Op1, Lhs, Rhs); 1623708019c4SRui Ueyama } 1624708019c4SRui Ueyama return Lhs; 1625708019c4SRui Ueyama } 1626708019c4SRui Ueyama 1627708019c4SRui Ueyama uint64_t static getConstant(StringRef S) { 1628e2cc07bcSMichael J. Spencer if (S == "COMMONPAGESIZE") 1629708019c4SRui Ueyama return Target->PageSize; 1630e2cc07bcSMichael J. Spencer if (S == "MAXPAGESIZE") 1631997f8838SPetr Hosek return Config->MaxPageSize; 1632708019c4SRui Ueyama error("unknown constant: " + S); 1633708019c4SRui Ueyama return 0; 1634708019c4SRui Ueyama } 1635708019c4SRui Ueyama 1636626e0b08SRui Ueyama // Parses Tok as an integer. Returns true if successful. 1637626e0b08SRui Ueyama // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H") 1638626e0b08SRui Ueyama // and decimal numbers. Decimal numbers may have "K" (kilo) or 1639626e0b08SRui Ueyama // "M" (mega) prefixes. 16409f2f7ad9SGeorge Rimar static bool readInteger(StringRef Tok, uint64_t &Result) { 164146247b85SRui Ueyama // Negative number 1642eaeafb2bSSimon Atanasyan if (Tok.startswith("-")) { 1643eaeafb2bSSimon Atanasyan if (!readInteger(Tok.substr(1), Result)) 1644eaeafb2bSSimon Atanasyan return false; 1645eaeafb2bSSimon Atanasyan Result = -Result; 1646eaeafb2bSSimon Atanasyan return true; 1647eaeafb2bSSimon Atanasyan } 164846247b85SRui Ueyama 164946247b85SRui Ueyama // Hexadecimal 16509f2f7ad9SGeorge Rimar if (Tok.startswith_lower("0x")) 16519f2f7ad9SGeorge Rimar return !Tok.substr(2).getAsInteger(16, Result); 16529f2f7ad9SGeorge Rimar if (Tok.endswith_lower("H")) 16539f2f7ad9SGeorge Rimar return !Tok.drop_back().getAsInteger(16, Result); 16549f2f7ad9SGeorge Rimar 165546247b85SRui Ueyama // Decimal 16569f2f7ad9SGeorge Rimar int Suffix = 1; 16579f2f7ad9SGeorge Rimar if (Tok.endswith_lower("K")) { 16589f2f7ad9SGeorge Rimar Suffix = 1024; 16599f2f7ad9SGeorge Rimar Tok = Tok.drop_back(); 16609f2f7ad9SGeorge Rimar } else if (Tok.endswith_lower("M")) { 16619f2f7ad9SGeorge Rimar Suffix = 1024 * 1024; 16629f2f7ad9SGeorge Rimar Tok = Tok.drop_back(); 16639f2f7ad9SGeorge Rimar } 16649f2f7ad9SGeorge Rimar if (Tok.getAsInteger(10, Result)) 16659f2f7ad9SGeorge Rimar return false; 16669f2f7ad9SGeorge Rimar Result *= Suffix; 16679f2f7ad9SGeorge Rimar return true; 16689f2f7ad9SGeorge Rimar } 16699f2f7ad9SGeorge Rimar 1670e38cbab5SGeorge Rimar BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) { 1671e38cbab5SGeorge Rimar int Size = StringSwitch<unsigned>(Tok) 1672e38cbab5SGeorge Rimar .Case("BYTE", 1) 1673e38cbab5SGeorge Rimar .Case("SHORT", 2) 1674e38cbab5SGeorge Rimar .Case("LONG", 4) 1675e38cbab5SGeorge Rimar .Case("QUAD", 8) 1676e38cbab5SGeorge Rimar .Default(-1); 1677e38cbab5SGeorge Rimar if (Size == -1) 1678e38cbab5SGeorge Rimar return nullptr; 1679e38cbab5SGeorge Rimar 168095c7d8d2SMeador Inge return new BytesDataCommand(readParenExpr(), Size); 1681e38cbab5SGeorge Rimar } 1682e38cbab5SGeorge Rimar 1683b71d6f7aSEugene Leviant StringRef ScriptParser::readParenLiteral() { 1684b71d6f7aSEugene Leviant expect("("); 1685b71d6f7aSEugene Leviant StringRef Tok = next(); 1686b71d6f7aSEugene Leviant expect(")"); 1687b71d6f7aSEugene Leviant return Tok; 1688b71d6f7aSEugene Leviant } 1689b71d6f7aSEugene Leviant 1690708019c4SRui Ueyama Expr ScriptParser::readPrimary() { 16916ad7dfccSRui Ueyama if (peek() == "(") 16926ad7dfccSRui Ueyama return readParenExpr(); 1693708019c4SRui Ueyama 16946ad7dfccSRui Ueyama StringRef Tok = next(); 1695b5f1c3ecSRui Ueyama std::string Location = getCurrentLocation(); 1696708019c4SRui Ueyama 1697eaeafb2bSSimon Atanasyan if (Tok == "~") { 1698eaeafb2bSSimon Atanasyan Expr E = readPrimary(); 1699eaeafb2bSSimon Atanasyan return [=](uint64_t Dot) { return ~E(Dot); }; 1700eaeafb2bSSimon Atanasyan } 1701eaeafb2bSSimon Atanasyan if (Tok == "-") { 1702eaeafb2bSSimon Atanasyan Expr E = readPrimary(); 1703eaeafb2bSSimon Atanasyan return [=](uint64_t Dot) { return -E(Dot); }; 1704eaeafb2bSSimon Atanasyan } 1705eaeafb2bSSimon Atanasyan 1706708019c4SRui Ueyama // Built-in functions are parsed here. 1707708019c4SRui Ueyama // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html. 170896659df0SGeorge Rimar if (Tok == "ADDR") { 1709b71d6f7aSEugene Leviant StringRef Name = readParenLiteral(); 1710ed30ce7aSEugene Leviant return {[=](uint64_t Dot) { 1711ed30ce7aSEugene Leviant return ScriptBase->getOutputSection(Location, Name)->Addr; 1712ed30ce7aSEugene Leviant }, 1713009d1742SRui Ueyama [=] { return false; }, 1714ed30ce7aSEugene Leviant [=] { return ScriptBase->getOutputSection(Location, Name); }}; 171596659df0SGeorge Rimar } 1716b71d6f7aSEugene Leviant if (Tok == "LOADADDR") { 1717b71d6f7aSEugene Leviant StringRef Name = readParenLiteral(); 1718afaa9343SEugene Leviant return [=](uint64_t Dot) { 1719ed30ce7aSEugene Leviant return ScriptBase->getOutputSection(Location, Name)->getLMA(); 1720afaa9343SEugene Leviant }; 1721b71d6f7aSEugene Leviant } 1722eefa758eSGeorge Rimar if (Tok == "ASSERT") 1723eefa758eSGeorge Rimar return readAssert(); 1724708019c4SRui Ueyama if (Tok == "ALIGN") { 17255d804dc8SRui Ueyama expect("("); 17265d804dc8SRui Ueyama Expr E = readExpr(); 17275d804dc8SRui Ueyama if (consume(",")) { 17285d804dc8SRui Ueyama Expr E2 = readExpr(); 17295d804dc8SRui Ueyama expect(")"); 17305d804dc8SRui Ueyama return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); }; 17315d804dc8SRui Ueyama } 17325d804dc8SRui Ueyama expect(")"); 1733708019c4SRui Ueyama return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); }; 1734708019c4SRui Ueyama } 1735708019c4SRui Ueyama if (Tok == "CONSTANT") { 1736b71d6f7aSEugene Leviant StringRef Name = readParenLiteral(); 1737b0de56b5SRafael Espindola return [=](uint64_t Dot) { return getConstant(Name); }; 1738708019c4SRui Ueyama } 1739f34f45fdSGeorge Rimar if (Tok == "DEFINED") { 17400ee25a69SRui Ueyama StringRef Name = readParenLiteral(); 17410ee25a69SRui Ueyama return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; }; 1742f34f45fdSGeorge Rimar } 174354c145ceSRafael Espindola if (Tok == "SEGMENT_START") { 174454c145ceSRafael Espindola expect("("); 17455424e7c7SJustin Bogner skip(); 174654c145ceSRafael Espindola expect(","); 17478c658bf8SGeorge Rimar Expr E = readExpr(); 174854c145ceSRafael Espindola expect(")"); 17498c658bf8SGeorge Rimar return [=](uint64_t Dot) { return E(Dot); }; 175054c145ceSRafael Espindola } 1751708019c4SRui Ueyama if (Tok == "DATA_SEGMENT_ALIGN") { 1752708019c4SRui Ueyama expect("("); 1753708019c4SRui Ueyama Expr E = readExpr(); 1754708019c4SRui Ueyama expect(","); 1755708019c4SRui Ueyama readExpr(); 1756708019c4SRui Ueyama expect(")"); 1757f7791bb9SRui Ueyama return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); }; 1758708019c4SRui Ueyama } 1759708019c4SRui Ueyama if (Tok == "DATA_SEGMENT_END") { 1760708019c4SRui Ueyama expect("("); 1761708019c4SRui Ueyama expect("."); 1762708019c4SRui Ueyama expect(")"); 1763708019c4SRui Ueyama return [](uint64_t Dot) { return Dot; }; 1764708019c4SRui Ueyama } 1765276b4e64SGeorge Rimar // GNU linkers implements more complicated logic to handle 1766276b4e64SGeorge Rimar // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to 1767276b4e64SGeorge Rimar // the next page boundary for simplicity. 1768276b4e64SGeorge Rimar if (Tok == "DATA_SEGMENT_RELRO_END") { 1769276b4e64SGeorge Rimar expect("("); 177097bdc722SRafael Espindola readExpr(); 1771276b4e64SGeorge Rimar expect(","); 1772276b4e64SGeorge Rimar readExpr(); 1773276b4e64SGeorge Rimar expect(")"); 1774276b4e64SGeorge Rimar return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); }; 1775276b4e64SGeorge Rimar } 17769e69450eSGeorge Rimar if (Tok == "SIZEOF") { 1777b71d6f7aSEugene Leviant StringRef Name = readParenLiteral(); 1778edf75e79SRui Ueyama return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); }; 17799e69450eSGeorge Rimar } 178036fac7f0SEugene Leviant if (Tok == "ALIGNOF") { 1781b71d6f7aSEugene Leviant StringRef Name = readParenLiteral(); 1782afaa9343SEugene Leviant return [=](uint64_t Dot) { 1783ed30ce7aSEugene Leviant return ScriptBase->getOutputSection(Location, Name)->Addralign; 1784afaa9343SEugene Leviant }; 178536fac7f0SEugene Leviant } 1786e32a3598SGeorge Rimar if (Tok == "SIZEOF_HEADERS") 1787b0de56b5SRafael Espindola return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); }; 1788708019c4SRui Ueyama 17899f2f7ad9SGeorge Rimar // Tok is a literal number. 17909f2f7ad9SGeorge Rimar uint64_t V; 17919f2f7ad9SGeorge Rimar if (readInteger(Tok, V)) 1792b0de56b5SRafael Espindola return [=](uint64_t Dot) { return V; }; 17939f2f7ad9SGeorge Rimar 17949f2f7ad9SGeorge Rimar // Tok is a symbol name. 179530835ea4SGeorge Rimar if (Tok != "." && !isValidCIdentifier(Tok)) 1796708019c4SRui Ueyama setError("malformed number: " + Tok); 17972f831dcaSRafael Espindola return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); }, 1798009d1742SRui Ueyama [=] { return isAbsolute(Tok); }, 1799009d1742SRui Ueyama [=] { return ScriptBase->getSymbolSection(Tok); }}; 1800a9c5a528SGeorge Rimar } 1801708019c4SRui Ueyama 1802708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) { 1803708019c4SRui Ueyama Expr L = readExpr(); 1804708019c4SRui Ueyama expect(":"); 1805708019c4SRui Ueyama Expr R = readExpr(); 1806708019c4SRui Ueyama return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); }; 1807708019c4SRui Ueyama } 1808708019c4SRui Ueyama 18096ad7dfccSRui Ueyama Expr ScriptParser::readParenExpr() { 18106ad7dfccSRui Ueyama expect("("); 18116ad7dfccSRui Ueyama Expr E = readExpr(); 18126ad7dfccSRui Ueyama expect(")"); 18136ad7dfccSRui Ueyama return E; 18146ad7dfccSRui Ueyama } 18156ad7dfccSRui Ueyama 1816bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() { 1817bbe38602SEugene Leviant std::vector<StringRef> Phdrs; 1818bbe38602SEugene Leviant while (!Error && peek().startswith(":")) { 1819bbe38602SEugene Leviant StringRef Tok = next(); 1820da841c16SGeorge Rimar Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1)); 1821bbe38602SEugene Leviant } 1822bbe38602SEugene Leviant return Phdrs; 1823bbe38602SEugene Leviant } 1824bbe38602SEugene Leviant 182595dd718cSGeorge Rimar // Read a program header type name. The next token must be a 182695dd718cSGeorge Rimar // name of a program header type or a constant (e.g. "0x3"). 1827bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() { 1828bbe38602SEugene Leviant StringRef Tok = next(); 182995dd718cSGeorge Rimar uint64_t Val; 183095dd718cSGeorge Rimar if (readInteger(Tok, Val)) 183195dd718cSGeorge Rimar return Val; 183295dd718cSGeorge Rimar 1833b0f6c590SRui Ueyama unsigned Ret = StringSwitch<unsigned>(Tok) 1834b0f6c590SRui Ueyama .Case("PT_NULL", PT_NULL) 1835b0f6c590SRui Ueyama .Case("PT_LOAD", PT_LOAD) 1836b0f6c590SRui Ueyama .Case("PT_DYNAMIC", PT_DYNAMIC) 1837b0f6c590SRui Ueyama .Case("PT_INTERP", PT_INTERP) 1838b0f6c590SRui Ueyama .Case("PT_NOTE", PT_NOTE) 1839b0f6c590SRui Ueyama .Case("PT_SHLIB", PT_SHLIB) 1840b0f6c590SRui Ueyama .Case("PT_PHDR", PT_PHDR) 1841b0f6c590SRui Ueyama .Case("PT_TLS", PT_TLS) 1842b0f6c590SRui Ueyama .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME) 1843b0f6c590SRui Ueyama .Case("PT_GNU_STACK", PT_GNU_STACK) 1844b0f6c590SRui Ueyama .Case("PT_GNU_RELRO", PT_GNU_RELRO) 1845270173f2SGeorge Rimar .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE) 1846cc6e567cSGeorge Rimar .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED) 1847a2a32c2cSGeorge Rimar .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA) 1848b0f6c590SRui Ueyama .Default(-1); 1849bbe38602SEugene Leviant 1850b0f6c590SRui Ueyama if (Ret == (unsigned)-1) { 1851b0f6c590SRui Ueyama setError("invalid program header type: " + Tok); 1852b0f6c590SRui Ueyama return PT_NULL; 1853b0f6c590SRui Ueyama } 1854b0f6c590SRui Ueyama return Ret; 1855bbe38602SEugene Leviant } 1856bbe38602SEugene Leviant 185712450b20SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };". 185812450b20SRui Ueyama void ScriptParser::readAnonymousDeclaration() { 185912450b20SRui Ueyama // Read global symbols first. "global:" is default, so if there's 186012450b20SRui Ueyama // no label, we assume global symbols. 186112450b20SRui Ueyama if (consume("global:") || peek() != "local:") 186212450b20SRui Ueyama Config->VersionScriptGlobals = readSymbols(); 186312450b20SRui Ueyama 186412450b20SRui Ueyama // Next, read local symbols. 186512450b20SRui Ueyama if (consume("local:")) { 186612450b20SRui Ueyama if (consume("*")) { 186712450b20SRui Ueyama Config->DefaultSymbolVersion = VER_NDX_LOCAL; 186812450b20SRui Ueyama expect(";"); 186912450b20SRui Ueyama } else { 187012450b20SRui Ueyama setError("local symbol list for anonymous version is not supported"); 187112450b20SRui Ueyama } 187212450b20SRui Ueyama } 187312450b20SRui Ueyama expect("}"); 187412450b20SRui Ueyama expect(";"); 187512450b20SRui Ueyama } 187612450b20SRui Ueyama 187712450b20SRui Ueyama // Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };". 187895769b4aSRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) { 187920b6598cSGeorge Rimar // Identifiers start at 2 because 0 and 1 are reserved 188020b6598cSGeorge Rimar // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants. 1881da805c48SRui Ueyama uint16_t VersionId = Config->VersionDefinitions.size() + 2; 188220b6598cSGeorge Rimar Config->VersionDefinitions.push_back({VerStr, VersionId}); 188320b6598cSGeorge Rimar 188412450b20SRui Ueyama // Read global symbols. 188583043f23SRui Ueyama if (consume("global:") || peek() != "local:") 188612450b20SRui Ueyama Config->VersionDefinitions.back().Globals = readSymbols(); 188712450b20SRui Ueyama 188812450b20SRui Ueyama // Read local symbols. 188912450b20SRui Ueyama if (consume("local:")) { 189012450b20SRui Ueyama if (consume("*")) { 189112450b20SRui Ueyama Config->DefaultSymbolVersion = VER_NDX_LOCAL; 189212450b20SRui Ueyama expect(";"); 189312450b20SRui Ueyama } else { 189412450b20SRui Ueyama for (SymbolVersion V : readSymbols()) 189512450b20SRui Ueyama Config->VersionScriptLocals.push_back(V); 189612450b20SRui Ueyama } 189712450b20SRui Ueyama } 189820b6598cSGeorge Rimar expect("}"); 189920b6598cSGeorge Rimar 190012450b20SRui Ueyama // Each version may have a parent version. For example, "Ver2" 190112450b20SRui Ueyama // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" 190212450b20SRui Ueyama // as a parent. This version hierarchy is, probably against your 190312450b20SRui Ueyama // instinct, purely for hint; the runtime doesn't care about it 190412450b20SRui Ueyama // at all. In LLD, we simply ignore it. 190512450b20SRui Ueyama if (peek() != ";") 19065424e7c7SJustin Bogner skip(); 190720b6598cSGeorge Rimar expect(";"); 190820b6598cSGeorge Rimar } 190920b6598cSGeorge Rimar 191012450b20SRui Ueyama // Reads a list of symbols for a versions cript. 191112450b20SRui Ueyama std::vector<SymbolVersion> ScriptParser::readSymbols() { 191212450b20SRui Ueyama std::vector<SymbolVersion> Ret; 1913e0fc2421SGeorge Rimar for (;;) { 19141ef90d2fSRafael Espindola if (consume("extern")) { 191512450b20SRui Ueyama for (SymbolVersion V : readVersionExtern()) 191612450b20SRui Ueyama Ret.push_back(V); 19171ef90d2fSRafael Espindola continue; 19181ef90d2fSRafael Espindola } 1919e0fc2421SGeorge Rimar 19200ee25a69SRui Ueyama if (peek() == "}" || peek() == "local:" || Error) 192112450b20SRui Ueyama break; 19220ee25a69SRui Ueyama StringRef Tok = next(); 192312450b20SRui Ueyama Ret.push_back({unquote(Tok), false, hasWildcard(Tok)}); 1924e0fc2421SGeorge Rimar expect(";"); 1925e0fc2421SGeorge Rimar } 192612450b20SRui Ueyama return Ret; 1927e0fc2421SGeorge Rimar } 1928e0fc2421SGeorge Rimar 192912450b20SRui Ueyama // Reads an "extern C++" directive, e.g., 193012450b20SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };" 193112450b20SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() { 19327e71415cSRafael Espindola StringRef Tok = next(); 19337e71415cSRafael Espindola bool IsCXX = Tok == "\"C++\""; 19347e71415cSRafael Espindola if (!IsCXX && Tok != "\"C\"") 1935d0ebd84cSRafael Espindola setError("Unknown language"); 193620b6598cSGeorge Rimar expect("{"); 193720b6598cSGeorge Rimar 193812450b20SRui Ueyama std::vector<SymbolVersion> Ret; 19390ee25a69SRui Ueyama while (!Error && peek() != "}") { 19400ee25a69SRui Ueyama StringRef Tok = next(); 19410ee25a69SRui Ueyama bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok); 19427e71415cSRafael Espindola Ret.push_back({unquote(Tok), IsCXX, HasWildcard}); 194320b6598cSGeorge Rimar expect(";"); 194420b6598cSGeorge Rimar } 194520b6598cSGeorge Rimar 194620b6598cSGeorge Rimar expect("}"); 194720b6598cSGeorge Rimar expect(";"); 194812450b20SRui Ueyama return Ret; 194920b6598cSGeorge Rimar } 195020b6598cSGeorge Rimar 195107320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) { 195222375f24SRui Ueyama ScriptParser(MB).readLinkerScript(); 195320b6598cSGeorge Rimar } 195420b6598cSGeorge Rimar 195520b6598cSGeorge Rimar void elf::readVersionScript(MemoryBufferRef MB) { 195622375f24SRui Ueyama ScriptParser(MB).readVersionScript(); 1957f7c5fbb1SRui Ueyama } 19581ebc8ed7SRui Ueyama 1959d0ebd84cSRafael Espindola void elf::readDynamicList(MemoryBufferRef MB) { 1960d0ebd84cSRafael Espindola ScriptParser(MB).readDynamicList(); 1961d0ebd84cSRafael Espindola } 1962d0ebd84cSRafael Espindola 196307320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>; 196407320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>; 196507320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>; 196607320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>; 1967