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. 11629e0aa5SRui Ueyama // It parses a linker script and write the result to Config or ScriptConfig 12629e0aa5SRui Ueyama // objects. 13629e0aa5SRui Ueyama // 14629e0aa5SRui Ueyama // If SECTIONS command is used, a ScriptConfig contains an AST 15629e0aa5SRui Ueyama // of the command which will later be consumed by createSections() and 16629e0aa5SRui Ueyama // assignAddresses(). 17f7c5fbb1SRui Ueyama // 18f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===// 19f7c5fbb1SRui Ueyama 20717677afSRui Ueyama #include "LinkerScript.h" 21f7c5fbb1SRui Ueyama #include "Config.h" 22f7c5fbb1SRui Ueyama #include "Driver.h" 231ebc8ed7SRui Ueyama #include "InputSection.h" 2455518e7dSRui Ueyama #include "Memory.h" 25652852c5SGeorge Rimar #include "OutputSections.h" 26e77b5bf6SAdhemerval Zanella #include "ScriptParser.h" 2793c9af42SRui Ueyama #include "Strings.h" 28f7c5fbb1SRui Ueyama #include "SymbolTable.h" 2955518e7dSRui Ueyama #include "Symbols.h" 30467c4d55SEugene Leviant #include "Target.h" 31bbe38602SEugene Leviant #include "Writer.h" 3222886a28SEugene Zelenko #include "llvm/ADT/STLExtras.h" 338c6a5aafSRui Ueyama #include "llvm/ADT/SmallString.h" 3422886a28SEugene Zelenko #include "llvm/ADT/StringRef.h" 35960504b9SRui Ueyama #include "llvm/ADT/StringSwitch.h" 3622886a28SEugene Zelenko #include "llvm/Support/Casting.h" 37652852c5SGeorge Rimar #include "llvm/Support/ELF.h" 3822886a28SEugene Zelenko #include "llvm/Support/Endian.h" 3922886a28SEugene Zelenko #include "llvm/Support/ErrorHandling.h" 40f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h" 4122886a28SEugene Zelenko #include "llvm/Support/MathExtras.h" 42f7c5fbb1SRui Ueyama #include "llvm/Support/MemoryBuffer.h" 43f03f3cc1SRui Ueyama #include "llvm/Support/Path.h" 4422886a28SEugene Zelenko #include <algorithm> 4522886a28SEugene Zelenko #include <cassert> 4622886a28SEugene Zelenko #include <cstddef> 4722886a28SEugene Zelenko #include <cstdint> 4822886a28SEugene Zelenko #include <iterator> 4922886a28SEugene Zelenko #include <limits> 5022886a28SEugene Zelenko #include <memory> 5122886a28SEugene Zelenko #include <string> 5222886a28SEugene Zelenko #include <tuple> 5322886a28SEugene Zelenko #include <vector> 54f7c5fbb1SRui Ueyama 55f7c5fbb1SRui Ueyama using namespace llvm; 56652852c5SGeorge Rimar using namespace llvm::ELF; 571ebc8ed7SRui Ueyama using namespace llvm::object; 58e38cbab5SGeorge Rimar using namespace llvm::support::endian; 59f7c5fbb1SRui Ueyama using namespace lld; 60e0df00b9SRafael Espindola using namespace lld::elf; 61f7c5fbb1SRui Ueyama 62884e786dSGeorge Rimar LinkerScriptBase *elf::ScriptBase; 6307320e40SRui Ueyama ScriptConfiguration *elf::ScriptConfig; 64717677afSRui Ueyama 656c55f0e3SGeorge Rimar template <class ELFT> static void addRegular(SymbolAssignment *Cmd) { 663dabfc6bSRafael Espindola uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT; 671bdaf3e3SRui Ueyama Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE, 68463984d4SGeorge Rimar 0, 0, STB_GLOBAL, nullptr, nullptr); 691602421cSRui Ueyama Cmd->Sym = Sym->body(); 7020d03194SEugene Leviant 7120d03194SEugene Leviant // If we have no SECTIONS then we don't have '.' and don't call 7220d03194SEugene Leviant // assignAddresses(). We calculate symbol value immediately in this case. 7320d03194SEugene Leviant if (!ScriptConfig->HasSections) 7420d03194SEugene Leviant cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0); 75ceabe80eSEugene Leviant } 76ceabe80eSEugene Leviant 770c70d3ccSRui Ueyama template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) { 78afaa9343SEugene Leviant // If we have SECTIONS block then output sections haven't been created yet. 79afaa9343SEugene Leviant const OutputSectionBase *Sec = 80afaa9343SEugene Leviant ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section(); 81e1937bb5SGeorge Rimar Symbol *Sym = Symtab<ELFT>::X->addSynthetic( 82afaa9343SEugene Leviant Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT); 831602421cSRui Ueyama Cmd->Sym = Sym->body(); 84afaa9343SEugene Leviant 85afaa9343SEugene Leviant // If we already know section then we can calculate symbol value immediately. 86afaa9343SEugene Leviant if (Sec) 87afaa9343SEugene Leviant cast<DefinedSynthetic<ELFT>>(Cmd->Sym)->Value = 88afaa9343SEugene Leviant Cmd->Expression(0) - Sec->Addr; 89ceabe80eSEugene Leviant } 90ceabe80eSEugene Leviant 91db741e72SEugene Leviant template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) { 922f831dcaSRafael Espindola if (Cmd->Expression.IsAbsolute()) 93db741e72SEugene Leviant addRegular<ELFT>(Cmd); 94db741e72SEugene Leviant else 95db741e72SEugene Leviant addSynthetic<ELFT>(Cmd); 96db741e72SEugene Leviant } 971602421cSRui Ueyama // If a symbol was in PROVIDE(), we need to define it only when 981602421cSRui Ueyama // it is an undefined symbol. 991602421cSRui Ueyama template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) { 1001602421cSRui Ueyama if (Cmd->Name == ".") 101ceabe80eSEugene Leviant return false; 1021602421cSRui Ueyama if (!Cmd->Provide) 103ceabe80eSEugene Leviant return true; 1041602421cSRui Ueyama SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name); 1051602421cSRui Ueyama return B && B->isUndefined(); 106ceabe80eSEugene Leviant } 107ceabe80eSEugene Leviant 108076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) { 109076fe157SGeorge Rimar return C->Kind == AssignmentKind; 110076fe157SGeorge Rimar } 111076fe157SGeorge Rimar 112076fe157SGeorge Rimar bool OutputSectionCommand::classof(const BaseCommand *C) { 113076fe157SGeorge Rimar return C->Kind == OutputSectionKind; 114076fe157SGeorge Rimar } 115076fe157SGeorge Rimar 116eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) { 117eea3114fSGeorge Rimar return C->Kind == InputSectionKind; 118eea3114fSGeorge Rimar } 119eea3114fSGeorge Rimar 120eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) { 121eefa758eSGeorge Rimar return C->Kind == AssertKind; 122eefa758eSGeorge Rimar } 123eefa758eSGeorge Rimar 124e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) { 125e38cbab5SGeorge Rimar return C->Kind == BytesDataKind; 126e38cbab5SGeorge Rimar } 127e38cbab5SGeorge Rimar 12822886a28SEugene Zelenko template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default; 12922886a28SEugene Zelenko template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default; 130f34d0e08SRui Ueyama 13107320e40SRui Ueyama template <class ELFT> 13207320e40SRui Ueyama bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) { 133cf43f179SEugene Leviant for (InputSectionDescription *ID : Opt.KeptSections) { 134cf43f179SEugene Leviant StringRef Filename = S->getFile()->getName(); 135f91282e1SRui Ueyama if (!ID->FilePat.match(sys::path::filename(Filename))) 136cf43f179SEugene Leviant continue; 137cf43f179SEugene Leviant 138cf43f179SEugene Leviant for (SectionPattern &P : ID->SectionPatterns) 139f91282e1SRui Ueyama if (P.SectionPat.match(S->Name)) 140eea3114fSGeorge Rimar return true; 141cf43f179SEugene Leviant } 142eea3114fSGeorge Rimar return false; 143eea3114fSGeorge Rimar } 144eea3114fSGeorge Rimar 145575208caSGeorge Rimar static bool comparePriority(InputSectionData *A, InputSectionData *B) { 146575208caSGeorge Rimar return getPriority(A->Name) < getPriority(B->Name); 147575208caSGeorge Rimar } 148575208caSGeorge Rimar 149c0028d3dSRafael Espindola static bool compareName(InputSectionData *A, InputSectionData *B) { 150042a3f20SRafael Espindola return A->Name < B->Name; 1510702c4e8SGeorge Rimar } 152742c3836SRui Ueyama 153c0028d3dSRafael Espindola static bool compareAlignment(InputSectionData *A, InputSectionData *B) { 154742c3836SRui Ueyama // ">" is not a mistake. Larger alignments are placed before smaller 155742c3836SRui Ueyama // alignments in order to reduce the amount of padding necessary. 156742c3836SRui Ueyama // This is compatible with GNU. 157742c3836SRui Ueyama return A->Alignment > B->Alignment; 158742c3836SRui Ueyama } 159742c3836SRui Ueyama 160c0028d3dSRafael Espindola static std::function<bool(InputSectionData *, InputSectionData *)> 161be394db3SGeorge Rimar getComparator(SortSectionPolicy K) { 162be394db3SGeorge Rimar switch (K) { 163be394db3SGeorge Rimar case SortSectionPolicy::Alignment: 164c0028d3dSRafael Espindola return compareAlignment; 165be394db3SGeorge Rimar case SortSectionPolicy::Name: 166be394db3SGeorge Rimar return compareName; 167be394db3SGeorge Rimar case SortSectionPolicy::Priority: 168be394db3SGeorge Rimar return comparePriority; 169be394db3SGeorge Rimar default: 170be394db3SGeorge Rimar llvm_unreachable("unknown sort policy"); 171be394db3SGeorge Rimar } 172742c3836SRui Ueyama } 1730702c4e8SGeorge Rimar 17448c3f1ceSRui Ueyama template <class ELFT> 175e71a3f8aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections, 17606ae6836SGeorge Rimar ConstraintKind Kind) { 1778f66df92SGeorge Rimar if (Kind == ConstraintKind::NoConstraint) 1788f66df92SGeorge Rimar return true; 179e746e52cSRafael Espindola bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) { 180d3190795SRafael Espindola auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2); 1811854a8ebSRafael Espindola return Sec->Flags & SHF_WRITE; 18206ae6836SGeorge Rimar }); 183e746e52cSRafael Espindola return (IsRW && Kind == ConstraintKind::ReadWrite) || 184e746e52cSRafael Espindola (!IsRW && Kind == ConstraintKind::ReadOnly); 18506ae6836SGeorge Rimar } 18606ae6836SGeorge Rimar 18707171f21SGeorge Rimar static void sortSections(InputSectionData **Begin, InputSectionData **End, 188ee924709SRui Ueyama SortSectionPolicy K) { 189ee924709SRui Ueyama if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None) 19007171f21SGeorge Rimar std::stable_sort(Begin, End, getComparator(K)); 191ee924709SRui Ueyama } 192ee924709SRui Ueyama 193d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches. 194be94e1b6SRafael Espindola template <class ELFT> 195e71a3f8aSRafael Espindola void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) { 1964dc07becSRui Ueyama // Collects all sections that satisfy constraints of I 1974dc07becSRui Ueyama // and attach them to I. 1984dc07becSRui Ueyama for (SectionPattern &Pat : I->SectionPatterns) { 19907171f21SGeorge Rimar size_t SizeBefore = I->Sections.size(); 2008c6a5aafSRui Ueyama 2018c6a5aafSRui Ueyama for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) { 2028f9026baSRafael Espindola if (!S->Live || S->OutSec) 2038c6a5aafSRui Ueyama continue; 2048c6a5aafSRui Ueyama 2058c6a5aafSRui Ueyama StringRef Filename; 2068c6a5aafSRui Ueyama if (elf::ObjectFile<ELFT> *F = S->getFile()) 2078c6a5aafSRui Ueyama Filename = sys::path::filename(F->getName()); 2088c6a5aafSRui Ueyama 209e8a6102fSRui Ueyama if (I->FilePat.match(Filename) && !Pat.ExcludedFilePat.match(Filename) && 210e8a6102fSRui Ueyama Pat.SectionPat.match(S->Name)) 211d3190795SRafael Espindola I->Sections.push_back(S); 212395281cfSGeorge Rimar } 213d3190795SRafael Espindola 214ee924709SRui Ueyama // Sort sections as instructed by SORT-family commands and --sort-section 215ee924709SRui Ueyama // option. Because SORT-family commands can be nested at most two depth 216ee924709SRui Ueyama // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command 217ee924709SRui Ueyama // line option is respected even if a SORT command is given, the exact 218ee924709SRui Ueyama // behavior we have here is a bit complicated. Here are the rules. 219ee924709SRui Ueyama // 220ee924709SRui Ueyama // 1. If two SORT commands are given, --sort-section is ignored. 221ee924709SRui Ueyama // 2. If one SORT command is given, and if it is not SORT_NONE, 222ee924709SRui Ueyama // --sort-section is handled as an inner SORT command. 223ee924709SRui Ueyama // 3. If one SORT command is given, and if it is SORT_NONE, don't sort. 224ee924709SRui Ueyama // 4. If no SORT command is given, sort according to --sort-section. 22507171f21SGeorge Rimar InputSectionData **Begin = I->Sections.data() + SizeBefore; 22607171f21SGeorge Rimar InputSectionData **End = I->Sections.data() + I->Sections.size(); 22707171f21SGeorge Rimar if (Pat.SortOuter != SortSectionPolicy::None) { 22807171f21SGeorge Rimar if (Pat.SortInner == SortSectionPolicy::Default) 22907171f21SGeorge Rimar sortSections(Begin, End, Config->SortSection); 230ee924709SRui Ueyama else 23107171f21SGeorge Rimar sortSections(Begin, End, Pat.SortInner); 23207171f21SGeorge Rimar sortSections(Begin, End, Pat.SortOuter); 23307171f21SGeorge Rimar } 234ee924709SRui Ueyama } 235d3190795SRafael Espindola 236d3190795SRafael Espindola // We do not add duplicate input sections, so mark them with a dummy output 237d3190795SRafael Espindola // section for now. 238d3190795SRafael Espindola for (InputSectionData *S : I->Sections) { 239d3190795SRafael Espindola auto *S2 = static_cast<InputSectionBase<ELFT> *>(S); 240e08e78dfSRafael Espindola S2->OutSec = (OutputSectionBase *)-1; 241d3190795SRafael Espindola } 242be94e1b6SRafael Espindola } 243be94e1b6SRafael Espindola 244be94e1b6SRafael Espindola template <class ELFT> 245be94e1b6SRafael Espindola void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) { 246be94e1b6SRafael Espindola for (InputSectionBase<ELFT> *S : V) { 247be94e1b6SRafael Espindola S->Live = false; 248be94e1b6SRafael Espindola reportDiscarded(S); 249be94e1b6SRafael Espindola } 250be94e1b6SRafael Espindola } 251be94e1b6SRafael Espindola 25206ae6836SGeorge Rimar template <class ELFT> 2530b9ce6a4SRui Ueyama std::vector<InputSectionBase<ELFT> *> 25406ae6836SGeorge Rimar LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) { 2550b9ce6a4SRui Ueyama std::vector<InputSectionBase<ELFT> *> Ret; 256e7f912cdSRui Ueyama 25706ae6836SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) { 2587c3ff2ebSRafael Espindola auto *Cmd = dyn_cast<InputSectionDescription>(Base.get()); 2597c3ff2ebSRafael Espindola if (!Cmd) 2600b9ce6a4SRui Ueyama continue; 261e71a3f8aSRafael Espindola computeInputSections(Cmd); 262d3190795SRafael Espindola for (InputSectionData *S : Cmd->Sections) 263d3190795SRafael Espindola Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S)); 2640b9ce6a4SRui Ueyama } 265e71a3f8aSRafael Espindola 266cc1ba8c7SEugene Leviant // After we created final list we should now set OutSec pointer to null, 267cc1ba8c7SEugene Leviant // instead of -1. Otherwise we may get a crash when writing relocs, in 268cc1ba8c7SEugene Leviant // case section is discarded by linker script 269cc1ba8c7SEugene Leviant for (InputSectionBase<ELFT> *S : Ret) 270cc1ba8c7SEugene Leviant S->OutSec = nullptr; 271cc1ba8c7SEugene Leviant 2720b9ce6a4SRui Ueyama return Ret; 2730b9ce6a4SRui Ueyama } 2740b9ce6a4SRui Ueyama 275e5d3ca50SPetr Hosek template <class ELFT> 27610897f18SRafael Espindola static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C, 27710897f18SRafael Espindola StringRef OutsecName) { 27810897f18SRafael Espindola // When using linker script the merge rules are different. 27910897f18SRafael Espindola // Unfortunately, linker scripts are name based. This means that expressions 28010897f18SRafael Espindola // like *(.foo*) can refer to multiple input sections that would normally be 28110897f18SRafael Espindola // placed in different output sections. We cannot put them in different 28210897f18SRafael Espindola // output sections or we would produce wrong results for 28310897f18SRafael Espindola // start = .; *(.foo.*) end = .; *(.bar) 28410897f18SRafael Espindola // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to 28510897f18SRafael Espindola // another. The problem is that there is no way to layout those output 28610897f18SRafael Espindola // sections such that the .foo sections are the only thing between the 28710897f18SRafael Espindola // start and end symbols. 28810897f18SRafael Espindola 28910897f18SRafael Espindola // An extra annoyance is that we cannot simply disable merging of the contents 29010897f18SRafael Espindola // of SHF_MERGE sections, but our implementation requires one output section 29110897f18SRafael Espindola // per "kind" (string or not, which size/aligment). 29210897f18SRafael Espindola // Fortunately, creating symbols in the middle of a merge section is not 29310897f18SRafael Espindola // supported by bfd or gold, so we can just create multiple section in that 29410897f18SRafael Espindola // case. 29510897f18SRafael Espindola typedef typename ELFT::uint uintX_t; 2961854a8ebSRafael Espindola uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS); 29710897f18SRafael Espindola 29810897f18SRafael Espindola uintX_t Alignment = 0; 29910897f18SRafael Espindola if (isa<MergeInputSection<ELFT>>(C)) 3001854a8ebSRafael Espindola Alignment = std::max<uintX_t>(C->Alignment, C->Entsize); 30110897f18SRafael Espindola 30210897f18SRafael Espindola return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment}; 30310897f18SRafael Espindola } 30410897f18SRafael Espindola 30510897f18SRafael Espindola template <class ELFT> 30620d03194SEugene Leviant void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory, 30720d03194SEugene Leviant InputSectionBase<ELFT> *Sec, 30820d03194SEugene Leviant StringRef Name) { 309e08e78dfSRafael Espindola OutputSectionBase *OutSec; 31028c1597aSRafael Espindola bool IsNew; 31110897f18SRafael Espindola std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec); 31228c1597aSRafael Espindola if (IsNew) 31328c1597aSRafael Espindola OutputSections->push_back(OutSec); 31420d03194SEugene Leviant OutSec->addSection(Sec); 31520d03194SEugene Leviant } 31620d03194SEugene Leviant 31720d03194SEugene Leviant template <class ELFT> 31820d03194SEugene Leviant void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) { 3197c3ff2ebSRafael Espindola for (unsigned I = 0; I < Opt.Commands.size(); ++I) { 3207c3ff2ebSRafael Espindola auto Iter = Opt.Commands.begin() + I; 3217c3ff2ebSRafael Espindola const std::unique_ptr<BaseCommand> &Base1 = *Iter; 3222ab5f73dSRui Ueyama if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) { 3232ab5f73dSRui Ueyama if (shouldDefine<ELFT>(Cmd)) 324b0de56b5SRafael Espindola addSymbol<ELFT>(Cmd); 3252ab5f73dSRui Ueyama continue; 3262ab5f73dSRui Ueyama } 32720d03194SEugene Leviant if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) { 32820d03194SEugene Leviant // If we don't have SECTIONS then output sections have already been 329194470cdSGeorge Rimar // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses 33020d03194SEugene Leviant // will not be called, so ASSERT should be evaluated now. 33120d03194SEugene Leviant if (!Opt.HasSections) 33220d03194SEugene Leviant Cmd->Expression(0); 33320d03194SEugene Leviant continue; 33420d03194SEugene Leviant } 3352ab5f73dSRui Ueyama 336ceabe80eSEugene Leviant if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) { 3377bd37870SRafael Espindola std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd); 3387bd37870SRafael Espindola 33948c3f1ceSRui Ueyama if (Cmd->Name == "/DISCARD/") { 3407bd37870SRafael Espindola discard(V); 34148c3f1ceSRui Ueyama continue; 34248c3f1ceSRui Ueyama } 3430b9ce6a4SRui Ueyama 3447c3ff2ebSRafael Espindola if (!matchConstraints<ELFT>(V, Cmd->Constraint)) { 3457c3ff2ebSRafael Espindola for (InputSectionBase<ELFT> *S : V) 3467c3ff2ebSRafael Espindola S->OutSec = nullptr; 3477c3ff2ebSRafael Espindola Opt.Commands.erase(Iter); 348dfbbbc86SGeorge Rimar --I; 3497c3ff2ebSRafael Espindola continue; 3507c3ff2ebSRafael Espindola } 3517c3ff2ebSRafael Espindola 3527c3ff2ebSRafael Espindola for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands) 3537c3ff2ebSRafael Espindola if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) 3547c3ff2ebSRafael Espindola if (shouldDefine<ELFT>(OutCmd)) 3557c3ff2ebSRafael Espindola addSymbol<ELFT>(OutCmd); 3567c3ff2ebSRafael Espindola 35797403d15SEugene Leviant if (V.empty()) 3580b9ce6a4SRui Ueyama continue; 3590b9ce6a4SRui Ueyama 360a14b13d8SGeorge Rimar for (InputSectionBase<ELFT> *Sec : V) { 36120d03194SEugene Leviant addSection(Factory, Sec, Cmd->Name); 36220d03194SEugene Leviant if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0) 363db24d9c3SGeorge Rimar Sec->Alignment = Subalign; 36420d03194SEugene Leviant } 365eea3114fSGeorge Rimar } 36648c3f1ceSRui Ueyama } 367db24d9c3SGeorge Rimar } 368e63d81bdSEugene Leviant 36920d03194SEugene Leviant template <class ELFT> 37020d03194SEugene Leviant void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) { 37120d03194SEugene Leviant processCommands(Factory); 3728c6a5aafSRui Ueyama 3730b9ce6a4SRui Ueyama // Add orphan sections. 3748c6a5aafSRui Ueyama for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) 3758f9026baSRafael Espindola if (S->Live && !S->OutSec) 37655518e7dSRui Ueyama addSection(Factory, S, getOutputSectionName(S->Name)); 377e63d81bdSEugene Leviant } 378e63d81bdSEugene Leviant 379db741e72SEugene Leviant // Sets value of a section-defined symbol. Two kinds of 380db741e72SEugene Leviant // symbols are processed: synthetic symbols, whose value 381db741e72SEugene Leviant // is an offset from beginning of section and regular 382db741e72SEugene Leviant // symbols whose value is absolute. 383db741e72SEugene Leviant template <class ELFT> 384afaa9343SEugene Leviant static void assignSectionSymbol(SymbolAssignment *Cmd, 385498ed714SRafael Espindola typename ELFT::uint Value) { 386db741e72SEugene Leviant if (!Cmd->Sym) 387db741e72SEugene Leviant return; 388db741e72SEugene Leviant 389db741e72SEugene Leviant if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) { 390afaa9343SEugene Leviant Body->Section = Cmd->Expression.Section(); 391afaa9343SEugene Leviant Body->Value = Cmd->Expression(Value) - Body->Section->Addr; 392db741e72SEugene Leviant return; 393db741e72SEugene Leviant } 394db741e72SEugene Leviant auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym); 395498ed714SRafael Espindola Body->Value = Cmd->Expression(Value); 396db741e72SEugene Leviant } 397db741e72SEugene Leviant 398e08e78dfSRafael Espindola template <class ELFT> static bool isTbss(OutputSectionBase *Sec) { 39904a2e348SRafael Espindola return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS; 400a940e539SRafael Espindola } 401a940e539SRafael Espindola 402d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) { 403d3190795SRafael Espindola if (!AlreadyOutputIS.insert(S).second) 404ceabe80eSEugene Leviant return; 405e08e78dfSRafael Espindola bool IsTbss = isTbss<ELFT>(CurOutSec); 406d3190795SRafael Espindola 407d3190795SRafael Espindola uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot; 408d3190795SRafael Espindola Pos = alignTo(Pos, S->Alignment); 40904a2e348SRafael Espindola S->OutSecOff = Pos - CurOutSec->Addr; 410d3190795SRafael Espindola Pos += S->getSize(); 411d3190795SRafael Espindola 412d3190795SRafael Espindola // Update output section size after adding each section. This is so that 413d3190795SRafael Espindola // SIZEOF works correctly in the case below: 414d3190795SRafael Espindola // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) } 41504a2e348SRafael Espindola CurOutSec->Size = Pos - CurOutSec->Addr; 416d3190795SRafael Espindola 4177252ae52SRafael Espindola if (IsTbss) 4187252ae52SRafael Espindola ThreadBssOffset = Pos - Dot; 4197252ae52SRafael Espindola else 420d3190795SRafael Espindola Dot = Pos; 4212de509c3SRui Ueyama } 422ceabe80eSEugene Leviant 423d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::flush() { 42465499b90SRafael Espindola if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second) 42565499b90SRafael Espindola return; 42665499b90SRafael Espindola if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) { 427d3190795SRafael Espindola for (InputSection<ELFT> *I : OutSec->Sections) 428d3190795SRafael Espindola output(I); 42965499b90SRafael Espindola } else { 43004a2e348SRafael Espindola Dot += CurOutSec->Size; 431d3190795SRafael Espindola } 432d3190795SRafael Espindola } 43397403d15SEugene Leviant 434d3190795SRafael Espindola template <class ELFT> 435e08e78dfSRafael Espindola void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) { 436d3190795SRafael Espindola if (CurOutSec == Sec) 437d3190795SRafael Espindola return; 438d3190795SRafael Espindola if (AlreadyOutputOS.count(Sec)) 439d3190795SRafael Espindola return; 440d3190795SRafael Espindola 441d3190795SRafael Espindola flush(); 442d3190795SRafael Espindola CurOutSec = Sec; 443d3190795SRafael Espindola 44404a2e348SRafael Espindola Dot = alignTo(Dot, CurOutSec->Addralign); 445e08e78dfSRafael Espindola CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot; 446b71d6f7aSEugene Leviant 447b71d6f7aSEugene Leviant // If neither AT nor AT> is specified for an allocatable section, the linker 448b71d6f7aSEugene Leviant // will set the LMA such that the difference between VMA and LMA for the 449b71d6f7aSEugene Leviant // section is the same as the preceding output section in the same region 450b71d6f7aSEugene Leviant // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html 451b71d6f7aSEugene Leviant CurOutSec->setLMAOffset(LMAOffset); 452d3190795SRafael Espindola } 453d3190795SRafael Espindola 454d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) { 455e38cbab5SGeorge Rimar // This handles the assignments to symbol or to a location counter (.) 456d3190795SRafael Espindola if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) { 45797403d15SEugene Leviant if (AssignCmd->Name == ".") { 45897403d15SEugene Leviant // Update to location counter means update to section size. 459d3190795SRafael Espindola Dot = AssignCmd->Expression(Dot); 46004a2e348SRafael Espindola CurOutSec->Size = Dot - CurOutSec->Addr; 461d3190795SRafael Espindola return; 46297403d15SEugene Leviant } 463afaa9343SEugene Leviant assignSectionSymbol<ELFT>(AssignCmd, Dot); 464d3190795SRafael Espindola return; 46597403d15SEugene Leviant } 466e38cbab5SGeorge Rimar 467e38cbab5SGeorge Rimar // Handle BYTE(), SHORT(), LONG(), or QUAD(). 468e38cbab5SGeorge Rimar if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) { 46904a2e348SRafael Espindola DataCmd->Offset = Dot - CurOutSec->Addr; 470e38cbab5SGeorge Rimar Dot += DataCmd->Size; 47104a2e348SRafael Espindola CurOutSec->Size = Dot - CurOutSec->Addr; 472e38cbab5SGeorge Rimar return; 473e38cbab5SGeorge Rimar } 474e38cbab5SGeorge Rimar 475e38cbab5SGeorge Rimar // It handles single input section description command, 476e38cbab5SGeorge Rimar // calculates and assigns the offsets for each section and also 477e38cbab5SGeorge Rimar // updates the output section size. 478d3190795SRafael Espindola auto &ICmd = cast<InputSectionDescription>(Base); 479d3190795SRafael Espindola for (InputSectionData *ID : ICmd.Sections) { 480d3190795SRafael Espindola auto *IB = static_cast<InputSectionBase<ELFT> *>(ID); 481d3190795SRafael Espindola switchTo(IB->OutSec); 482d3190795SRafael Espindola if (auto *I = dyn_cast<InputSection<ELFT>>(IB)) 483d3190795SRafael Espindola output(I); 48465499b90SRafael Espindola else 48565499b90SRafael Espindola flush(); 486ceabe80eSEugene Leviant } 487ceabe80eSEugene Leviant } 488ceabe80eSEugene Leviant 4898f66df92SGeorge Rimar template <class ELFT> 490e08e78dfSRafael Espindola static std::vector<OutputSectionBase *> 491e08e78dfSRafael Espindola findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) { 492e08e78dfSRafael Espindola std::vector<OutputSectionBase *> Ret; 493e08e78dfSRafael Espindola for (OutputSectionBase *Sec : Sections) 4949257764dSEugene Leviant if (Sec->getName() == Name) 495a14b13d8SGeorge Rimar Ret.push_back(Sec); 496a14b13d8SGeorge Rimar return Ret; 4978f66df92SGeorge Rimar } 4988f66df92SGeorge Rimar 499d3190795SRafael Espindola template <class ELFT> 500d3190795SRafael Espindola void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) { 501b71d6f7aSEugene Leviant if (Cmd->LMAExpr) 502b71d6f7aSEugene Leviant LMAOffset = Cmd->LMAExpr(Dot) - Dot; 503e08e78dfSRafael Espindola std::vector<OutputSectionBase *> Sections = 504e08e78dfSRafael Espindola findSections<ELFT>(Cmd->Name, *OutputSections); 505d3190795SRafael Espindola if (Sections.empty()) 506d3190795SRafael Espindola return; 507d3190795SRafael Espindola switchTo(Sections[0]); 508d3190795SRafael Espindola // Find the last section output location. We will output orphan sections 509d3190795SRafael Espindola // there so that end symbols point to the correct location. 510d3190795SRafael Espindola auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(), 511d3190795SRafael Espindola [](const std::unique_ptr<BaseCommand> &Cmd) { 512d3190795SRafael Espindola return !isa<SymbolAssignment>(*Cmd); 513d3190795SRafael Espindola }) 514d3190795SRafael Espindola .base(); 515d3190795SRafael Espindola for (auto I = Cmd->Commands.begin(); I != E; ++I) 516d3190795SRafael Espindola process(**I); 517e08e78dfSRafael Espindola for (OutputSectionBase *Base : Sections) 518d3190795SRafael Espindola switchTo(Base); 5192506cb4dSEugene Leviant flush(); 520b31dd370SGeorge Rimar std::for_each(E, Cmd->Commands.end(), 521b31dd370SGeorge Rimar [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); }); 522d3190795SRafael Espindola } 523d3190795SRafael Espindola 52407fe6129SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() { 5256d38e4dbSRafael Espindola // It is common practice to use very generic linker scripts. So for any 5266d38e4dbSRafael Espindola // given run some of the output sections in the script will be empty. 5276d38e4dbSRafael Espindola // We could create corresponding empty output sections, but that would 5286d38e4dbSRafael Espindola // clutter the output. 5296d38e4dbSRafael Espindola // We instead remove trivially empty sections. The bfd linker seems even 5306d38e4dbSRafael Espindola // more aggressive at removing them. 5316d38e4dbSRafael Espindola auto Pos = std::remove_if( 5326d38e4dbSRafael Espindola Opt.Commands.begin(), Opt.Commands.end(), 5336d38e4dbSRafael Espindola [&](const std::unique_ptr<BaseCommand> &Base) { 5346d38e4dbSRafael Espindola auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 5356d38e4dbSRafael Espindola if (!Cmd) 5366d38e4dbSRafael Espindola return false; 5376a53737cSRafael Espindola return findSections<ELFT>(Cmd->Name, *OutputSections).empty(); 5386d38e4dbSRafael Espindola }); 5396d38e4dbSRafael Espindola Opt.Commands.erase(Pos, Opt.Commands.end()); 54007fe6129SRafael Espindola } 54107fe6129SRafael Espindola 5426a53737cSRafael Espindola static bool isAllSectionDescription(const OutputSectionCommand &Cmd) { 5436a53737cSRafael Espindola for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands) 5446a53737cSRafael Espindola if (!isa<InputSectionDescription>(*I)) 5456a53737cSRafael Espindola return false; 5466a53737cSRafael Espindola return true; 5476a53737cSRafael Espindola } 5486d38e4dbSRafael Espindola 5496a53737cSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() { 5509546fffbSRafael Espindola // If the output section contains only symbol assignments, create a 5519546fffbSRafael Espindola // corresponding output section. The bfd linker seems to only create them if 5529546fffbSRafael Espindola // '.' is assigned to, but creating these section should not have any bad 5539546fffbSRafael Espindola // consequeces and gives us a section to put the symbol in. 5549546fffbSRafael Espindola uintX_t Flags = SHF_ALLOC; 5559546fffbSRafael Espindola uint32_t Type = 0; 5569546fffbSRafael Espindola for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 5579546fffbSRafael Espindola auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 5589546fffbSRafael Espindola if (!Cmd) 5599546fffbSRafael Espindola continue; 560e08e78dfSRafael Espindola std::vector<OutputSectionBase *> Secs = 561e08e78dfSRafael Espindola findSections<ELFT>(Cmd->Name, *OutputSections); 5629546fffbSRafael Espindola if (!Secs.empty()) { 56304a2e348SRafael Espindola Flags = Secs[0]->Flags; 56404a2e348SRafael Espindola Type = Secs[0]->Type; 5659546fffbSRafael Espindola continue; 5669546fffbSRafael Espindola } 5679546fffbSRafael Espindola 5686a53737cSRafael Espindola if (isAllSectionDescription(*Cmd)) 5696a53737cSRafael Espindola continue; 5706a53737cSRafael Espindola 57195642b95SRui Ueyama auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags); 5729546fffbSRafael Espindola OutputSections->push_back(OutSec); 5739546fffbSRafael Espindola } 574f7a17448SRafael Espindola } 575f7a17448SRafael Espindola 576f7a17448SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() { 577f7a17448SRafael Espindola placeOrphanSections(); 578f7a17448SRafael Espindola 579f7a17448SRafael Espindola // If output section command doesn't specify any segments, 580f7a17448SRafael Espindola // and we haven't previously assigned any section to segment, 581f7a17448SRafael Espindola // then we simply assign section to the very first load segment. 582f7a17448SRafael Espindola // Below is an example of such linker script: 583f7a17448SRafael Espindola // PHDRS { seg PT_LOAD; } 584f7a17448SRafael Espindola // SECTIONS { .aaa : { *(.aaa) } } 585f7a17448SRafael Espindola std::vector<StringRef> DefPhdrs; 586f7a17448SRafael Espindola auto FirstPtLoad = 587f7a17448SRafael Espindola std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(), 588f7a17448SRafael Espindola [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; }); 589f7a17448SRafael Espindola if (FirstPtLoad != Opt.PhdrsCommands.end()) 590f7a17448SRafael Espindola DefPhdrs.push_back(FirstPtLoad->Name); 591f7a17448SRafael Espindola 592f7a17448SRafael Espindola // Walk the commands and propagate the program headers to commands that don't 593f7a17448SRafael Espindola // explicitly specify them. 594f7a17448SRafael Espindola for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 595f7a17448SRafael Espindola auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 596f7a17448SRafael Espindola if (!Cmd) 597f7a17448SRafael Espindola continue; 598f7a17448SRafael Espindola if (Cmd->Phdrs.empty()) 599f7a17448SRafael Espindola Cmd->Phdrs = DefPhdrs; 600f7a17448SRafael Espindola else 601f7a17448SRafael Espindola DefPhdrs = Cmd->Phdrs; 602f7a17448SRafael Espindola } 6036a53737cSRafael Espindola 6046a53737cSRafael Espindola removeEmptyCommands(); 6059546fffbSRafael Espindola } 6069546fffbSRafael Espindola 60715c57951SRafael Espindola // When placing orphan sections, we want to place them after symbol assignments 60815c57951SRafael Espindola // so that an orphan after 60915c57951SRafael Espindola // begin_foo = .; 61015c57951SRafael Espindola // foo : { *(foo) } 61115c57951SRafael Espindola // end_foo = .; 61215c57951SRafael Espindola // doesn't break the intended meaning of the begin/end symbols. 61315c57951SRafael Espindola // We don't want to go over sections since Writer<ELFT>::sortSections is the 61415c57951SRafael Espindola // one in charge of deciding the order of the sections. 61515c57951SRafael Espindola // We don't want to go over alignments, since doing so in 61615c57951SRafael Espindola // rx_sec : { *(rx_sec) } 61715c57951SRafael Espindola // . = ALIGN(0x1000); 61815c57951SRafael Espindola // /* The RW PT_LOAD starts here*/ 61915c57951SRafael Espindola // rw_sec : { *(rw_sec) } 62015c57951SRafael Espindola // would mean that the RW PT_LOAD would become unaligned. 62115c57951SRafael Espindola static bool shouldSkip(const BaseCommand &Cmd) { 62215c57951SRafael Espindola if (isa<OutputSectionCommand>(Cmd)) 62315c57951SRafael Espindola return false; 62415c57951SRafael Espindola const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd); 62515c57951SRafael Espindola if (!Assign) 62615c57951SRafael Espindola return true; 62715c57951SRafael Espindola return Assign->Name != "."; 62815c57951SRafael Espindola } 62915c57951SRafael Espindola 630337f903cSRafael Espindola // Orphan sections are sections present in the input files which are not 631337f903cSRafael Espindola // explicitly placed into the output file by the linker script. This just 632337f903cSRafael Espindola // places them in the order already decided in OutputSections. 6336d91fce5SRafael Espindola template <class ELFT> 634337f903cSRafael Espindola void LinkerScript<ELFT>::placeOrphanSections() { 635aab6d5c5SRafael Espindola // The OutputSections are already in the correct order. 636aab6d5c5SRafael Espindola // This loops creates or moves commands as needed so that they are in the 637aab6d5c5SRafael Espindola // correct order. 638aab6d5c5SRafael Espindola int CmdIndex = 0; 639e08e78dfSRafael Espindola for (OutputSectionBase *Sec : *OutputSections) { 640652852c5SGeorge Rimar StringRef Name = Sec->getName(); 641aab6d5c5SRafael Espindola 642aab6d5c5SRafael Espindola // Find the last spot where we can insert a command and still get the 64315c57951SRafael Espindola // correct result. 644aab6d5c5SRafael Espindola auto CmdIter = Opt.Commands.begin() + CmdIndex; 645aab6d5c5SRafael Espindola auto E = Opt.Commands.end(); 64615c57951SRafael Espindola while (CmdIter != E && shouldSkip(**CmdIter)) { 647aab6d5c5SRafael Espindola ++CmdIter; 648aab6d5c5SRafael Espindola ++CmdIndex; 649aab6d5c5SRafael Espindola } 650aab6d5c5SRafael Espindola 651aab6d5c5SRafael Espindola auto Pos = 652aab6d5c5SRafael Espindola std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) { 653aab6d5c5SRafael Espindola auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 654aab6d5c5SRafael Espindola return Cmd && Cmd->Name == Name; 655aab6d5c5SRafael Espindola }); 656aab6d5c5SRafael Espindola if (Pos == E) { 657aab6d5c5SRafael Espindola Opt.Commands.insert(CmdIter, 658aab6d5c5SRafael Espindola llvm::make_unique<OutputSectionCommand>(Name)); 659aab6d5c5SRafael Espindola ++CmdIndex; 66015c57951SRafael Espindola continue; 66115c57951SRafael Espindola } 66215c57951SRafael Espindola 66315c57951SRafael Espindola // Continue from where we found it. 66415c57951SRafael Espindola CmdIndex = (Pos - Opt.Commands.begin()) + 1; 665652852c5SGeorge Rimar } 666337f903cSRafael Espindola } 667337f903cSRafael Espindola 668337f903cSRafael Espindola template <class ELFT> 669337f903cSRafael Espindola void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) { 6707c18c28cSRui Ueyama // Assign addresses as instructed by linker script SECTIONS sub-commands. 671be607334SRafael Espindola Dot = 0; 672652852c5SGeorge Rimar 673076fe157SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 674076fe157SGeorge Rimar if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) { 6758d083e6aSRui Ueyama if (Cmd->Name == ".") { 6768d083e6aSRui Ueyama Dot = Cmd->Expression(Dot); 6778d083e6aSRui Ueyama } else if (Cmd->Sym) { 678afaa9343SEugene Leviant assignSectionSymbol<ELFT>(Cmd, Dot); 6798d083e6aSRui Ueyama } 68005ef4cffSRui Ueyama continue; 681652852c5SGeorge Rimar } 682652852c5SGeorge Rimar 683eefa758eSGeorge Rimar if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) { 684eefa758eSGeorge Rimar Cmd->Expression(Dot); 685eefa758eSGeorge Rimar continue; 686eefa758eSGeorge Rimar } 687eefa758eSGeorge Rimar 688076fe157SGeorge Rimar auto *Cmd = cast<OutputSectionCommand>(Base.get()); 689652852c5SGeorge Rimar 69058e5c4dcSGeorge Rimar if (Cmd->AddrExpr) 69158e5c4dcSGeorge Rimar Dot = Cmd->AddrExpr(Dot); 69258e5c4dcSGeorge Rimar 693d3190795SRafael Espindola assignOffsets(Cmd); 694a14b13d8SGeorge Rimar } 695467c4d55SEugene Leviant 696aab6d5c5SRafael Espindola uintX_t MinVA = std::numeric_limits<uintX_t>::max(); 697e08e78dfSRafael Espindola for (OutputSectionBase *Sec : *OutputSections) { 69804a2e348SRafael Espindola if (Sec->Flags & SHF_ALLOC) 699e08e78dfSRafael Espindola MinVA = std::min<uint64_t>(MinVA, Sec->Addr); 700aab6d5c5SRafael Espindola else 70104a2e348SRafael Espindola Sec->Addr = 0; 702aab6d5c5SRafael Espindola } 703aab6d5c5SRafael Espindola 7040d4b6d5cSRafael Espindola uintX_t HeaderSize = getHeaderSize(); 7056d91fce5SRafael Espindola auto FirstPTLoad = 7066d91fce5SRafael Espindola std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) { 7076d91fce5SRafael Espindola return E.H.p_type == PT_LOAD; 7086d91fce5SRafael Espindola }); 709db35fdf7SEugene Leviant 7106d91fce5SRafael Espindola if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) { 711db35fdf7SEugene Leviant // If linker script specifies program headers and first PT_LOAD doesn't 712db35fdf7SEugene Leviant // have both PHDRS and FILEHDR attributes then do nothing 713db35fdf7SEugene Leviant if (!Opt.PhdrsCommands.empty()) { 714db35fdf7SEugene Leviant size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad); 715db35fdf7SEugene Leviant if (!Opt.PhdrsCommands[SegNum].HasPhdrs || 716db35fdf7SEugene Leviant !Opt.PhdrsCommands[SegNum].HasFilehdr) 717db35fdf7SEugene Leviant return; 718db35fdf7SEugene Leviant } 71964c32d6fSRafael Espindola // ELF and Program headers need to be right before the first section in 720b91e7118SGeorge Rimar // memory. Set their addresses accordingly. 7214ec013acSRafael Espindola MinVA = alignDown(MinVA - HeaderSize, Target->PageSize); 72204a2e348SRafael Espindola Out<ELFT>::ElfHeader->Addr = MinVA; 72304a2e348SRafael Espindola Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA; 7246d91fce5SRafael Espindola FirstPTLoad->First = Out<ELFT>::ElfHeader; 7256d91fce5SRafael Espindola if (!FirstPTLoad->Last) 7266d91fce5SRafael Espindola FirstPTLoad->Last = Out<ELFT>::ProgramHeaders; 727cd8eaf89SEugene Leviant } else if (!FirstPTLoad->First) { 728cd8eaf89SEugene Leviant // Sometimes the very first PT_LOAD segment can be empty. 729cd8eaf89SEugene Leviant // This happens if (all conditions met): 730cd8eaf89SEugene Leviant // - Linker script is used 731cd8eaf89SEugene Leviant // - First section in ELF image is not RO 732cd8eaf89SEugene Leviant // - Not enough space for program headers. 733cd8eaf89SEugene Leviant // The code below removes empty PT_LOAD segment and updates 734cd8eaf89SEugene Leviant // program headers size. 735cd8eaf89SEugene Leviant Phdrs.erase(FirstPTLoad); 73604a2e348SRafael Espindola Out<ELFT>::ProgramHeaders->Size = 73704a2e348SRafael Espindola sizeof(typename ELFT::Phdr) * Phdrs.size(); 7386d91fce5SRafael Espindola } 739fb8978fcSDima Stepanov } 740652852c5SGeorge Rimar 741464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command. 74207320e40SRui Ueyama template <class ELFT> 743a4b41dcaSRafael Espindola std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() { 744edebbdf1SRui Ueyama std::vector<PhdrEntry<ELFT>> Ret; 745bbe38602SEugene Leviant 746464daadcSRui Ueyama // Process PHDRS and FILEHDR keywords because they are not 747464daadcSRui Ueyama // real output sections and cannot be added in the following loop. 748bbe38602SEugene Leviant for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) { 749edebbdf1SRui Ueyama Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags); 750edebbdf1SRui Ueyama PhdrEntry<ELFT> &Phdr = Ret.back(); 751bbe38602SEugene Leviant 752bbe38602SEugene Leviant if (Cmd.HasFilehdr) 753adca245fSRui Ueyama Phdr.add(Out<ELFT>::ElfHeader); 754bbe38602SEugene Leviant if (Cmd.HasPhdrs) 755adca245fSRui Ueyama Phdr.add(Out<ELFT>::ProgramHeaders); 75656b21c86SEugene Leviant 75756b21c86SEugene Leviant if (Cmd.LMAExpr) { 75856b21c86SEugene Leviant Phdr.H.p_paddr = Cmd.LMAExpr(0); 75956b21c86SEugene Leviant Phdr.HasLMA = true; 76056b21c86SEugene Leviant } 761bbe38602SEugene Leviant } 762bbe38602SEugene Leviant 763464daadcSRui Ueyama // Add output sections to program headers. 764e08e78dfSRafael Espindola for (OutputSectionBase *Sec : *OutputSections) { 76504a2e348SRafael Espindola if (!(Sec->Flags & SHF_ALLOC)) 766bbe38602SEugene Leviant break; 767bbe38602SEugene Leviant 768bbe38602SEugene Leviant // Assign headers specified by linker script 769f7a17448SRafael Espindola for (size_t Id : getPhdrIndices(Sec->getName())) { 770edebbdf1SRui Ueyama Ret[Id].add(Sec); 771865bf863SEugene Leviant if (Opt.PhdrsCommands[Id].Flags == UINT_MAX) 7720b113671SRafael Espindola Ret[Id].H.p_flags |= Sec->getPhdrFlags(); 773bbe38602SEugene Leviant } 774bbe38602SEugene Leviant } 775edebbdf1SRui Ueyama return Ret; 776bbe38602SEugene Leviant } 777bbe38602SEugene Leviant 778f9bc3bd2SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() { 779f9bc3bd2SEugene Leviant // Ignore .interp section in case we have PHDRS specification 780f9bc3bd2SEugene Leviant // and PT_INTERP isn't listed. 781f9bc3bd2SEugene Leviant return !Opt.PhdrsCommands.empty() && 782f9bc3bd2SEugene Leviant llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) { 783f9bc3bd2SEugene Leviant return Cmd.Type == PT_INTERP; 784f9bc3bd2SEugene Leviant }) == Opt.PhdrsCommands.end(); 785f9bc3bd2SEugene Leviant } 786f9bc3bd2SEugene Leviant 787bbe38602SEugene Leviant template <class ELFT> 78807320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) { 789f6c3ccefSGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) 790f6c3ccefSGeorge Rimar if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get())) 791f6c3ccefSGeorge Rimar if (Cmd->Name == Name) 792f6c3ccefSGeorge Rimar return Cmd->Filler; 793e2ee72b5SGeorge Rimar return {}; 794e2ee72b5SGeorge Rimar } 795e2ee72b5SGeorge Rimar 796e38cbab5SGeorge Rimar template <class ELFT> 797e38cbab5SGeorge Rimar static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) { 798e38cbab5SGeorge Rimar const endianness E = ELFT::TargetEndianness; 799e38cbab5SGeorge Rimar 800e38cbab5SGeorge Rimar switch (Size) { 801e38cbab5SGeorge Rimar case 1: 802e38cbab5SGeorge Rimar *Buf = (uint8_t)Data; 803e38cbab5SGeorge Rimar break; 804e38cbab5SGeorge Rimar case 2: 805e38cbab5SGeorge Rimar write16<E>(Buf, Data); 806e38cbab5SGeorge Rimar break; 807e38cbab5SGeorge Rimar case 4: 808e38cbab5SGeorge Rimar write32<E>(Buf, Data); 809e38cbab5SGeorge Rimar break; 810e38cbab5SGeorge Rimar case 8: 811e38cbab5SGeorge Rimar write64<E>(Buf, Data); 812e38cbab5SGeorge Rimar break; 813e38cbab5SGeorge Rimar default: 814e38cbab5SGeorge Rimar llvm_unreachable("unsupported Size argument"); 815e38cbab5SGeorge Rimar } 816e38cbab5SGeorge Rimar } 817e38cbab5SGeorge Rimar 818e38cbab5SGeorge Rimar template <class ELFT> 819e38cbab5SGeorge Rimar void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) { 820e38cbab5SGeorge Rimar int I = getSectionIndex(Name); 821e38cbab5SGeorge Rimar if (I == INT_MAX) 822e38cbab5SGeorge Rimar return; 823e38cbab5SGeorge Rimar 824e38cbab5SGeorge Rimar OutputSectionCommand *Cmd = 825e38cbab5SGeorge Rimar dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()); 826e38cbab5SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands) 827e38cbab5SGeorge Rimar if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get())) 828e38cbab5SGeorge Rimar writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size); 829e38cbab5SGeorge Rimar } 830e38cbab5SGeorge Rimar 831b71d6f7aSEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) { 8328ceadb38SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) 8338ceadb38SGeorge Rimar if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get())) 834b71d6f7aSEugene Leviant if (Cmd->LMAExpr && Cmd->Name == Name) 835b71d6f7aSEugene Leviant return true; 836b71d6f7aSEugene Leviant return false; 8378ceadb38SGeorge Rimar } 8388ceadb38SGeorge Rimar 839c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script 840c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they 841c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script, 842c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file. 843076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) { 844f510fa6bSRui Ueyama int I = 0; 845f510fa6bSRui Ueyama for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 846076fe157SGeorge Rimar if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get())) 847076fe157SGeorge Rimar if (Cmd->Name == Name) 848f510fa6bSRui Ueyama return I; 849f510fa6bSRui Ueyama ++I; 850f510fa6bSRui Ueyama } 851f510fa6bSRui Ueyama return INT_MAX; 85271b26e94SGeorge Rimar } 85371b26e94SGeorge Rimar 854bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() { 855bbe38602SEugene Leviant return !Opt.PhdrsCommands.empty(); 856bbe38602SEugene Leviant } 857bbe38602SEugene Leviant 8589e69450eSGeorge Rimar template <class ELFT> 859afaa9343SEugene Leviant const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(StringRef Name) { 860afaa9343SEugene Leviant static OutputSectionBase FakeSec("", 0, 0); 86196659df0SGeorge Rimar 862e08e78dfSRafael Espindola for (OutputSectionBase *Sec : *OutputSections) 863b71d6f7aSEugene Leviant if (Sec->getName() == Name) 864afaa9343SEugene Leviant return Sec; 865b71d6f7aSEugene Leviant error("undefined section " + Name); 866afaa9343SEugene Leviant return &FakeSec; 86736fac7f0SEugene Leviant } 86836fac7f0SEugene Leviant 869884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() { 8700d4b6d5cSRafael Espindola return elf::getHeaderSize<ELFT>(); 871e32a3598SGeorge Rimar } 872e32a3598SGeorge Rimar 873884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) { 874884e786dSGeorge Rimar if (SymbolBody *B = Symtab<ELFT>::X->find(S)) 875884e786dSGeorge Rimar return B->getVA<ELFT>(); 876884e786dSGeorge Rimar error("symbol not found: " + S); 877884e786dSGeorge Rimar return 0; 878884e786dSGeorge Rimar } 879884e786dSGeorge Rimar 880f34f45fdSGeorge Rimar template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) { 881f34f45fdSGeorge Rimar return Symtab<ELFT>::X->find(S) != nullptr; 882f34f45fdSGeorge Rimar } 883f34f45fdSGeorge Rimar 8842f831dcaSRafael Espindola template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) { 8852f831dcaSRafael Espindola SymbolBody *Sym = Symtab<ELFT>::X->find(S); 8862f831dcaSRafael Espindola auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym); 8872f831dcaSRafael Espindola return DR && !DR->Section; 8882f831dcaSRafael Espindola } 8892f831dcaSRafael Espindola 890afaa9343SEugene Leviant // Gets section symbol belongs to. Symbol "." doesn't belong to any 891afaa9343SEugene Leviant // specific section but isn't absolute at the same time, so we try 892afaa9343SEugene Leviant // to find suitable section for it as well. 893afaa9343SEugene Leviant template <class ELFT> 894afaa9343SEugene Leviant const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) { 895afaa9343SEugene Leviant SymbolBody *Sym = Symtab<ELFT>::X->find(S); 896afaa9343SEugene Leviant if (!Sym) { 897afaa9343SEugene Leviant if (OutputSections->empty()) 898afaa9343SEugene Leviant return nullptr; 899afaa9343SEugene Leviant return CurOutSec ? CurOutSec : (*OutputSections)[0]; 900afaa9343SEugene Leviant } 901afaa9343SEugene Leviant 902afaa9343SEugene Leviant if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym)) 903afaa9343SEugene Leviant return DR->Section ? DR->Section->OutSec : nullptr; 904afaa9343SEugene Leviant if (auto *DS = dyn_cast_or_null<DefinedSynthetic<ELFT>>(Sym)) 905afaa9343SEugene Leviant return DS->Section; 906afaa9343SEugene Leviant 907afaa9343SEugene Leviant return nullptr; 908afaa9343SEugene Leviant } 909afaa9343SEugene Leviant 910bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified 911bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within 912bbe38602SEugene Leviant // PHDRS {} script block. 913bbe38602SEugene Leviant template <class ELFT> 914edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) { 915076fe157SGeorge Rimar for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) { 916076fe157SGeorge Rimar auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()); 917edebbdf1SRui Ueyama if (!Cmd || Cmd->Name != SectionName) 91831d842f5SGeorge Rimar continue; 91931d842f5SGeorge Rimar 92029c5a2a9SRui Ueyama std::vector<size_t> Ret; 92129c5a2a9SRui Ueyama for (StringRef PhdrName : Cmd->Phdrs) 92229c5a2a9SRui Ueyama Ret.push_back(getPhdrIndex(PhdrName)); 92329c5a2a9SRui Ueyama return Ret; 924bbe38602SEugene Leviant } 92531d842f5SGeorge Rimar return {}; 92631d842f5SGeorge Rimar } 927bbe38602SEugene Leviant 92829c5a2a9SRui Ueyama template <class ELFT> 92929c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) { 93029c5a2a9SRui Ueyama size_t I = 0; 93129c5a2a9SRui Ueyama for (PhdrsCommand &Cmd : Opt.PhdrsCommands) { 93229c5a2a9SRui Ueyama if (Cmd.Name == PhdrName) 93329c5a2a9SRui Ueyama return I; 93429c5a2a9SRui Ueyama ++I; 93529c5a2a9SRui Ueyama } 93629c5a2a9SRui Ueyama error("section header '" + PhdrName + "' is not listed in PHDRS"); 93729c5a2a9SRui Ueyama return 0; 93829c5a2a9SRui Ueyama } 93929c5a2a9SRui Ueyama 94007320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase { 941c3794e58SGeorge Rimar typedef void (ScriptParser::*Handler)(); 942c3794e58SGeorge Rimar 943f7c5fbb1SRui Ueyama public: 94407320e40SRui Ueyama ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {} 945f23b2320SGeorge Rimar 94620b6598cSGeorge Rimar void readLinkerScript(); 94720b6598cSGeorge Rimar void readVersionScript(); 948f7c5fbb1SRui Ueyama 949f7c5fbb1SRui Ueyama private: 95052a1509eSRui Ueyama void addFile(StringRef Path); 95152a1509eSRui Ueyama 952f7c5fbb1SRui Ueyama void readAsNeeded(); 95390c5099eSDenis Protivensky void readEntry(); 95483f406cfSGeorge Rimar void readExtern(); 955f7c5fbb1SRui Ueyama void readGroup(); 95631aa1f83SRui Ueyama void readInclude(); 957ee59282bSRui Ueyama void readOutput(); 9589159ce93SDavide Italiano void readOutputArch(); 959f7c5fbb1SRui Ueyama void readOutputFormat(); 960bbe38602SEugene Leviant void readPhdrs(); 96168a39a65SDavide Italiano void readSearchDir(); 9628e3b38abSDenis Protivensky void readSections(); 96395769b4aSRui Ueyama void readVersion(); 96495769b4aSRui Ueyama void readVersionScriptCommand(); 9658e3b38abSDenis Protivensky 966113cdec9SRui Ueyama SymbolAssignment *readAssignment(StringRef Name); 967e38cbab5SGeorge Rimar BytesDataCommand *readBytesDataCommand(StringRef Tok); 968ff1f29e0SGeorge Rimar std::vector<uint8_t> readFill(); 96910416564SRui Ueyama OutputSectionCommand *readOutputSectionDescription(StringRef OutSec); 970ff1f29e0SGeorge Rimar std::vector<uint8_t> readOutputSectionFiller(StringRef Tok); 971bbe38602SEugene Leviant std::vector<StringRef> readOutputSectionPhdrs(); 972a2496cbeSGeorge Rimar InputSectionDescription *readInputSectionDescription(StringRef Tok); 973db688454SEugene Leviant StringMatcher readFilePatterns(); 97407171f21SGeorge Rimar std::vector<SectionPattern> readInputSectionsList(); 975a2496cbeSGeorge Rimar InputSectionDescription *readInputSectionRules(StringRef FilePattern); 976bbe38602SEugene Leviant unsigned readPhdrType(); 977be394db3SGeorge Rimar SortSectionPolicy readSortKind(); 978a35e39caSPetr Hosek SymbolAssignment *readProvideHidden(bool Provide, bool Hidden); 979c96da110SRafael Espindola SymbolAssignment *readProvideOrAssignment(StringRef Tok); 98003fc010eSGeorge Rimar void readSort(); 981eefa758eSGeorge Rimar Expr readAssert(); 982708019c4SRui Ueyama 983708019c4SRui Ueyama Expr readExpr(); 984708019c4SRui Ueyama Expr readExpr1(Expr Lhs, int MinPrec); 985b71d6f7aSEugene Leviant StringRef readParenLiteral(); 986708019c4SRui Ueyama Expr readPrimary(); 987708019c4SRui Ueyama Expr readTernary(Expr Cond); 9886ad7dfccSRui Ueyama Expr readParenExpr(); 989f7c5fbb1SRui Ueyama 99020b6598cSGeorge Rimar // For parsing version script. 9912a00b846SRui Ueyama void readVersionExtern(std::vector<SymbolVersion> *Globals); 99295769b4aSRui Ueyama void readVersionDeclaration(StringRef VerStr); 99320b6598cSGeorge Rimar void readGlobal(StringRef VerStr); 994bb6c01e7SGeorge Rimar void readLocal(StringRef VerStr); 995e0fc2421SGeorge Rimar void readSymbols(std::vector<SymbolVersion> &V); 99620b6598cSGeorge Rimar 99707320e40SRui Ueyama ScriptConfiguration &Opt = *ScriptConfig; 99816b0cc9eSSimon Atanasyan bool IsUnderSysroot; 999f7c5fbb1SRui Ueyama }; 1000f7c5fbb1SRui Ueyama 100120b6598cSGeorge Rimar void ScriptParser::readVersionScript() { 100295769b4aSRui Ueyama readVersionScriptCommand(); 100320b6598cSGeorge Rimar if (!atEOF()) 100495769b4aSRui Ueyama setError("EOF expected, but got " + next()); 100595769b4aSRui Ueyama } 100695769b4aSRui Ueyama 100795769b4aSRui Ueyama void ScriptParser::readVersionScriptCommand() { 100883043f23SRui Ueyama if (consume("{")) { 100995769b4aSRui Ueyama readVersionDeclaration(""); 101020b6598cSGeorge Rimar return; 101120b6598cSGeorge Rimar } 101220b6598cSGeorge Rimar 101395769b4aSRui Ueyama while (!atEOF() && !Error && peek() != "}") { 101420b6598cSGeorge Rimar StringRef VerStr = next(); 101520b6598cSGeorge Rimar if (VerStr == "{") { 101695769b4aSRui Ueyama setError("anonymous version definition is used in " 101795769b4aSRui Ueyama "combination with other version definitions"); 101820b6598cSGeorge Rimar return; 101920b6598cSGeorge Rimar } 102020b6598cSGeorge Rimar expect("{"); 102195769b4aSRui Ueyama readVersionDeclaration(VerStr); 102220b6598cSGeorge Rimar } 102320b6598cSGeorge Rimar } 102420b6598cSGeorge Rimar 102595769b4aSRui Ueyama void ScriptParser::readVersion() { 102695769b4aSRui Ueyama expect("{"); 102795769b4aSRui Ueyama readVersionScriptCommand(); 102895769b4aSRui Ueyama expect("}"); 102995769b4aSRui Ueyama } 103095769b4aSRui Ueyama 103120b6598cSGeorge Rimar void ScriptParser::readLinkerScript() { 1032f7c5fbb1SRui Ueyama while (!atEOF()) { 1033f7c5fbb1SRui Ueyama StringRef Tok = next(); 1034a27eeccaSRui Ueyama if (Tok == ";") 1035a27eeccaSRui Ueyama continue; 1036a27eeccaSRui Ueyama 103720d03194SEugene Leviant if (Tok == "ASSERT") { 103820d03194SEugene Leviant Opt.Commands.emplace_back(new AssertCommand(readAssert())); 103920d03194SEugene Leviant } else if (Tok == "ENTRY") { 1040a27eeccaSRui Ueyama readEntry(); 1041a27eeccaSRui Ueyama } else if (Tok == "EXTERN") { 1042a27eeccaSRui Ueyama readExtern(); 1043a27eeccaSRui Ueyama } else if (Tok == "GROUP" || Tok == "INPUT") { 1044a27eeccaSRui Ueyama readGroup(); 1045a27eeccaSRui Ueyama } else if (Tok == "INCLUDE") { 1046a27eeccaSRui Ueyama readInclude(); 1047a27eeccaSRui Ueyama } else if (Tok == "OUTPUT") { 1048a27eeccaSRui Ueyama readOutput(); 1049a27eeccaSRui Ueyama } else if (Tok == "OUTPUT_ARCH") { 1050a27eeccaSRui Ueyama readOutputArch(); 1051a27eeccaSRui Ueyama } else if (Tok == "OUTPUT_FORMAT") { 1052a27eeccaSRui Ueyama readOutputFormat(); 1053a27eeccaSRui Ueyama } else if (Tok == "PHDRS") { 1054a27eeccaSRui Ueyama readPhdrs(); 1055a27eeccaSRui Ueyama } else if (Tok == "SEARCH_DIR") { 1056a27eeccaSRui Ueyama readSearchDir(); 1057a27eeccaSRui Ueyama } else if (Tok == "SECTIONS") { 1058a27eeccaSRui Ueyama readSections(); 1059a27eeccaSRui Ueyama } else if (Tok == "VERSION") { 1060a27eeccaSRui Ueyama readVersion(); 1061c96da110SRafael Espindola } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) { 10620df80befSPetr Hosek Opt.Commands.emplace_back(Cmd); 1063e5d3ca50SPetr Hosek } else { 10645761042dSGeorge Rimar setError("unknown directive: " + Tok); 1065f7c5fbb1SRui Ueyama } 1066f7c5fbb1SRui Ueyama } 1067e5d3ca50SPetr Hosek } 1068f7c5fbb1SRui Ueyama 1069717677afSRui Ueyama void ScriptParser::addFile(StringRef S) { 107016b0cc9eSSimon Atanasyan if (IsUnderSysroot && S.startswith("/")) { 10715af1687fSJustin Bogner SmallString<128> PathData; 10725af1687fSJustin Bogner StringRef Path = (Config->Sysroot + S).toStringRef(PathData); 107316b0cc9eSSimon Atanasyan if (sys::fs::exists(Path)) { 10745af1687fSJustin Bogner Driver->addFile(Saver.save(Path)); 107516b0cc9eSSimon Atanasyan return; 107616b0cc9eSSimon Atanasyan } 107716b0cc9eSSimon Atanasyan } 107816b0cc9eSSimon Atanasyan 1079f03f3cc1SRui Ueyama if (sys::path::is_absolute(S)) { 108052a1509eSRui Ueyama Driver->addFile(S); 108152a1509eSRui Ueyama } else if (S.startswith("=")) { 108252a1509eSRui Ueyama if (Config->Sysroot.empty()) 108352a1509eSRui Ueyama Driver->addFile(S.substr(1)); 108452a1509eSRui Ueyama else 108552a1509eSRui Ueyama Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1))); 108652a1509eSRui Ueyama } else if (S.startswith("-l")) { 108721eecb4fSRui Ueyama Driver->addLibrary(S.substr(2)); 1088a1b8fc3bSSimon Atanasyan } else if (sys::fs::exists(S)) { 1089a1b8fc3bSSimon Atanasyan Driver->addFile(S); 109052a1509eSRui Ueyama } else { 109152a1509eSRui Ueyama std::string Path = findFromSearchPaths(S); 109252a1509eSRui Ueyama if (Path.empty()) 1093777f9630SGeorge Rimar setError("unable to find " + S); 1094025d59b1SRui Ueyama else 109552a1509eSRui Ueyama Driver->addFile(Saver.save(Path)); 109652a1509eSRui Ueyama } 109752a1509eSRui Ueyama } 109852a1509eSRui Ueyama 1099717677afSRui Ueyama void ScriptParser::readAsNeeded() { 1100f7c5fbb1SRui Ueyama expect("("); 110135da9b6eSRui Ueyama bool Orig = Config->AsNeeded; 110235da9b6eSRui Ueyama Config->AsNeeded = true; 110383043f23SRui Ueyama while (!Error && !consume(")")) 1104cd574a5eSGeorge Rimar addFile(unquote(next())); 110535da9b6eSRui Ueyama Config->AsNeeded = Orig; 1106f7c5fbb1SRui Ueyama } 1107f7c5fbb1SRui Ueyama 1108717677afSRui Ueyama void ScriptParser::readEntry() { 110990c5099eSDenis Protivensky // -e <symbol> takes predecence over ENTRY(<symbol>). 111090c5099eSDenis Protivensky expect("("); 111190c5099eSDenis Protivensky StringRef Tok = next(); 111290c5099eSDenis Protivensky if (Config->Entry.empty()) 111390c5099eSDenis Protivensky Config->Entry = Tok; 111490c5099eSDenis Protivensky expect(")"); 111590c5099eSDenis Protivensky } 111690c5099eSDenis Protivensky 1117717677afSRui Ueyama void ScriptParser::readExtern() { 111883f406cfSGeorge Rimar expect("("); 111983043f23SRui Ueyama while (!Error && !consume(")")) 1120a2acc931SRui Ueyama Config->Undefined.push_back(next()); 112183f406cfSGeorge Rimar } 112283f406cfSGeorge Rimar 1123717677afSRui Ueyama void ScriptParser::readGroup() { 1124f7c5fbb1SRui Ueyama expect("("); 112583043f23SRui Ueyama while (!Error && !consume(")")) { 1126f7c5fbb1SRui Ueyama StringRef Tok = next(); 1127a2acc931SRui Ueyama if (Tok == "AS_NEEDED") 1128f7c5fbb1SRui Ueyama readAsNeeded(); 1129a2acc931SRui Ueyama else 1130cd574a5eSGeorge Rimar addFile(unquote(Tok)); 1131f7c5fbb1SRui Ueyama } 1132f7c5fbb1SRui Ueyama } 1133f7c5fbb1SRui Ueyama 1134717677afSRui Ueyama void ScriptParser::readInclude() { 113531aa1f83SRui Ueyama StringRef Tok = next(); 1136cd574a5eSGeorge Rimar auto MBOrErr = MemoryBuffer::getFile(unquote(Tok)); 1137025d59b1SRui Ueyama if (!MBOrErr) { 11385761042dSGeorge Rimar setError("cannot open " + Tok); 1139025d59b1SRui Ueyama return; 1140025d59b1SRui Ueyama } 114131aa1f83SRui Ueyama std::unique_ptr<MemoryBuffer> &MB = *MBOrErr; 1142a47ee68dSRui Ueyama StringRef S = Saver.save(MB->getMemBufferRef().getBuffer()); 1143a47ee68dSRui Ueyama std::vector<StringRef> V = tokenize(S); 114431aa1f83SRui Ueyama Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end()); 114531aa1f83SRui Ueyama } 114631aa1f83SRui Ueyama 1147717677afSRui Ueyama void ScriptParser::readOutput() { 1148ee59282bSRui Ueyama // -o <file> takes predecence over OUTPUT(<file>). 1149ee59282bSRui Ueyama expect("("); 1150ee59282bSRui Ueyama StringRef Tok = next(); 1151ee59282bSRui Ueyama if (Config->OutputFile.empty()) 1152cd574a5eSGeorge Rimar Config->OutputFile = unquote(Tok); 1153ee59282bSRui Ueyama expect(")"); 1154ee59282bSRui Ueyama } 1155ee59282bSRui Ueyama 1156717677afSRui Ueyama void ScriptParser::readOutputArch() { 11579159ce93SDavide Italiano // Error checking only for now. 11589159ce93SDavide Italiano expect("("); 11595424e7c7SJustin Bogner skip(); 11609159ce93SDavide Italiano expect(")"); 11619159ce93SDavide Italiano } 11629159ce93SDavide Italiano 1163717677afSRui Ueyama void ScriptParser::readOutputFormat() { 1164f7c5fbb1SRui Ueyama // Error checking only for now. 1165f7c5fbb1SRui Ueyama expect("("); 11665424e7c7SJustin Bogner skip(); 11676836c618SDavide Italiano StringRef Tok = next(); 11686836c618SDavide Italiano if (Tok == ")") 11696836c618SDavide Italiano return; 1170025d59b1SRui Ueyama if (Tok != ",") { 11715761042dSGeorge Rimar setError("unexpected token: " + Tok); 1172025d59b1SRui Ueyama return; 1173025d59b1SRui Ueyama } 11745424e7c7SJustin Bogner skip(); 11756836c618SDavide Italiano expect(","); 11765424e7c7SJustin Bogner skip(); 1177f7c5fbb1SRui Ueyama expect(")"); 1178f7c5fbb1SRui Ueyama } 1179f7c5fbb1SRui Ueyama 1180bbe38602SEugene Leviant void ScriptParser::readPhdrs() { 1181bbe38602SEugene Leviant expect("{"); 118283043f23SRui Ueyama while (!Error && !consume("}")) { 1183bbe38602SEugene Leviant StringRef Tok = next(); 118456b21c86SEugene Leviant Opt.PhdrsCommands.push_back( 118556b21c86SEugene Leviant {Tok, PT_NULL, false, false, UINT_MAX, nullptr}); 1186bbe38602SEugene Leviant PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back(); 1187bbe38602SEugene Leviant 1188bbe38602SEugene Leviant PhdrCmd.Type = readPhdrType(); 1189bbe38602SEugene Leviant do { 1190bbe38602SEugene Leviant Tok = next(); 1191bbe38602SEugene Leviant if (Tok == ";") 1192bbe38602SEugene Leviant break; 1193bbe38602SEugene Leviant if (Tok == "FILEHDR") 1194bbe38602SEugene Leviant PhdrCmd.HasFilehdr = true; 1195bbe38602SEugene Leviant else if (Tok == "PHDRS") 1196bbe38602SEugene Leviant PhdrCmd.HasPhdrs = true; 119756b21c86SEugene Leviant else if (Tok == "AT") 119856b21c86SEugene Leviant PhdrCmd.LMAExpr = readParenExpr(); 1199865bf863SEugene Leviant else if (Tok == "FLAGS") { 1200865bf863SEugene Leviant expect("("); 1201eb685cd7SRafael Espindola // Passing 0 for the value of dot is a bit of a hack. It means that 1202eb685cd7SRafael Espindola // we accept expressions like ".|1". 1203eb685cd7SRafael Espindola PhdrCmd.Flags = readExpr()(0); 1204865bf863SEugene Leviant expect(")"); 1205865bf863SEugene Leviant } else 1206bbe38602SEugene Leviant setError("unexpected header attribute: " + Tok); 1207bbe38602SEugene Leviant } while (!Error); 1208bbe38602SEugene Leviant } 1209bbe38602SEugene Leviant } 1210bbe38602SEugene Leviant 1211717677afSRui Ueyama void ScriptParser::readSearchDir() { 121268a39a65SDavide Italiano expect("("); 121386c5fb82SRui Ueyama StringRef Tok = next(); 12146c7ad13fSRui Ueyama if (!Config->Nostdlib) 1215cd574a5eSGeorge Rimar Config->SearchPaths.push_back(unquote(Tok)); 121668a39a65SDavide Italiano expect(")"); 121768a39a65SDavide Italiano } 121868a39a65SDavide Italiano 1219717677afSRui Ueyama void ScriptParser::readSections() { 1220e05336ffSEugene Leviant Opt.HasSections = true; 12218e3b38abSDenis Protivensky expect("{"); 122283043f23SRui Ueyama while (!Error && !consume("}")) { 1223113cdec9SRui Ueyama StringRef Tok = next(); 1224c96da110SRafael Espindola BaseCommand *Cmd = readProvideOrAssignment(Tok); 1225ceabe80eSEugene Leviant if (!Cmd) { 1226ceabe80eSEugene Leviant if (Tok == "ASSERT") 1227eefa758eSGeorge Rimar Cmd = new AssertCommand(readAssert()); 1228ceabe80eSEugene Leviant else 122910416564SRui Ueyama Cmd = readOutputSectionDescription(Tok); 12308e3b38abSDenis Protivensky } 123110416564SRui Ueyama Opt.Commands.emplace_back(Cmd); 1232652852c5SGeorge Rimar } 1233708019c4SRui Ueyama } 12348e3b38abSDenis Protivensky 1235708019c4SRui Ueyama static int precedence(StringRef Op) { 1236708019c4SRui Ueyama return StringSwitch<int>(Op) 12370120e3f2SRui Ueyama .Cases("*", "/", 5) 12380120e3f2SRui Ueyama .Cases("+", "-", 4) 12390120e3f2SRui Ueyama .Cases("<<", ">>", 3) 12409c4ac5f2SRui Ueyama .Cases("<", "<=", ">", ">=", "==", "!=", 2) 12410120e3f2SRui Ueyama .Cases("&", "|", 1) 1242708019c4SRui Ueyama .Default(-1); 1243708019c4SRui Ueyama } 1244708019c4SRui Ueyama 1245db688454SEugene Leviant StringMatcher ScriptParser::readFilePatterns() { 124610416564SRui Ueyama std::vector<StringRef> V; 124783043f23SRui Ueyama while (!Error && !consume(")")) 124810416564SRui Ueyama V.push_back(next()); 1249f91282e1SRui Ueyama return StringMatcher(V); 12500702c4e8SGeorge Rimar } 12510702c4e8SGeorge Rimar 1252be394db3SGeorge Rimar SortSectionPolicy ScriptParser::readSortKind() { 125383043f23SRui Ueyama if (consume("SORT") || consume("SORT_BY_NAME")) 1254be394db3SGeorge Rimar return SortSectionPolicy::Name; 125583043f23SRui Ueyama if (consume("SORT_BY_ALIGNMENT")) 1256be394db3SGeorge Rimar return SortSectionPolicy::Alignment; 125783043f23SRui Ueyama if (consume("SORT_BY_INIT_PRIORITY")) 1258be394db3SGeorge Rimar return SortSectionPolicy::Priority; 125983043f23SRui Ueyama if (consume("SORT_NONE")) 1260be394db3SGeorge Rimar return SortSectionPolicy::None; 1261b2a0abdfSRui Ueyama return SortSectionPolicy::Default; 1262be394db3SGeorge Rimar } 1263be394db3SGeorge Rimar 1264395281cfSGeorge Rimar // Method reads a list of sequence of excluded files and section globs given in 1265395281cfSGeorge Rimar // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+ 1266395281cfSGeorge Rimar // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3) 1267af03be19SGeorge Rimar // The semantics of that is next: 1268af03be19SGeorge Rimar // * Include .foo.1 from every file. 1269af03be19SGeorge Rimar // * Include .foo.2 from every file but a.o 1270af03be19SGeorge Rimar // * Include .foo.3 from every file but b.o 127107171f21SGeorge Rimar std::vector<SectionPattern> ScriptParser::readInputSectionsList() { 127207171f21SGeorge Rimar std::vector<SectionPattern> Ret; 1273601e9898SGeorge Rimar while (!Error && peek() != ")") { 1274f91282e1SRui Ueyama StringMatcher ExcludeFilePat; 127583043f23SRui Ueyama if (consume("EXCLUDE_FILE")) { 1276395281cfSGeorge Rimar expect("("); 1277f91282e1SRui Ueyama ExcludeFilePat = readFilePatterns(); 1278395281cfSGeorge Rimar } 1279395281cfSGeorge Rimar 1280601e9898SGeorge Rimar std::vector<StringRef> V; 1281601e9898SGeorge Rimar while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE") 1282395281cfSGeorge Rimar V.push_back(next()); 1283601e9898SGeorge Rimar 1284601e9898SGeorge Rimar if (!V.empty()) 1285f91282e1SRui Ueyama Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)}); 1286601e9898SGeorge Rimar else 1287601e9898SGeorge Rimar setError("section pattern is expected"); 1288395281cfSGeorge Rimar } 128907171f21SGeorge Rimar return Ret; 1290395281cfSGeorge Rimar } 1291395281cfSGeorge Rimar 129207171f21SGeorge Rimar // Section pattern grammar can have complex expressions, for example: 129307171f21SGeorge Rimar // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*)) 129407171f21SGeorge Rimar // Generally is a sequence of globs and excludes that may be wrapped in a SORT() 129507171f21SGeorge Rimar // commands, like: SORT(glob0) glob1 glob2 SORT(glob4) 129607171f21SGeorge Rimar // This methods handles wrapping sequences of excluded files and section globs 129707171f21SGeorge Rimar // into SORT() if that needed and reads them all. 1298a2496cbeSGeorge Rimar InputSectionDescription * 1299a2496cbeSGeorge Rimar ScriptParser::readInputSectionRules(StringRef FilePattern) { 1300c91930a1SGeorge Rimar auto *Cmd = new InputSectionDescription(FilePattern); 13010ed42b0cSDavide Italiano expect("("); 130283043f23SRui Ueyama while (!HasError && !consume(")")) { 130307171f21SGeorge Rimar SortSectionPolicy Outer = readSortKind(); 130407171f21SGeorge Rimar SortSectionPolicy Inner = SortSectionPolicy::Default; 130507171f21SGeorge Rimar std::vector<SectionPattern> V; 130607171f21SGeorge Rimar if (Outer != SortSectionPolicy::Default) { 13070702c4e8SGeorge Rimar expect("("); 130807171f21SGeorge Rimar Inner = readSortKind(); 130907171f21SGeorge Rimar if (Inner != SortSectionPolicy::Default) { 1310350ece4eSGeorge Rimar expect("("); 131107171f21SGeorge Rimar V = readInputSectionsList(); 13120702c4e8SGeorge Rimar expect(")"); 1313350ece4eSGeorge Rimar } else { 131407171f21SGeorge Rimar V = readInputSectionsList(); 1315350ece4eSGeorge Rimar } 1316350ece4eSGeorge Rimar expect(")"); 131707171f21SGeorge Rimar } else { 131807171f21SGeorge Rimar V = readInputSectionsList(); 13190659800eSGeorge Rimar } 13200702c4e8SGeorge Rimar 132107171f21SGeorge Rimar for (SectionPattern &Pat : V) { 132207171f21SGeorge Rimar Pat.SortInner = Inner; 132307171f21SGeorge Rimar Pat.SortOuter = Outer; 132407171f21SGeorge Rimar } 132507171f21SGeorge Rimar 132607171f21SGeorge Rimar std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns)); 132707171f21SGeorge Rimar } 132810416564SRui Ueyama return Cmd; 13290659800eSGeorge Rimar } 13300659800eSGeorge Rimar 1331a2496cbeSGeorge Rimar InputSectionDescription * 1332a2496cbeSGeorge Rimar ScriptParser::readInputSectionDescription(StringRef Tok) { 13330659800eSGeorge Rimar // Input section wildcard can be surrounded by KEEP. 13340659800eSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep 1335a2496cbeSGeorge Rimar if (Tok == "KEEP") { 1336e7282797SDavide Italiano expect("("); 1337a2496cbeSGeorge Rimar StringRef FilePattern = next(); 1338a2496cbeSGeorge Rimar InputSectionDescription *Cmd = readInputSectionRules(FilePattern); 13390ed42b0cSDavide Italiano expect(")"); 1340cf43f179SEugene Leviant Opt.KeptSections.push_back(Cmd); 134110416564SRui Ueyama return Cmd; 134210416564SRui Ueyama } 1343a2496cbeSGeorge Rimar return readInputSectionRules(Tok); 13440659800eSGeorge Rimar } 13450659800eSGeorge Rimar 134603fc010eSGeorge Rimar void ScriptParser::readSort() { 134703fc010eSGeorge Rimar expect("("); 134803fc010eSGeorge Rimar expect("CONSTRUCTORS"); 134903fc010eSGeorge Rimar expect(")"); 135003fc010eSGeorge Rimar } 135103fc010eSGeorge Rimar 1352eefa758eSGeorge Rimar Expr ScriptParser::readAssert() { 1353eefa758eSGeorge Rimar expect("("); 1354eefa758eSGeorge Rimar Expr E = readExpr(); 1355eefa758eSGeorge Rimar expect(","); 1356cd574a5eSGeorge Rimar StringRef Msg = unquote(next()); 1357eefa758eSGeorge Rimar expect(")"); 1358eefa758eSGeorge Rimar return [=](uint64_t Dot) { 1359eefa758eSGeorge Rimar uint64_t V = E(Dot); 1360eefa758eSGeorge Rimar if (!V) 1361eefa758eSGeorge Rimar error(Msg); 1362eefa758eSGeorge Rimar return V; 1363eefa758eSGeorge Rimar }; 1364eefa758eSGeorge Rimar } 1365eefa758eSGeorge Rimar 136625150e8bSRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an 136725150e8bSRui Ueyama // alias for =fillexp section attribute, which is different from 136825150e8bSRui Ueyama // what GNU linkers do. 136925150e8bSRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html 1370ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readFill() { 1371ff1f29e0SGeorge Rimar expect("("); 1372ff1f29e0SGeorge Rimar std::vector<uint8_t> V = readOutputSectionFiller(next()); 1373ff1f29e0SGeorge Rimar expect(")"); 1374ff1f29e0SGeorge Rimar expect(";"); 1375ff1f29e0SGeorge Rimar return V; 1376ff1f29e0SGeorge Rimar } 1377ff1f29e0SGeorge Rimar 137810416564SRui Ueyama OutputSectionCommand * 137910416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) { 1380076fe157SGeorge Rimar OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec); 138158e5c4dcSGeorge Rimar 138258e5c4dcSGeorge Rimar // Read an address expression. 138358e5c4dcSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address 138458e5c4dcSGeorge Rimar if (peek() != ":") 138558e5c4dcSGeorge Rimar Cmd->AddrExpr = readExpr(); 138658e5c4dcSGeorge Rimar 13878e3b38abSDenis Protivensky expect(":"); 1388246f681eSDavide Italiano 138983043f23SRui Ueyama if (consume("AT")) 1390b71d6f7aSEugene Leviant Cmd->LMAExpr = readParenExpr(); 139183043f23SRui Ueyama if (consume("ALIGN")) 13926ad7dfccSRui Ueyama Cmd->AlignExpr = readParenExpr(); 139383043f23SRui Ueyama if (consume("SUBALIGN")) 1394db24d9c3SGeorge Rimar Cmd->SubalignExpr = readParenExpr(); 1395630c6179SGeorge Rimar 1396246f681eSDavide Italiano // Parse constraints. 139783043f23SRui Ueyama if (consume("ONLY_IF_RO")) 1398efc4066bSRui Ueyama Cmd->Constraint = ConstraintKind::ReadOnly; 139983043f23SRui Ueyama if (consume("ONLY_IF_RW")) 1400efc4066bSRui Ueyama Cmd->Constraint = ConstraintKind::ReadWrite; 14018e3b38abSDenis Protivensky expect("{"); 14028ec77e64SRui Ueyama 140383043f23SRui Ueyama while (!Error && !consume("}")) { 1404ceabe80eSEugene Leviant StringRef Tok = next(); 1405c96da110SRafael Espindola if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) 1406ceabe80eSEugene Leviant Cmd->Commands.emplace_back(Assignment); 1407e38cbab5SGeorge Rimar else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) 1408e38cbab5SGeorge Rimar Cmd->Commands.emplace_back(Data); 1409ff1f29e0SGeorge Rimar else if (Tok == "FILL") 1410ff1f29e0SGeorge Rimar Cmd->Filler = readFill(); 1411ceabe80eSEugene Leviant else if (Tok == "SORT") 141203fc010eSGeorge Rimar readSort(); 1413a2496cbeSGeorge Rimar else if (peek() == "(") 1414a2496cbeSGeorge Rimar Cmd->Commands.emplace_back(readInputSectionDescription(Tok)); 1415ceabe80eSEugene Leviant else 1416ceabe80eSEugene Leviant setError("unknown command " + Tok); 14178e3b38abSDenis Protivensky } 1418076fe157SGeorge Rimar Cmd->Phdrs = readOutputSectionPhdrs(); 14194ebc5620SGeorge Rimar 142083043f23SRui Ueyama if (consume("=")) 14214ebc5620SGeorge Rimar Cmd->Filler = readOutputSectionFiller(next()); 14224ebc5620SGeorge Rimar else if (peek().startswith("=")) 1423ff1f29e0SGeorge Rimar Cmd->Filler = readOutputSectionFiller(next().drop_front()); 14244ebc5620SGeorge Rimar 142510416564SRui Ueyama return Cmd; 1426f71caa2bSRui Ueyama } 14278ec77e64SRui Ueyama 14282c8f1f04SRui Ueyama // Read "=<number>" where <number> is an octal/decimal/hexadecimal number. 14292c8f1f04SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html 14302c8f1f04SRui Ueyama // 14312c8f1f04SRui Ueyama // ld.gold is not fully compatible with ld.bfd. ld.bfd handles 14322c8f1f04SRui Ueyama // hexstrings as blobs of arbitrary sizes, while ld.gold handles them 14332c8f1f04SRui Ueyama // as 32-bit big-endian values. We will do the same as ld.gold does 14342c8f1f04SRui Ueyama // because it's simpler than what ld.bfd does. 1435ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) { 1436965827d6SRui Ueyama uint32_t V; 1437ff1f29e0SGeorge Rimar if (Tok.getAsInteger(0, V)) { 1438965827d6SRui Ueyama setError("invalid filler expression: " + Tok); 1439f71caa2bSRui Ueyama return {}; 1440e2ee72b5SGeorge Rimar } 1441965827d6SRui Ueyama return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)}; 14428e3b38abSDenis Protivensky } 14438e3b38abSDenis Protivensky 1444a35e39caSPetr Hosek SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) { 1445a31c91b1SEugene Leviant expect("("); 1446174e0a16SRui Ueyama SymbolAssignment *Cmd = readAssignment(next()); 1447a35e39caSPetr Hosek Cmd->Provide = Provide; 1448174e0a16SRui Ueyama Cmd->Hidden = Hidden; 1449a31c91b1SEugene Leviant expect(")"); 1450a31c91b1SEugene Leviant expect(";"); 145110416564SRui Ueyama return Cmd; 1452eda81a1bSEugene Leviant } 1453eda81a1bSEugene Leviant 1454c96da110SRafael Espindola SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) { 1455ceabe80eSEugene Leviant SymbolAssignment *Cmd = nullptr; 1456ceabe80eSEugene Leviant if (peek() == "=" || peek() == "+=") { 1457ceabe80eSEugene Leviant Cmd = readAssignment(Tok); 1458ceabe80eSEugene Leviant expect(";"); 1459ceabe80eSEugene Leviant } else if (Tok == "PROVIDE") { 1460a35e39caSPetr Hosek Cmd = readProvideHidden(true, false); 1461a35e39caSPetr Hosek } else if (Tok == "HIDDEN") { 1462a35e39caSPetr Hosek Cmd = readProvideHidden(false, true); 1463ceabe80eSEugene Leviant } else if (Tok == "PROVIDE_HIDDEN") { 1464a35e39caSPetr Hosek Cmd = readProvideHidden(true, true); 1465ceabe80eSEugene Leviant } 1466ceabe80eSEugene Leviant return Cmd; 1467ceabe80eSEugene Leviant } 1468ceabe80eSEugene Leviant 146930835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) { 147030835ea4SGeorge Rimar if (S == ".") 147130835ea4SGeorge Rimar return Dot; 1472884e786dSGeorge Rimar return ScriptBase->getSymbolValue(S); 1473e32a3598SGeorge Rimar } 1474e32a3598SGeorge Rimar 14752f831dcaSRafael Espindola static bool isAbsolute(StringRef S) { 14762f831dcaSRafael Espindola if (S == ".") 14772f831dcaSRafael Espindola return false; 14782f831dcaSRafael Espindola return ScriptBase->isAbsolute(S); 14792f831dcaSRafael Espindola } 14802f831dcaSRafael Espindola 148130835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) { 148230835ea4SGeorge Rimar StringRef Op = next(); 1483db741e72SEugene Leviant Expr E; 148430835ea4SGeorge Rimar assert(Op == "=" || Op == "+="); 148583043f23SRui Ueyama if (consume("ABSOLUTE")) { 14867c1381a0SRui Ueyama // The RHS may be something like "ABSOLUTE(.) & 0xff". 14877c1381a0SRui Ueyama // Call readExpr1 to read the whole expression. 14887c1381a0SRui Ueyama E = readExpr1(readParenExpr(), 0); 14892f831dcaSRafael Espindola E.IsAbsolute = []() { return true; }; 1490db741e72SEugene Leviant } else { 1491db741e72SEugene Leviant E = readExpr(); 1492db741e72SEugene Leviant } 149330835ea4SGeorge Rimar if (Op == "+=") 149430835ea4SGeorge Rimar E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); }; 1495f661393aSRafael Espindola return new SymbolAssignment(Name, E); 149630835ea4SGeorge Rimar } 149730835ea4SGeorge Rimar 149830835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker 149930835ea4SGeorge Rimar // script expression. 150030835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); } 150130835ea4SGeorge Rimar 150236c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) { 150336c1cd23SRui Ueyama if (Op == "*") 150436c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) * R(Dot); }; 150536c1cd23SRui Ueyama if (Op == "/") { 150636c1cd23SRui Ueyama return [=](uint64_t Dot) -> uint64_t { 150736c1cd23SRui Ueyama uint64_t RHS = R(Dot); 150836c1cd23SRui Ueyama if (RHS == 0) { 150936c1cd23SRui Ueyama error("division by zero"); 151036c1cd23SRui Ueyama return 0; 151136c1cd23SRui Ueyama } 151236c1cd23SRui Ueyama return L(Dot) / RHS; 151336c1cd23SRui Ueyama }; 151436c1cd23SRui Ueyama } 151536c1cd23SRui Ueyama if (Op == "+") 15162f831dcaSRafael Espindola return {[=](uint64_t Dot) { return L(Dot) + R(Dot); }, 1517afaa9343SEugene Leviant [=]() { return L.IsAbsolute() && R.IsAbsolute(); }, 1518afaa9343SEugene Leviant [=]() { 1519afaa9343SEugene Leviant const OutputSectionBase *S = L.Section(); 1520afaa9343SEugene Leviant return S ? S : R.Section(); 1521afaa9343SEugene Leviant }}; 152236c1cd23SRui Ueyama if (Op == "-") 152336c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) - R(Dot); }; 1524c8ccd1f1SGeorge Rimar if (Op == "<<") 1525c8ccd1f1SGeorge Rimar return [=](uint64_t Dot) { return L(Dot) << R(Dot); }; 1526c8ccd1f1SGeorge Rimar if (Op == ">>") 1527c8ccd1f1SGeorge Rimar return [=](uint64_t Dot) { return L(Dot) >> R(Dot); }; 152836c1cd23SRui Ueyama if (Op == "<") 152936c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) < R(Dot); }; 153036c1cd23SRui Ueyama if (Op == ">") 153136c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) > R(Dot); }; 153236c1cd23SRui Ueyama if (Op == ">=") 153336c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) >= R(Dot); }; 153436c1cd23SRui Ueyama if (Op == "<=") 153536c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) <= R(Dot); }; 153636c1cd23SRui Ueyama if (Op == "==") 153736c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) == R(Dot); }; 153836c1cd23SRui Ueyama if (Op == "!=") 153936c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) != R(Dot); }; 154036c1cd23SRui Ueyama if (Op == "&") 154136c1cd23SRui Ueyama return [=](uint64_t Dot) { return L(Dot) & R(Dot); }; 1542cc3dd629SRafael Espindola if (Op == "|") 1543cc3dd629SRafael Espindola return [=](uint64_t Dot) { return L(Dot) | R(Dot); }; 154436c1cd23SRui Ueyama llvm_unreachable("invalid operator"); 154536c1cd23SRui Ueyama } 154636c1cd23SRui Ueyama 1547708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function 1548708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator. 1549708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) { 1550708019c4SRui Ueyama while (!atEOF() && !Error) { 1551708019c4SRui Ueyama // Read an operator and an expression. 1552708019c4SRui Ueyama StringRef Op1 = peek(); 1553708019c4SRui Ueyama if (Op1 == "?") 1554708019c4SRui Ueyama return readTernary(Lhs); 1555708019c4SRui Ueyama if (precedence(Op1) < MinPrec) 1556a31c91b1SEugene Leviant break; 15575424e7c7SJustin Bogner skip(); 1558708019c4SRui Ueyama Expr Rhs = readPrimary(); 1559708019c4SRui Ueyama 1560708019c4SRui Ueyama // Evaluate the remaining part of the expression first if the 1561708019c4SRui Ueyama // next operator has greater precedence than the previous one. 1562708019c4SRui Ueyama // For example, if we have read "+" and "3", and if the next 1563708019c4SRui Ueyama // operator is "*", then we'll evaluate 3 * ... part first. 1564708019c4SRui Ueyama while (!atEOF()) { 1565708019c4SRui Ueyama StringRef Op2 = peek(); 1566708019c4SRui Ueyama if (precedence(Op2) <= precedence(Op1)) 1567eda81a1bSEugene Leviant break; 1568708019c4SRui Ueyama Rhs = readExpr1(Rhs, precedence(Op2)); 1569eda81a1bSEugene Leviant } 1570708019c4SRui Ueyama 1571708019c4SRui Ueyama Lhs = combine(Op1, Lhs, Rhs); 1572708019c4SRui Ueyama } 1573708019c4SRui Ueyama return Lhs; 1574708019c4SRui Ueyama } 1575708019c4SRui Ueyama 1576708019c4SRui Ueyama uint64_t static getConstant(StringRef S) { 1577e2cc07bcSMichael J. Spencer if (S == "COMMONPAGESIZE") 1578708019c4SRui Ueyama return Target->PageSize; 1579e2cc07bcSMichael J. Spencer if (S == "MAXPAGESIZE") 1580997f8838SPetr Hosek return Config->MaxPageSize; 1581708019c4SRui Ueyama error("unknown constant: " + S); 1582708019c4SRui Ueyama return 0; 1583708019c4SRui Ueyama } 1584708019c4SRui Ueyama 1585626e0b08SRui Ueyama // Parses Tok as an integer. Returns true if successful. 1586626e0b08SRui Ueyama // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H") 1587626e0b08SRui Ueyama // and decimal numbers. Decimal numbers may have "K" (kilo) or 1588626e0b08SRui Ueyama // "M" (mega) prefixes. 15899f2f7ad9SGeorge Rimar static bool readInteger(StringRef Tok, uint64_t &Result) { 1590eaeafb2bSSimon Atanasyan if (Tok.startswith("-")) { 1591eaeafb2bSSimon Atanasyan if (!readInteger(Tok.substr(1), Result)) 1592eaeafb2bSSimon Atanasyan return false; 1593eaeafb2bSSimon Atanasyan Result = -Result; 1594eaeafb2bSSimon Atanasyan return true; 1595eaeafb2bSSimon Atanasyan } 15969f2f7ad9SGeorge Rimar if (Tok.startswith_lower("0x")) 15979f2f7ad9SGeorge Rimar return !Tok.substr(2).getAsInteger(16, Result); 15989f2f7ad9SGeorge Rimar if (Tok.endswith_lower("H")) 15999f2f7ad9SGeorge Rimar return !Tok.drop_back().getAsInteger(16, Result); 16009f2f7ad9SGeorge Rimar 16019f2f7ad9SGeorge Rimar int Suffix = 1; 16029f2f7ad9SGeorge Rimar if (Tok.endswith_lower("K")) { 16039f2f7ad9SGeorge Rimar Suffix = 1024; 16049f2f7ad9SGeorge Rimar Tok = Tok.drop_back(); 16059f2f7ad9SGeorge Rimar } else if (Tok.endswith_lower("M")) { 16069f2f7ad9SGeorge Rimar Suffix = 1024 * 1024; 16079f2f7ad9SGeorge Rimar Tok = Tok.drop_back(); 16089f2f7ad9SGeorge Rimar } 16099f2f7ad9SGeorge Rimar if (Tok.getAsInteger(10, Result)) 16109f2f7ad9SGeorge Rimar return false; 16119f2f7ad9SGeorge Rimar Result *= Suffix; 16129f2f7ad9SGeorge Rimar return true; 16139f2f7ad9SGeorge Rimar } 16149f2f7ad9SGeorge Rimar 1615e38cbab5SGeorge Rimar BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) { 1616e38cbab5SGeorge Rimar int Size = StringSwitch<unsigned>(Tok) 1617e38cbab5SGeorge Rimar .Case("BYTE", 1) 1618e38cbab5SGeorge Rimar .Case("SHORT", 2) 1619e38cbab5SGeorge Rimar .Case("LONG", 4) 1620e38cbab5SGeorge Rimar .Case("QUAD", 8) 1621e38cbab5SGeorge Rimar .Default(-1); 1622e38cbab5SGeorge Rimar if (Size == -1) 1623e38cbab5SGeorge Rimar return nullptr; 1624e38cbab5SGeorge Rimar 1625e38cbab5SGeorge Rimar expect("("); 1626e38cbab5SGeorge Rimar uint64_t Val = 0; 1627e38cbab5SGeorge Rimar StringRef S = next(); 1628e38cbab5SGeorge Rimar if (!readInteger(S, Val)) 1629e38cbab5SGeorge Rimar setError("unexpected value: " + S); 1630e38cbab5SGeorge Rimar expect(")"); 1631e38cbab5SGeorge Rimar return new BytesDataCommand(Val, Size); 1632e38cbab5SGeorge Rimar } 1633e38cbab5SGeorge Rimar 1634b71d6f7aSEugene Leviant StringRef ScriptParser::readParenLiteral() { 1635b71d6f7aSEugene Leviant expect("("); 1636b71d6f7aSEugene Leviant StringRef Tok = next(); 1637b71d6f7aSEugene Leviant expect(")"); 1638b71d6f7aSEugene Leviant return Tok; 1639b71d6f7aSEugene Leviant } 1640b71d6f7aSEugene Leviant 1641708019c4SRui Ueyama Expr ScriptParser::readPrimary() { 16426ad7dfccSRui Ueyama if (peek() == "(") 16436ad7dfccSRui Ueyama return readParenExpr(); 1644708019c4SRui Ueyama 16456ad7dfccSRui Ueyama StringRef Tok = next(); 1646708019c4SRui Ueyama 1647eaeafb2bSSimon Atanasyan if (Tok == "~") { 1648eaeafb2bSSimon Atanasyan Expr E = readPrimary(); 1649eaeafb2bSSimon Atanasyan return [=](uint64_t Dot) { return ~E(Dot); }; 1650eaeafb2bSSimon Atanasyan } 1651eaeafb2bSSimon Atanasyan if (Tok == "-") { 1652eaeafb2bSSimon Atanasyan Expr E = readPrimary(); 1653eaeafb2bSSimon Atanasyan return [=](uint64_t Dot) { return -E(Dot); }; 1654eaeafb2bSSimon Atanasyan } 1655eaeafb2bSSimon Atanasyan 1656708019c4SRui Ueyama // Built-in functions are parsed here. 1657708019c4SRui Ueyama // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html. 165896659df0SGeorge Rimar if (Tok == "ADDR") { 1659b71d6f7aSEugene Leviant StringRef Name = readParenLiteral(); 1660afaa9343SEugene Leviant return { 1661afaa9343SEugene Leviant [=](uint64_t Dot) { return ScriptBase->getOutputSection(Name)->Addr; }, 1662afaa9343SEugene Leviant [=]() { return false; }, 1663afaa9343SEugene Leviant [=]() { return ScriptBase->getOutputSection(Name); }}; 166496659df0SGeorge Rimar } 1665b71d6f7aSEugene Leviant if (Tok == "LOADADDR") { 1666b71d6f7aSEugene Leviant StringRef Name = readParenLiteral(); 1667afaa9343SEugene Leviant return [=](uint64_t Dot) { 1668afaa9343SEugene Leviant return ScriptBase->getOutputSection(Name)->getLMA(); 1669afaa9343SEugene Leviant }; 1670b71d6f7aSEugene Leviant } 1671eefa758eSGeorge Rimar if (Tok == "ASSERT") 1672eefa758eSGeorge Rimar return readAssert(); 1673708019c4SRui Ueyama if (Tok == "ALIGN") { 16746ad7dfccSRui Ueyama Expr E = readParenExpr(); 1675708019c4SRui Ueyama return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); }; 1676708019c4SRui Ueyama } 1677708019c4SRui Ueyama if (Tok == "CONSTANT") { 1678b71d6f7aSEugene Leviant StringRef Name = readParenLiteral(); 1679b0de56b5SRafael Espindola return [=](uint64_t Dot) { return getConstant(Name); }; 1680708019c4SRui Ueyama } 1681f34f45fdSGeorge Rimar if (Tok == "DEFINED") { 1682f34f45fdSGeorge Rimar expect("("); 1683f34f45fdSGeorge Rimar StringRef Tok = next(); 1684f34f45fdSGeorge Rimar expect(")"); 1685f2821028SGeorge Rimar return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; }; 1686f34f45fdSGeorge Rimar } 168754c145ceSRafael Espindola if (Tok == "SEGMENT_START") { 168854c145ceSRafael Espindola expect("("); 16895424e7c7SJustin Bogner skip(); 169054c145ceSRafael Espindola expect(","); 16918c658bf8SGeorge Rimar Expr E = readExpr(); 169254c145ceSRafael Espindola expect(")"); 16938c658bf8SGeorge Rimar return [=](uint64_t Dot) { return E(Dot); }; 169454c145ceSRafael Espindola } 1695708019c4SRui Ueyama if (Tok == "DATA_SEGMENT_ALIGN") { 1696708019c4SRui Ueyama expect("("); 1697708019c4SRui Ueyama Expr E = readExpr(); 1698708019c4SRui Ueyama expect(","); 1699708019c4SRui Ueyama readExpr(); 1700708019c4SRui Ueyama expect(")"); 1701f7791bb9SRui Ueyama return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); }; 1702708019c4SRui Ueyama } 1703708019c4SRui Ueyama if (Tok == "DATA_SEGMENT_END") { 1704708019c4SRui Ueyama expect("("); 1705708019c4SRui Ueyama expect("."); 1706708019c4SRui Ueyama expect(")"); 1707708019c4SRui Ueyama return [](uint64_t Dot) { return Dot; }; 1708708019c4SRui Ueyama } 1709276b4e64SGeorge Rimar // GNU linkers implements more complicated logic to handle 1710276b4e64SGeorge Rimar // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to 1711276b4e64SGeorge Rimar // the next page boundary for simplicity. 1712276b4e64SGeorge Rimar if (Tok == "DATA_SEGMENT_RELRO_END") { 1713276b4e64SGeorge Rimar expect("("); 171497bdc722SRafael Espindola readExpr(); 1715276b4e64SGeorge Rimar expect(","); 1716276b4e64SGeorge Rimar readExpr(); 1717276b4e64SGeorge Rimar expect(")"); 1718276b4e64SGeorge Rimar return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); }; 1719276b4e64SGeorge Rimar } 17209e69450eSGeorge Rimar if (Tok == "SIZEOF") { 1721b71d6f7aSEugene Leviant StringRef Name = readParenLiteral(); 1722afaa9343SEugene Leviant return 1723afaa9343SEugene Leviant [=](uint64_t Dot) { return ScriptBase->getOutputSection(Name)->Size; }; 17249e69450eSGeorge Rimar } 172536fac7f0SEugene Leviant if (Tok == "ALIGNOF") { 1726b71d6f7aSEugene Leviant StringRef Name = readParenLiteral(); 1727afaa9343SEugene Leviant return [=](uint64_t Dot) { 1728afaa9343SEugene Leviant return ScriptBase->getOutputSection(Name)->Addralign; 1729afaa9343SEugene Leviant }; 173036fac7f0SEugene Leviant } 1731e32a3598SGeorge Rimar if (Tok == "SIZEOF_HEADERS") 1732b0de56b5SRafael Espindola return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); }; 1733708019c4SRui Ueyama 17349f2f7ad9SGeorge Rimar // Tok is a literal number. 17359f2f7ad9SGeorge Rimar uint64_t V; 17369f2f7ad9SGeorge Rimar if (readInteger(Tok, V)) 1737b0de56b5SRafael Espindola return [=](uint64_t Dot) { return V; }; 17389f2f7ad9SGeorge Rimar 17399f2f7ad9SGeorge Rimar // Tok is a symbol name. 174030835ea4SGeorge Rimar if (Tok != "." && !isValidCIdentifier(Tok)) 1741708019c4SRui Ueyama setError("malformed number: " + Tok); 17422f831dcaSRafael Espindola return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); }, 1743afaa9343SEugene Leviant [=]() { return isAbsolute(Tok); }, 1744afaa9343SEugene Leviant [=]() { return ScriptBase->getSymbolSection(Tok); }}; 1745a9c5a528SGeorge Rimar } 1746708019c4SRui Ueyama 1747708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) { 17485424e7c7SJustin Bogner skip(); 1749708019c4SRui Ueyama Expr L = readExpr(); 1750708019c4SRui Ueyama expect(":"); 1751708019c4SRui Ueyama Expr R = readExpr(); 1752708019c4SRui Ueyama return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); }; 1753708019c4SRui Ueyama } 1754708019c4SRui Ueyama 17556ad7dfccSRui Ueyama Expr ScriptParser::readParenExpr() { 17566ad7dfccSRui Ueyama expect("("); 17576ad7dfccSRui Ueyama Expr E = readExpr(); 17586ad7dfccSRui Ueyama expect(")"); 17596ad7dfccSRui Ueyama return E; 17606ad7dfccSRui Ueyama } 17616ad7dfccSRui Ueyama 1762bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() { 1763bbe38602SEugene Leviant std::vector<StringRef> Phdrs; 1764bbe38602SEugene Leviant while (!Error && peek().startswith(":")) { 1765bbe38602SEugene Leviant StringRef Tok = next(); 1766da841c16SGeorge Rimar Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1)); 1767bbe38602SEugene Leviant } 1768bbe38602SEugene Leviant return Phdrs; 1769bbe38602SEugene Leviant } 1770bbe38602SEugene Leviant 177195dd718cSGeorge Rimar // Read a program header type name. The next token must be a 177295dd718cSGeorge Rimar // name of a program header type or a constant (e.g. "0x3"). 1773bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() { 1774bbe38602SEugene Leviant StringRef Tok = next(); 177595dd718cSGeorge Rimar uint64_t Val; 177695dd718cSGeorge Rimar if (readInteger(Tok, Val)) 177795dd718cSGeorge Rimar return Val; 177895dd718cSGeorge Rimar 1779b0f6c590SRui Ueyama unsigned Ret = StringSwitch<unsigned>(Tok) 1780b0f6c590SRui Ueyama .Case("PT_NULL", PT_NULL) 1781b0f6c590SRui Ueyama .Case("PT_LOAD", PT_LOAD) 1782b0f6c590SRui Ueyama .Case("PT_DYNAMIC", PT_DYNAMIC) 1783b0f6c590SRui Ueyama .Case("PT_INTERP", PT_INTERP) 1784b0f6c590SRui Ueyama .Case("PT_NOTE", PT_NOTE) 1785b0f6c590SRui Ueyama .Case("PT_SHLIB", PT_SHLIB) 1786b0f6c590SRui Ueyama .Case("PT_PHDR", PT_PHDR) 1787b0f6c590SRui Ueyama .Case("PT_TLS", PT_TLS) 1788b0f6c590SRui Ueyama .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME) 1789b0f6c590SRui Ueyama .Case("PT_GNU_STACK", PT_GNU_STACK) 1790b0f6c590SRui Ueyama .Case("PT_GNU_RELRO", PT_GNU_RELRO) 1791270173f2SGeorge Rimar .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE) 1792cc6e567cSGeorge Rimar .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED) 1793b0f6c590SRui Ueyama .Default(-1); 1794bbe38602SEugene Leviant 1795b0f6c590SRui Ueyama if (Ret == (unsigned)-1) { 1796b0f6c590SRui Ueyama setError("invalid program header type: " + Tok); 1797b0f6c590SRui Ueyama return PT_NULL; 1798b0f6c590SRui Ueyama } 1799b0f6c590SRui Ueyama return Ret; 1800bbe38602SEugene Leviant } 1801bbe38602SEugene Leviant 180295769b4aSRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) { 180320b6598cSGeorge Rimar // Identifiers start at 2 because 0 and 1 are reserved 180420b6598cSGeorge Rimar // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants. 180520b6598cSGeorge Rimar size_t VersionId = Config->VersionDefinitions.size() + 2; 180620b6598cSGeorge Rimar Config->VersionDefinitions.push_back({VerStr, VersionId}); 180720b6598cSGeorge Rimar 180883043f23SRui Ueyama if (consume("global:") || peek() != "local:") 180920b6598cSGeorge Rimar readGlobal(VerStr); 181083043f23SRui Ueyama if (consume("local:")) 1811bb6c01e7SGeorge Rimar readLocal(VerStr); 181220b6598cSGeorge Rimar expect("}"); 181320b6598cSGeorge Rimar 181420b6598cSGeorge Rimar // Each version may have a parent version. For example, "Ver2" defined as 181520b6598cSGeorge Rimar // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This 181620b6598cSGeorge Rimar // version hierarchy is, probably against your instinct, purely for human; the 181720b6598cSGeorge Rimar // runtime doesn't care about them at all. In LLD, we simply skip the token. 181820b6598cSGeorge Rimar if (!VerStr.empty() && peek() != ";") 18195424e7c7SJustin Bogner skip(); 182020b6598cSGeorge Rimar expect(";"); 182120b6598cSGeorge Rimar } 182220b6598cSGeorge Rimar 1823e0fc2421SGeorge Rimar void ScriptParser::readSymbols(std::vector<SymbolVersion> &V) { 1824e0fc2421SGeorge Rimar for (;;) { 1825e0fc2421SGeorge Rimar if (consume("extern")) 1826e0fc2421SGeorge Rimar readVersionExtern(&V); 1827e0fc2421SGeorge Rimar 1828e0fc2421SGeorge Rimar StringRef Cur = peek(); 1829e0fc2421SGeorge Rimar if (Cur == "}" || Cur == "local:" || Error) 1830e0fc2421SGeorge Rimar return; 1831e0fc2421SGeorge Rimar skip(); 1832e0fc2421SGeorge Rimar V.push_back({unquote(Cur), false, hasWildcard(Cur)}); 1833e0fc2421SGeorge Rimar expect(";"); 1834e0fc2421SGeorge Rimar } 1835e0fc2421SGeorge Rimar } 1836e0fc2421SGeorge Rimar 1837bb6c01e7SGeorge Rimar void ScriptParser::readLocal(StringRef VerStr) { 1838bb6c01e7SGeorge Rimar if (consume("*")) { 183920b6598cSGeorge Rimar Config->DefaultSymbolVersion = VER_NDX_LOCAL; 184020b6598cSGeorge Rimar expect(";"); 1841bb6c01e7SGeorge Rimar return; 1842bb6c01e7SGeorge Rimar } 1843bb6c01e7SGeorge Rimar 1844bb6c01e7SGeorge Rimar if (VerStr.empty()) 1845bb6c01e7SGeorge Rimar setError("locals list for anonymous version is not supported"); 1846bb6c01e7SGeorge Rimar 1847*17c65af8SGeorge Rimar readSymbols(Config->VersionScriptLocals); 184820b6598cSGeorge Rimar } 184920b6598cSGeorge Rimar 1850e0fc2421SGeorge Rimar void ScriptParser::readVersionExtern(std::vector<SymbolVersion> *V) { 1851cd574a5eSGeorge Rimar expect("\"C++\""); 185220b6598cSGeorge Rimar expect("{"); 185320b6598cSGeorge Rimar 185420b6598cSGeorge Rimar for (;;) { 185520b6598cSGeorge Rimar if (peek() == "}" || Error) 185620b6598cSGeorge Rimar break; 1857cd574a5eSGeorge Rimar bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek()); 1858e0fc2421SGeorge Rimar V->push_back({unquote(next()), true, HasWildcard}); 185920b6598cSGeorge Rimar expect(";"); 186020b6598cSGeorge Rimar } 186120b6598cSGeorge Rimar 186220b6598cSGeorge Rimar expect("}"); 186320b6598cSGeorge Rimar expect(";"); 186420b6598cSGeorge Rimar } 186520b6598cSGeorge Rimar 186620b6598cSGeorge Rimar void ScriptParser::readGlobal(StringRef VerStr) { 186720b6598cSGeorge Rimar if (VerStr.empty()) 1868e0fc2421SGeorge Rimar readSymbols(Config->VersionScriptGlobals); 186920b6598cSGeorge Rimar else 1870e0fc2421SGeorge Rimar readSymbols(Config->VersionDefinitions.back().Globals); 187120b6598cSGeorge Rimar } 187220b6598cSGeorge Rimar 187316b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) { 187416b0cc9eSSimon Atanasyan if (Config->Sysroot == "") 187516b0cc9eSSimon Atanasyan return false; 187616b0cc9eSSimon Atanasyan for (; !Path.empty(); Path = sys::path::parent_path(Path)) 187716b0cc9eSSimon Atanasyan if (sys::fs::equivalent(Config->Sysroot, Path)) 187816b0cc9eSSimon Atanasyan return true; 187916b0cc9eSSimon Atanasyan return false; 188016b0cc9eSSimon Atanasyan } 188116b0cc9eSSimon Atanasyan 188207320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) { 188316b0cc9eSSimon Atanasyan StringRef Path = MB.getBufferIdentifier(); 188420b6598cSGeorge Rimar ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript(); 188520b6598cSGeorge Rimar } 188620b6598cSGeorge Rimar 188720b6598cSGeorge Rimar void elf::readVersionScript(MemoryBufferRef MB) { 188820b6598cSGeorge Rimar ScriptParser(MB.getBuffer(), false).readVersionScript(); 1889f7c5fbb1SRui Ueyama } 18901ebc8ed7SRui Ueyama 189107320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>; 189207320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>; 189307320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>; 189407320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>; 1895