1f7c5fbb1SRui Ueyama //===- LinkerScript.cpp ---------------------------------------------------===//
2f7c5fbb1SRui Ueyama //
3f7c5fbb1SRui Ueyama //                             The LLVM Linker
4f7c5fbb1SRui Ueyama //
5f7c5fbb1SRui Ueyama // This file is distributed under the University of Illinois Open Source
6f7c5fbb1SRui Ueyama // License. See LICENSE.TXT for details.
7f7c5fbb1SRui Ueyama //
8f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
9f7c5fbb1SRui Ueyama //
10f7c5fbb1SRui Ueyama // This file contains the parser/evaluator of the linker script.
11f7c5fbb1SRui Ueyama //
12f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
13f7c5fbb1SRui Ueyama 
14717677afSRui Ueyama #include "LinkerScript.h"
15f7c5fbb1SRui Ueyama #include "Config.h"
16f7c5fbb1SRui Ueyama #include "Driver.h"
171ebc8ed7SRui Ueyama #include "InputSection.h"
189381eb10SRui Ueyama #include "Memory.h"
19652852c5SGeorge Rimar #include "OutputSections.h"
20e77b5bf6SAdhemerval Zanella #include "ScriptParser.h"
2193c9af42SRui Ueyama #include "Strings.h"
22f7c5fbb1SRui Ueyama #include "SymbolTable.h"
2355518e7dSRui Ueyama #include "Symbols.h"
243fb5a6dcSGeorge Rimar #include "SyntheticSections.h"
25467c4d55SEugene Leviant #include "Target.h"
26bbe38602SEugene Leviant #include "Writer.h"
2722886a28SEugene Zelenko #include "llvm/ADT/STLExtras.h"
288c6a5aafSRui Ueyama #include "llvm/ADT/SmallString.h"
2922886a28SEugene Zelenko #include "llvm/ADT/StringRef.h"
30960504b9SRui Ueyama #include "llvm/ADT/StringSwitch.h"
3122886a28SEugene Zelenko #include "llvm/Support/Casting.h"
32652852c5SGeorge Rimar #include "llvm/Support/ELF.h"
3322886a28SEugene Zelenko #include "llvm/Support/Endian.h"
3422886a28SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
35f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h"
3622886a28SEugene Zelenko #include "llvm/Support/MathExtras.h"
37f03f3cc1SRui Ueyama #include "llvm/Support/Path.h"
3822886a28SEugene Zelenko #include <algorithm>
3922886a28SEugene Zelenko #include <cassert>
4022886a28SEugene Zelenko #include <cstddef>
4122886a28SEugene Zelenko #include <cstdint>
4222886a28SEugene Zelenko #include <iterator>
4322886a28SEugene Zelenko #include <limits>
4422886a28SEugene Zelenko #include <memory>
4522886a28SEugene Zelenko #include <string>
4622886a28SEugene Zelenko #include <tuple>
4722886a28SEugene Zelenko #include <vector>
48f7c5fbb1SRui Ueyama 
49f7c5fbb1SRui Ueyama using namespace llvm;
50652852c5SGeorge Rimar using namespace llvm::ELF;
511ebc8ed7SRui Ueyama using namespace llvm::object;
52e38cbab5SGeorge Rimar using namespace llvm::support::endian;
53f7c5fbb1SRui Ueyama using namespace lld;
54e0df00b9SRafael Espindola using namespace lld::elf;
55f7c5fbb1SRui Ueyama 
56884e786dSGeorge Rimar LinkerScriptBase *elf::ScriptBase;
5707320e40SRui Ueyama ScriptConfiguration *elf::ScriptConfig;
58717677afSRui Ueyama 
596c55f0e3SGeorge Rimar template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
603dabfc6bSRafael Espindola   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
611bdaf3e3SRui Ueyama   Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
62463984d4SGeorge Rimar                                             0, 0, STB_GLOBAL, nullptr, nullptr);
631602421cSRui Ueyama   Cmd->Sym = Sym->body();
6420d03194SEugene Leviant 
6520d03194SEugene Leviant   // If we have no SECTIONS then we don't have '.' and don't call
6620d03194SEugene Leviant   // assignAddresses(). We calculate symbol value immediately in this case.
6720d03194SEugene Leviant   if (!ScriptConfig->HasSections)
6820d03194SEugene Leviant     cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
69ceabe80eSEugene Leviant }
70ceabe80eSEugene Leviant 
710c70d3ccSRui Ueyama template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
72afaa9343SEugene Leviant   // If we have SECTIONS block then output sections haven't been created yet.
73afaa9343SEugene Leviant   const OutputSectionBase *Sec =
74afaa9343SEugene Leviant       ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
75e1937bb5SGeorge Rimar   Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
76afaa9343SEugene Leviant       Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
771602421cSRui Ueyama   Cmd->Sym = Sym->body();
78afaa9343SEugene Leviant 
79afaa9343SEugene Leviant   // If we already know section then we can calculate symbol value immediately.
80afaa9343SEugene Leviant   if (Sec)
81afaa9343SEugene Leviant     cast<DefinedSynthetic<ELFT>>(Cmd->Sym)->Value =
82afaa9343SEugene Leviant         Cmd->Expression(0) - Sec->Addr;
83ceabe80eSEugene Leviant }
84ceabe80eSEugene Leviant 
8522375f24SRui Ueyama static bool isUnderSysroot(StringRef Path) {
8622375f24SRui Ueyama   if (Config->Sysroot == "")
8722375f24SRui Ueyama     return false;
8822375f24SRui Ueyama   for (; !Path.empty(); Path = sys::path::parent_path(Path))
8922375f24SRui Ueyama     if (sys::fs::equivalent(Config->Sysroot, Path))
9022375f24SRui Ueyama       return true;
9122375f24SRui Ueyama   return false;
9222375f24SRui Ueyama }
9322375f24SRui Ueyama 
94db741e72SEugene Leviant template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
952f831dcaSRafael Espindola   if (Cmd->Expression.IsAbsolute())
96db741e72SEugene Leviant     addRegular<ELFT>(Cmd);
97db741e72SEugene Leviant   else
98db741e72SEugene Leviant     addSynthetic<ELFT>(Cmd);
99db741e72SEugene Leviant }
1001602421cSRui Ueyama // If a symbol was in PROVIDE(), we need to define it only when
1011602421cSRui Ueyama // it is an undefined symbol.
1021602421cSRui Ueyama template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
1031602421cSRui Ueyama   if (Cmd->Name == ".")
104ceabe80eSEugene Leviant     return false;
1051602421cSRui Ueyama   if (!Cmd->Provide)
106ceabe80eSEugene Leviant     return true;
1071602421cSRui Ueyama   SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
1081602421cSRui Ueyama   return B && B->isUndefined();
109ceabe80eSEugene Leviant }
110ceabe80eSEugene Leviant 
111076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
112076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
113076fe157SGeorge Rimar }
114076fe157SGeorge Rimar 
115076fe157SGeorge Rimar bool OutputSectionCommand::classof(const BaseCommand *C) {
116076fe157SGeorge Rimar   return C->Kind == OutputSectionKind;
117076fe157SGeorge Rimar }
118076fe157SGeorge Rimar 
119eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
120eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
121eea3114fSGeorge Rimar }
122eea3114fSGeorge Rimar 
123eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
124eefa758eSGeorge Rimar   return C->Kind == AssertKind;
125eefa758eSGeorge Rimar }
126eefa758eSGeorge Rimar 
127e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) {
128e38cbab5SGeorge Rimar   return C->Kind == BytesDataKind;
129e38cbab5SGeorge Rimar }
130e38cbab5SGeorge Rimar 
13122886a28SEugene Zelenko template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
13222886a28SEugene Zelenko template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
133f34d0e08SRui Ueyama 
134e0be2901SRui Ueyama template <class ELFT> static StringRef basename(InputSectionBase<ELFT> *S) {
135e0be2901SRui Ueyama   if (S->getFile())
136e0be2901SRui Ueyama     return sys::path::filename(S->getFile()->getName());
137e0be2901SRui Ueyama   return "";
138e0be2901SRui Ueyama }
139e0be2901SRui Ueyama 
14007320e40SRui Ueyama template <class ELFT>
14107320e40SRui Ueyama bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
142e0be2901SRui Ueyama   for (InputSectionDescription *ID : Opt.KeptSections)
143e0be2901SRui Ueyama     if (ID->FilePat.match(basename(S)))
144cf43f179SEugene Leviant       for (SectionPattern &P : ID->SectionPatterns)
145f91282e1SRui Ueyama         if (P.SectionPat.match(S->Name))
146eea3114fSGeorge Rimar           return true;
147eea3114fSGeorge Rimar   return false;
148eea3114fSGeorge Rimar }
149eea3114fSGeorge Rimar 
150575208caSGeorge Rimar static bool comparePriority(InputSectionData *A, InputSectionData *B) {
151575208caSGeorge Rimar   return getPriority(A->Name) < getPriority(B->Name);
152575208caSGeorge Rimar }
153575208caSGeorge Rimar 
154c0028d3dSRafael Espindola static bool compareName(InputSectionData *A, InputSectionData *B) {
155042a3f20SRafael Espindola   return A->Name < B->Name;
1560702c4e8SGeorge Rimar }
157742c3836SRui Ueyama 
158c0028d3dSRafael Espindola static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
159742c3836SRui Ueyama   // ">" is not a mistake. Larger alignments are placed before smaller
160742c3836SRui Ueyama   // alignments in order to reduce the amount of padding necessary.
161742c3836SRui Ueyama   // This is compatible with GNU.
162742c3836SRui Ueyama   return A->Alignment > B->Alignment;
163742c3836SRui Ueyama }
164742c3836SRui Ueyama 
165c0028d3dSRafael Espindola static std::function<bool(InputSectionData *, InputSectionData *)>
166be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
167be394db3SGeorge Rimar   switch (K) {
168be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
169c0028d3dSRafael Espindola     return compareAlignment;
170be394db3SGeorge Rimar   case SortSectionPolicy::Name:
171be394db3SGeorge Rimar     return compareName;
172be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
173be394db3SGeorge Rimar     return comparePriority;
174be394db3SGeorge Rimar   default:
175be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
176be394db3SGeorge Rimar   }
177742c3836SRui Ueyama }
1780702c4e8SGeorge Rimar 
17948c3f1ceSRui Ueyama template <class ELFT>
180e71a3f8aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
18106ae6836SGeorge Rimar                              ConstraintKind Kind) {
1828f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
1838f66df92SGeorge Rimar     return true;
184e746e52cSRafael Espindola   bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
185d3190795SRafael Espindola     auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
1861854a8ebSRafael Espindola     return Sec->Flags & SHF_WRITE;
18706ae6836SGeorge Rimar   });
188e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
189e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
19006ae6836SGeorge Rimar }
19106ae6836SGeorge Rimar 
19207171f21SGeorge Rimar static void sortSections(InputSectionData **Begin, InputSectionData **End,
193ee924709SRui Ueyama                          SortSectionPolicy K) {
194ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
19507171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
196ee924709SRui Ueyama }
197ee924709SRui Ueyama 
198d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
199be94e1b6SRafael Espindola template <class ELFT>
200e71a3f8aSRafael Espindola void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
2014dc07becSRui Ueyama   // Collects all sections that satisfy constraints of I
2024dc07becSRui Ueyama   // and attach them to I.
2034dc07becSRui Ueyama   for (SectionPattern &Pat : I->SectionPatterns) {
20407171f21SGeorge Rimar     size_t SizeBefore = I->Sections.size();
2058c6a5aafSRui Ueyama 
2068c6a5aafSRui Ueyama     for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
207f94efdddSRui Ueyama       if (!S->Live || S->Assigned)
2088c6a5aafSRui Ueyama         continue;
2098c6a5aafSRui Ueyama 
210e0be2901SRui Ueyama       StringRef Filename = basename(S);
211e0be2901SRui Ueyama       if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
212e0be2901SRui Ueyama         continue;
213e0be2901SRui Ueyama       if (!Pat.SectionPat.match(S->Name))
214e0be2901SRui Ueyama         continue;
215d3190795SRafael Espindola       I->Sections.push_back(S);
216f94efdddSRui Ueyama       S->Assigned = true;
217f94efdddSRui Ueyama     }
218d3190795SRafael Espindola 
219ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
220ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
221ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
222ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
223ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
224ee924709SRui Ueyama     //
225ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
226ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
227ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
228ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
229ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
23007171f21SGeorge Rimar     InputSectionData **Begin = I->Sections.data() + SizeBefore;
23107171f21SGeorge Rimar     InputSectionData **End = I->Sections.data() + I->Sections.size();
23207171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
23307171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
23407171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
235ee924709SRui Ueyama       else
23607171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
23707171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
23807171f21SGeorge Rimar     }
239ee924709SRui Ueyama   }
240be94e1b6SRafael Espindola }
241be94e1b6SRafael Espindola 
242be94e1b6SRafael Espindola template <class ELFT>
243be94e1b6SRafael Espindola void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
244be94e1b6SRafael Espindola   for (InputSectionBase<ELFT> *S : V) {
245be94e1b6SRafael Espindola     S->Live = false;
246be94e1b6SRafael Espindola     reportDiscarded(S);
247be94e1b6SRafael Espindola   }
248be94e1b6SRafael Espindola }
249be94e1b6SRafael Espindola 
25006ae6836SGeorge Rimar template <class ELFT>
2510b9ce6a4SRui Ueyama std::vector<InputSectionBase<ELFT> *>
25206ae6836SGeorge Rimar LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
2530b9ce6a4SRui Ueyama   std::vector<InputSectionBase<ELFT> *> Ret;
254e7f912cdSRui Ueyama 
25506ae6836SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
2567c3ff2ebSRafael Espindola     auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
2577c3ff2ebSRafael Espindola     if (!Cmd)
2580b9ce6a4SRui Ueyama       continue;
259e71a3f8aSRafael Espindola     computeInputSections(Cmd);
260d3190795SRafael Espindola     for (InputSectionData *S : Cmd->Sections)
261d3190795SRafael Espindola       Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
2620b9ce6a4SRui Ueyama   }
263e71a3f8aSRafael Espindola 
2640b9ce6a4SRui Ueyama   return Ret;
2650b9ce6a4SRui Ueyama }
2660b9ce6a4SRui Ueyama 
267e5d3ca50SPetr Hosek template <class ELFT>
26810897f18SRafael Espindola static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
26910897f18SRafael Espindola                                             StringRef OutsecName) {
27010897f18SRafael Espindola   // When using linker script the merge rules are different.
27110897f18SRafael Espindola   // Unfortunately, linker scripts are name based. This means that expressions
27210897f18SRafael Espindola   // like *(.foo*) can refer to multiple input sections that would normally be
27310897f18SRafael Espindola   // placed in different output sections. We cannot put them in different
27410897f18SRafael Espindola   // output sections or we would produce wrong results for
27510897f18SRafael Espindola   // start = .; *(.foo.*) end = .; *(.bar)
27610897f18SRafael Espindola   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
27710897f18SRafael Espindola   // another. The problem is that there is no way to layout those output
27810897f18SRafael Espindola   // sections such that the .foo sections are the only thing between the
27910897f18SRafael Espindola   // start and end symbols.
28010897f18SRafael Espindola 
28110897f18SRafael Espindola   // An extra annoyance is that we cannot simply disable merging of the contents
28210897f18SRafael Espindola   // of SHF_MERGE sections, but our implementation requires one output section
28310897f18SRafael Espindola   // per "kind" (string or not, which size/aligment).
28410897f18SRafael Espindola   // Fortunately, creating symbols in the middle of a merge section is not
28510897f18SRafael Espindola   // supported by bfd or gold, so we can just create multiple section in that
28610897f18SRafael Espindola   // case.
28710897f18SRafael Espindola   typedef typename ELFT::uint uintX_t;
2881854a8ebSRafael Espindola   uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
28910897f18SRafael Espindola 
29010897f18SRafael Espindola   uintX_t Alignment = 0;
29110897f18SRafael Espindola   if (isa<MergeInputSection<ELFT>>(C))
2921854a8ebSRafael Espindola     Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
29310897f18SRafael Espindola 
29410897f18SRafael Espindola   return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
29510897f18SRafael Espindola }
29610897f18SRafael Espindola 
29710897f18SRafael Espindola template <class ELFT>
29820d03194SEugene Leviant void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
29920d03194SEugene Leviant                                     InputSectionBase<ELFT> *Sec,
30020d03194SEugene Leviant                                     StringRef Name) {
301e08e78dfSRafael Espindola   OutputSectionBase *OutSec;
30228c1597aSRafael Espindola   bool IsNew;
30310897f18SRafael Espindola   std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
30428c1597aSRafael Espindola   if (IsNew)
30528c1597aSRafael Espindola     OutputSections->push_back(OutSec);
30620d03194SEugene Leviant   OutSec->addSection(Sec);
30720d03194SEugene Leviant }
30820d03194SEugene Leviant 
30920d03194SEugene Leviant template <class ELFT>
31020d03194SEugene Leviant void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
3117c3ff2ebSRafael Espindola   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
3127c3ff2ebSRafael Espindola     auto Iter = Opt.Commands.begin() + I;
3137c3ff2ebSRafael Espindola     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
3140b1b695aSRui Ueyama 
3150b1b695aSRui Ueyama     // Handle symbol assignments outside of any output section.
3162ab5f73dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
3172ab5f73dSRui Ueyama       if (shouldDefine<ELFT>(Cmd))
318b0de56b5SRafael Espindola         addSymbol<ELFT>(Cmd);
3192ab5f73dSRui Ueyama       continue;
3202ab5f73dSRui Ueyama     }
3210b1b695aSRui Ueyama 
32220d03194SEugene Leviant     if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
32320d03194SEugene Leviant       // If we don't have SECTIONS then output sections have already been
324194470cdSGeorge Rimar       // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
32520d03194SEugene Leviant       // will not be called, so ASSERT should be evaluated now.
32620d03194SEugene Leviant       if (!Opt.HasSections)
32720d03194SEugene Leviant         Cmd->Expression(0);
32820d03194SEugene Leviant       continue;
32920d03194SEugene Leviant     }
3302ab5f73dSRui Ueyama 
331ceabe80eSEugene Leviant     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
3327bd37870SRafael Espindola       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
3337bd37870SRafael Espindola 
3340b1b695aSRui Ueyama       // The output section name `/DISCARD/' is special.
3350b1b695aSRui Ueyama       // Any input section assigned to it is discarded.
33648c3f1ceSRui Ueyama       if (Cmd->Name == "/DISCARD/") {
3377bd37870SRafael Espindola         discard(V);
33848c3f1ceSRui Ueyama         continue;
33948c3f1ceSRui Ueyama       }
3400b9ce6a4SRui Ueyama 
3410b1b695aSRui Ueyama       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
3420b1b695aSRui Ueyama       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
3430b1b695aSRui Ueyama       // sections satisfy a given constraint. If not, a directive is handled
3440b1b695aSRui Ueyama       // as if it wasn't present from the beginning.
3450b1b695aSRui Ueyama       //
3460b1b695aSRui Ueyama       // Because we'll iterate over Commands many more times, the easiest
3470b1b695aSRui Ueyama       // way to "make it as if it wasn't present" is to just remove it.
3487c3ff2ebSRafael Espindola       if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
3497c3ff2ebSRafael Espindola         for (InputSectionBase<ELFT> *S : V)
350f94efdddSRui Ueyama           S->Assigned = false;
3517c3ff2ebSRafael Espindola         Opt.Commands.erase(Iter);
352dfbbbc86SGeorge Rimar         --I;
3537c3ff2ebSRafael Espindola         continue;
3547c3ff2ebSRafael Espindola       }
3557c3ff2ebSRafael Espindola 
3560b1b695aSRui Ueyama       // A directive may contain symbol definitions like this:
3570b1b695aSRui Ueyama       // ".foo : { ...; bar = .; }". Handle them.
3587c3ff2ebSRafael Espindola       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
3597c3ff2ebSRafael Espindola         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
3607c3ff2ebSRafael Espindola           if (shouldDefine<ELFT>(OutCmd))
3617c3ff2ebSRafael Espindola             addSymbol<ELFT>(OutCmd);
3627c3ff2ebSRafael Espindola 
3630b1b695aSRui Ueyama       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
3640b1b695aSRui Ueyama       // is given, input sections are aligned to that value, whether the
3650b1b695aSRui Ueyama       // given value is larger or smaller than the original section alignment.
3660b1b695aSRui Ueyama       if (Cmd->SubalignExpr) {
3670b1b695aSRui Ueyama         uint32_t Subalign = Cmd->SubalignExpr(0);
3680b1b695aSRui Ueyama         for (InputSectionBase<ELFT> *S : V)
3690b1b695aSRui Ueyama           S->Alignment = Subalign;
37020d03194SEugene Leviant       }
3710b1b695aSRui Ueyama 
3720b1b695aSRui Ueyama       // Add input sections to an output section.
3730b1b695aSRui Ueyama       for (InputSectionBase<ELFT> *S : V)
3740b1b695aSRui Ueyama         addSection(Factory, S, Cmd->Name);
375eea3114fSGeorge Rimar     }
37648c3f1ceSRui Ueyama   }
377db24d9c3SGeorge Rimar }
378e63d81bdSEugene Leviant 
3790b1b695aSRui Ueyama // Add sections that didn't match any sections command.
38020d03194SEugene Leviant template <class ELFT>
38193c64025SGeorge Rimar void LinkerScript<ELFT>::addOrphanSections(
38293c64025SGeorge Rimar     OutputSectionFactory<ELFT> &Factory) {
3838c6a5aafSRui Ueyama   for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
3848f9026baSRafael Espindola     if (S->Live && !S->OutSec)
38555518e7dSRui Ueyama       addSection(Factory, S, getOutputSectionName(S->Name));
386e63d81bdSEugene Leviant }
387e63d81bdSEugene Leviant 
388db741e72SEugene Leviant // Sets value of a section-defined symbol. Two kinds of
389db741e72SEugene Leviant // symbols are processed: synthetic symbols, whose value
390db741e72SEugene Leviant // is an offset from beginning of section and regular
391db741e72SEugene Leviant // symbols whose value is absolute.
392db741e72SEugene Leviant template <class ELFT>
393afaa9343SEugene Leviant static void assignSectionSymbol(SymbolAssignment *Cmd,
394498ed714SRafael Espindola                                 typename ELFT::uint Value) {
395db741e72SEugene Leviant   if (!Cmd->Sym)
396db741e72SEugene Leviant     return;
397db741e72SEugene Leviant 
398db741e72SEugene Leviant   if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
399afaa9343SEugene Leviant     Body->Section = Cmd->Expression.Section();
400afaa9343SEugene Leviant     Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
401db741e72SEugene Leviant     return;
402db741e72SEugene Leviant   }
403db741e72SEugene Leviant   auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
404498ed714SRafael Espindola   Body->Value = Cmd->Expression(Value);
405db741e72SEugene Leviant }
406db741e72SEugene Leviant 
407e08e78dfSRafael Espindola template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
40804a2e348SRafael Espindola   return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
409a940e539SRafael Espindola }
410a940e539SRafael Espindola 
411d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
412d3190795SRafael Espindola   if (!AlreadyOutputIS.insert(S).second)
413ceabe80eSEugene Leviant     return;
414e08e78dfSRafael Espindola   bool IsTbss = isTbss<ELFT>(CurOutSec);
415d3190795SRafael Espindola 
416d3190795SRafael Espindola   uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
417d3190795SRafael Espindola   Pos = alignTo(Pos, S->Alignment);
41804a2e348SRafael Espindola   S->OutSecOff = Pos - CurOutSec->Addr;
419d3190795SRafael Espindola   Pos += S->getSize();
420d3190795SRafael Espindola 
421d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
422d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
423d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
42404a2e348SRafael Espindola   CurOutSec->Size = Pos - CurOutSec->Addr;
425d3190795SRafael Espindola 
4267252ae52SRafael Espindola   if (IsTbss)
4277252ae52SRafael Espindola     ThreadBssOffset = Pos - Dot;
4287252ae52SRafael Espindola   else
429d3190795SRafael Espindola     Dot = Pos;
4302de509c3SRui Ueyama }
431ceabe80eSEugene Leviant 
432d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::flush() {
43365499b90SRafael Espindola   if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
43465499b90SRafael Espindola     return;
43565499b90SRafael Espindola   if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
436d3190795SRafael Espindola     for (InputSection<ELFT> *I : OutSec->Sections)
437d3190795SRafael Espindola       output(I);
43865499b90SRafael Espindola   } else {
43904a2e348SRafael Espindola     Dot += CurOutSec->Size;
440d3190795SRafael Espindola   }
441d3190795SRafael Espindola }
44297403d15SEugene Leviant 
443d3190795SRafael Espindola template <class ELFT>
444e08e78dfSRafael Espindola void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
445d3190795SRafael Espindola   if (CurOutSec == Sec)
446d3190795SRafael Espindola     return;
447d3190795SRafael Espindola   if (AlreadyOutputOS.count(Sec))
448d3190795SRafael Espindola     return;
449d3190795SRafael Espindola 
450d3190795SRafael Espindola   flush();
451d3190795SRafael Espindola   CurOutSec = Sec;
452d3190795SRafael Espindola 
45304a2e348SRafael Espindola   Dot = alignTo(Dot, CurOutSec->Addralign);
454e08e78dfSRafael Espindola   CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
455b71d6f7aSEugene Leviant 
456b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
457b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
458b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
459b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
460b71d6f7aSEugene Leviant   CurOutSec->setLMAOffset(LMAOffset);
461d3190795SRafael Espindola }
462d3190795SRafael Espindola 
463d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
464e38cbab5SGeorge Rimar   // This handles the assignments to symbol or to a location counter (.)
465d3190795SRafael Espindola   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
46697403d15SEugene Leviant     if (AssignCmd->Name == ".") {
46797403d15SEugene Leviant       // Update to location counter means update to section size.
46814460e02SGeorge Rimar       uintX_t Val = AssignCmd->Expression(Dot);
46914460e02SGeorge Rimar       if (Val < Dot)
47014460e02SGeorge Rimar         error("unable to move location counter backward for: " +
47114460e02SGeorge Rimar               CurOutSec->Name);
47214460e02SGeorge Rimar       Dot = Val;
47304a2e348SRafael Espindola       CurOutSec->Size = Dot - CurOutSec->Addr;
474d3190795SRafael Espindola       return;
47597403d15SEugene Leviant     }
476afaa9343SEugene Leviant     assignSectionSymbol<ELFT>(AssignCmd, Dot);
477d3190795SRafael Espindola     return;
47897403d15SEugene Leviant   }
479e38cbab5SGeorge Rimar 
480e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
481e38cbab5SGeorge Rimar   if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
48204a2e348SRafael Espindola     DataCmd->Offset = Dot - CurOutSec->Addr;
483e38cbab5SGeorge Rimar     Dot += DataCmd->Size;
48404a2e348SRafael Espindola     CurOutSec->Size = Dot - CurOutSec->Addr;
485e38cbab5SGeorge Rimar     return;
486e38cbab5SGeorge Rimar   }
487e38cbab5SGeorge Rimar 
488b2d99d6aSMeador Inge   if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
489b2d99d6aSMeador Inge     AssertCmd->Expression(Dot);
490b2d99d6aSMeador Inge     return;
491b2d99d6aSMeador Inge   }
492b2d99d6aSMeador Inge 
493e38cbab5SGeorge Rimar   // It handles single input section description command,
494e38cbab5SGeorge Rimar   // calculates and assigns the offsets for each section and also
495e38cbab5SGeorge Rimar   // updates the output section size.
496d3190795SRafael Espindola   auto &ICmd = cast<InputSectionDescription>(Base);
497d3190795SRafael Espindola   for (InputSectionData *ID : ICmd.Sections) {
4983fb5a6dcSGeorge Rimar     // We tentatively added all synthetic sections at the beginning and removed
4993fb5a6dcSGeorge Rimar     // empty ones afterwards (because there is no way to know whether they were
5003fb5a6dcSGeorge Rimar     // going be empty or not other than actually running linker scripts.)
5013fb5a6dcSGeorge Rimar     // We need to ignore remains of empty sections.
5023fb5a6dcSGeorge Rimar     if (auto *Sec = dyn_cast<SyntheticSection<ELFT>>(ID))
5033fb5a6dcSGeorge Rimar       if (Sec->empty())
5043fb5a6dcSGeorge Rimar         continue;
5053fb5a6dcSGeorge Rimar 
506d3190795SRafael Espindola     auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
507d3190795SRafael Espindola     switchTo(IB->OutSec);
508d3190795SRafael Espindola     if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
509d3190795SRafael Espindola       output(I);
51065499b90SRafael Espindola     else
51165499b90SRafael Espindola       flush();
512ceabe80eSEugene Leviant   }
513ceabe80eSEugene Leviant }
514ceabe80eSEugene Leviant 
5158f66df92SGeorge Rimar template <class ELFT>
516e08e78dfSRafael Espindola static std::vector<OutputSectionBase *>
517e08e78dfSRafael Espindola findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
518e08e78dfSRafael Espindola   std::vector<OutputSectionBase *> Ret;
519e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : Sections)
5209257764dSEugene Leviant     if (Sec->getName() == Name)
521a14b13d8SGeorge Rimar       Ret.push_back(Sec);
522a14b13d8SGeorge Rimar   return Ret;
5238f66df92SGeorge Rimar }
5248f66df92SGeorge Rimar 
5250b1b695aSRui Ueyama // This function assigns offsets to input sections and an output section
5260b1b695aSRui Ueyama // for a single sections command (e.g. ".text { *(.text); }").
527d3190795SRafael Espindola template <class ELFT>
528d3190795SRafael Espindola void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
529b71d6f7aSEugene Leviant   if (Cmd->LMAExpr)
530b71d6f7aSEugene Leviant     LMAOffset = Cmd->LMAExpr(Dot) - Dot;
531e08e78dfSRafael Espindola   std::vector<OutputSectionBase *> Sections =
532e08e78dfSRafael Espindola       findSections<ELFT>(Cmd->Name, *OutputSections);
533d3190795SRafael Espindola   if (Sections.empty())
534d3190795SRafael Espindola     return;
535d3190795SRafael Espindola   switchTo(Sections[0]);
5360b1b695aSRui Ueyama 
537d3190795SRafael Espindola   // Find the last section output location. We will output orphan sections
538d3190795SRafael Espindola   // there so that end symbols point to the correct location.
539d3190795SRafael Espindola   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
540d3190795SRafael Espindola                         [](const std::unique_ptr<BaseCommand> &Cmd) {
541d3190795SRafael Espindola                           return !isa<SymbolAssignment>(*Cmd);
542d3190795SRafael Espindola                         })
543d3190795SRafael Espindola                .base();
544d3190795SRafael Espindola   for (auto I = Cmd->Commands.begin(); I != E; ++I)
545d3190795SRafael Espindola     process(**I);
546e08e78dfSRafael Espindola   for (OutputSectionBase *Base : Sections)
547d3190795SRafael Espindola     switchTo(Base);
5482506cb4dSEugene Leviant   flush();
549b31dd370SGeorge Rimar   std::for_each(E, Cmd->Commands.end(),
550b31dd370SGeorge Rimar                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
551d3190795SRafael Espindola }
552d3190795SRafael Espindola 
55307fe6129SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
5546d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
5556d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
5566d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
5576d38e4dbSRafael Espindola   // clutter the output.
5586d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
5596d38e4dbSRafael Espindola   // more aggressive at removing them.
5606d38e4dbSRafael Espindola   auto Pos = std::remove_if(
5616d38e4dbSRafael Espindola       Opt.Commands.begin(), Opt.Commands.end(),
5626d38e4dbSRafael Espindola       [&](const std::unique_ptr<BaseCommand> &Base) {
5630b1b695aSRui Ueyama         if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
5646a53737cSRafael Espindola           return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
5650b1b695aSRui Ueyama         return false;
5666d38e4dbSRafael Espindola       });
5676d38e4dbSRafael Espindola   Opt.Commands.erase(Pos, Opt.Commands.end());
56807fe6129SRafael Espindola }
56907fe6129SRafael Espindola 
5706a53737cSRafael Espindola static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
5716a53737cSRafael Espindola   for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
5726a53737cSRafael Espindola     if (!isa<InputSectionDescription>(*I))
5736a53737cSRafael Espindola       return false;
5746a53737cSRafael Espindola   return true;
5756a53737cSRafael Espindola }
5766d38e4dbSRafael Espindola 
5776a53737cSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
5789546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
5799546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
5809546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
5819546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
5829546fffbSRafael Espindola   uintX_t Flags = SHF_ALLOC;
583f93b8c29SRafael Espindola   uint32_t Type = SHT_NOBITS;
5849546fffbSRafael Espindola   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
5859546fffbSRafael Espindola     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
5869546fffbSRafael Espindola     if (!Cmd)
5879546fffbSRafael Espindola       continue;
588e08e78dfSRafael Espindola     std::vector<OutputSectionBase *> Secs =
589e08e78dfSRafael Espindola         findSections<ELFT>(Cmd->Name, *OutputSections);
5909546fffbSRafael Espindola     if (!Secs.empty()) {
59104a2e348SRafael Espindola       Flags = Secs[0]->Flags;
59204a2e348SRafael Espindola       Type = Secs[0]->Type;
5939546fffbSRafael Espindola       continue;
5949546fffbSRafael Espindola     }
5959546fffbSRafael Espindola 
5966a53737cSRafael Espindola     if (isAllSectionDescription(*Cmd))
5976a53737cSRafael Espindola       continue;
5986a53737cSRafael Espindola 
59995642b95SRui Ueyama     auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
6009546fffbSRafael Espindola     OutputSections->push_back(OutSec);
6019546fffbSRafael Espindola   }
602f7a17448SRafael Espindola }
603f7a17448SRafael Espindola 
604f7a17448SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
605f7a17448SRafael Espindola   placeOrphanSections();
606f7a17448SRafael Espindola 
607f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
608f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
609f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
610f7a17448SRafael Espindola   // Below is an example of such linker script:
611f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
612f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
613f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
614f7a17448SRafael Espindola   auto FirstPtLoad =
615f7a17448SRafael Espindola       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
616f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
617f7a17448SRafael Espindola   if (FirstPtLoad != Opt.PhdrsCommands.end())
618f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
619f7a17448SRafael Espindola 
620f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
621f7a17448SRafael Espindola   // explicitly specify them.
622f7a17448SRafael Espindola   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
623f7a17448SRafael Espindola     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
624f7a17448SRafael Espindola     if (!Cmd)
625f7a17448SRafael Espindola       continue;
626f7a17448SRafael Espindola     if (Cmd->Phdrs.empty())
627f7a17448SRafael Espindola       Cmd->Phdrs = DefPhdrs;
628f7a17448SRafael Espindola     else
629f7a17448SRafael Espindola       DefPhdrs = Cmd->Phdrs;
630f7a17448SRafael Espindola   }
6316a53737cSRafael Espindola 
6326a53737cSRafael Espindola   removeEmptyCommands();
6339546fffbSRafael Espindola }
6349546fffbSRafael Espindola 
63515c57951SRafael Espindola // When placing orphan sections, we want to place them after symbol assignments
63615c57951SRafael Espindola // so that an orphan after
63715c57951SRafael Espindola //   begin_foo = .;
63815c57951SRafael Espindola //   foo : { *(foo) }
63915c57951SRafael Espindola //   end_foo = .;
64015c57951SRafael Espindola // doesn't break the intended meaning of the begin/end symbols.
64115c57951SRafael Espindola // We don't want to go over sections since Writer<ELFT>::sortSections is the
64215c57951SRafael Espindola // one in charge of deciding the order of the sections.
64315c57951SRafael Espindola // We don't want to go over alignments, since doing so in
64415c57951SRafael Espindola //  rx_sec : { *(rx_sec) }
64515c57951SRafael Espindola //  . = ALIGN(0x1000);
64615c57951SRafael Espindola //  /* The RW PT_LOAD starts here*/
64715c57951SRafael Espindola //  rw_sec : { *(rw_sec) }
64815c57951SRafael Espindola // would mean that the RW PT_LOAD would become unaligned.
6495fcc99c2SRafael Espindola static bool shouldSkip(const BaseCommand &Cmd) {
65015c57951SRafael Espindola   if (isa<OutputSectionCommand>(Cmd))
65115c57951SRafael Espindola     return false;
65215c57951SRafael Espindola   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
65315c57951SRafael Espindola   if (!Assign)
65415c57951SRafael Espindola     return true;
6555fcc99c2SRafael Espindola   return Assign->Name != ".";
65615c57951SRafael Espindola }
65715c57951SRafael Espindola 
658337f903cSRafael Espindola // Orphan sections are sections present in the input files which are not
659337f903cSRafael Espindola // explicitly placed into the output file by the linker script. This just
660337f903cSRafael Espindola // places them in the order already decided in OutputSections.
66193c64025SGeorge Rimar template <class ELFT> void LinkerScript<ELFT>::placeOrphanSections() {
662aab6d5c5SRafael Espindola   // The OutputSections are already in the correct order.
663aab6d5c5SRafael Espindola   // This loops creates or moves commands as needed so that they are in the
664aab6d5c5SRafael Espindola   // correct order.
665aab6d5c5SRafael Espindola   int CmdIndex = 0;
6665fcc99c2SRafael Espindola 
6675fcc99c2SRafael Espindola   // As a horrible special case, skip the first . assignment if it is before any
6685fcc99c2SRafael Espindola   // section. We do this because it is common to set a load address by starting
6695fcc99c2SRafael Espindola   // the script with ". = 0xabcd" and the expectation is that every section is
6705fcc99c2SRafael Espindola   // after that.
6715fcc99c2SRafael Espindola   auto FirstSectionOrDotAssignment =
6725fcc99c2SRafael Espindola       std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
6735fcc99c2SRafael Espindola                    [](const std::unique_ptr<BaseCommand> &Cmd) {
6745fcc99c2SRafael Espindola                      if (isa<OutputSectionCommand>(*Cmd))
6755fcc99c2SRafael Espindola                        return true;
6765fcc99c2SRafael Espindola                      const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
6775fcc99c2SRafael Espindola                      if (!Assign)
6785fcc99c2SRafael Espindola                        return false;
6795fcc99c2SRafael Espindola                      return Assign->Name == ".";
6805fcc99c2SRafael Espindola                    });
6815fcc99c2SRafael Espindola   if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
6825fcc99c2SRafael Espindola     CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
6835fcc99c2SRafael Espindola     if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
6845fcc99c2SRafael Espindola       ++CmdIndex;
6855fcc99c2SRafael Espindola   }
6865fcc99c2SRafael Espindola 
687e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
688652852c5SGeorge Rimar     StringRef Name = Sec->getName();
689aab6d5c5SRafael Espindola 
690aab6d5c5SRafael Espindola     // Find the last spot where we can insert a command and still get the
69115c57951SRafael Espindola     // correct result.
692aab6d5c5SRafael Espindola     auto CmdIter = Opt.Commands.begin() + CmdIndex;
693aab6d5c5SRafael Espindola     auto E = Opt.Commands.end();
6945fcc99c2SRafael Espindola     while (CmdIter != E && shouldSkip(**CmdIter)) {
695aab6d5c5SRafael Espindola       ++CmdIter;
696aab6d5c5SRafael Espindola       ++CmdIndex;
697aab6d5c5SRafael Espindola     }
698aab6d5c5SRafael Espindola 
699aab6d5c5SRafael Espindola     auto Pos =
700aab6d5c5SRafael Espindola         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
701aab6d5c5SRafael Espindola           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
702aab6d5c5SRafael Espindola           return Cmd && Cmd->Name == Name;
703aab6d5c5SRafael Espindola         });
704aab6d5c5SRafael Espindola     if (Pos == E) {
705aab6d5c5SRafael Espindola       Opt.Commands.insert(CmdIter,
706aab6d5c5SRafael Espindola                           llvm::make_unique<OutputSectionCommand>(Name));
707aab6d5c5SRafael Espindola       ++CmdIndex;
70815c57951SRafael Espindola       continue;
70915c57951SRafael Espindola     }
71015c57951SRafael Espindola 
71115c57951SRafael Espindola     // Continue from where we found it.
71215c57951SRafael Espindola     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
713652852c5SGeorge Rimar   }
714337f903cSRafael Espindola }
715337f903cSRafael Espindola 
716337f903cSRafael Espindola template <class ELFT>
71717cb7c0aSRafael Espindola void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
7187c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
719be607334SRafael Espindola   Dot = 0;
720652852c5SGeorge Rimar 
721076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
722076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
7238d083e6aSRui Ueyama       if (Cmd->Name == ".") {
7248d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
7258d083e6aSRui Ueyama       } else if (Cmd->Sym) {
726afaa9343SEugene Leviant         assignSectionSymbol<ELFT>(Cmd, Dot);
7278d083e6aSRui Ueyama       }
72805ef4cffSRui Ueyama       continue;
729652852c5SGeorge Rimar     }
730652852c5SGeorge Rimar 
731eefa758eSGeorge Rimar     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
732eefa758eSGeorge Rimar       Cmd->Expression(Dot);
733eefa758eSGeorge Rimar       continue;
734eefa758eSGeorge Rimar     }
735eefa758eSGeorge Rimar 
736076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
73758e5c4dcSGeorge Rimar     if (Cmd->AddrExpr)
73858e5c4dcSGeorge Rimar       Dot = Cmd->AddrExpr(Dot);
739d3190795SRafael Espindola     assignOffsets(Cmd);
740a14b13d8SGeorge Rimar   }
741467c4d55SEugene Leviant 
742aab6d5c5SRafael Espindola   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
743e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
74404a2e348SRafael Espindola     if (Sec->Flags & SHF_ALLOC)
745e08e78dfSRafael Espindola       MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
746aab6d5c5SRafael Espindola     else
74704a2e348SRafael Espindola       Sec->Addr = 0;
748aab6d5c5SRafael Espindola   }
749aab6d5c5SRafael Espindola 
7500d4b6d5cSRafael Espindola   uintX_t HeaderSize = getHeaderSize();
7511c57007eSRafael Espindola   // If the linker script doesn't have PHDRS, add ElfHeader and ProgramHeaders
7521c57007eSRafael Espindola   // now that we know we have space.
7535967c973SRafael Espindola   if (HeaderSize <= MinVA && !hasPhdrsCommands())
7545967c973SRafael Espindola     allocateHeaders<ELFT>(Phdrs, *OutputSections);
7551c57007eSRafael Espindola 
75664c32d6fSRafael Espindola   // ELF and Program headers need to be right before the first section in
757b91e7118SGeorge Rimar   // memory. Set their addresses accordingly.
75828d5f059SRafael Espindola   MinVA = alignDown(MinVA - HeaderSize, Config->MaxPageSize);
75904a2e348SRafael Espindola   Out<ELFT>::ElfHeader->Addr = MinVA;
76004a2e348SRafael Espindola   Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
761fb8978fcSDima Stepanov }
762652852c5SGeorge Rimar 
763464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
76417cb7c0aSRafael Espindola template <class ELFT> std::vector<PhdrEntry> LinkerScript<ELFT>::createPhdrs() {
76517cb7c0aSRafael Espindola   std::vector<PhdrEntry> Ret;
766bbe38602SEugene Leviant 
767464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
768464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
769bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
770edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
77117cb7c0aSRafael Espindola     PhdrEntry &Phdr = Ret.back();
772bbe38602SEugene Leviant 
773bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
774adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
775bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
776adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
77756b21c86SEugene Leviant 
77856b21c86SEugene Leviant     if (Cmd.LMAExpr) {
77917cb7c0aSRafael Espindola       Phdr.p_paddr = Cmd.LMAExpr(0);
78056b21c86SEugene Leviant       Phdr.HasLMA = true;
78156b21c86SEugene Leviant     }
782bbe38602SEugene Leviant   }
783bbe38602SEugene Leviant 
784464daadcSRui Ueyama   // Add output sections to program headers.
785e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
78604a2e348SRafael Espindola     if (!(Sec->Flags & SHF_ALLOC))
787bbe38602SEugene Leviant       break;
788bbe38602SEugene Leviant 
789bbe38602SEugene Leviant     // Assign headers specified by linker script
790f7a17448SRafael Espindola     for (size_t Id : getPhdrIndices(Sec->getName())) {
791edebbdf1SRui Ueyama       Ret[Id].add(Sec);
792865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
79317cb7c0aSRafael Espindola         Ret[Id].p_flags |= Sec->getPhdrFlags();
794bbe38602SEugene Leviant     }
795bbe38602SEugene Leviant   }
796edebbdf1SRui Ueyama   return Ret;
797bbe38602SEugene Leviant }
798bbe38602SEugene Leviant 
799f9bc3bd2SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
800f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
801f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
802f9bc3bd2SEugene Leviant   return !Opt.PhdrsCommands.empty() &&
803f9bc3bd2SEugene Leviant          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
804f9bc3bd2SEugene Leviant            return Cmd.Type == PT_INTERP;
805f9bc3bd2SEugene Leviant          }) == Opt.PhdrsCommands.end();
806f9bc3bd2SEugene Leviant }
807f9bc3bd2SEugene Leviant 
80893c64025SGeorge Rimar template <class ELFT> uint32_t LinkerScript<ELFT>::getFiller(StringRef Name) {
809f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
810f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
811f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
812f6c3ccefSGeorge Rimar         return Cmd->Filler;
81316068aebSRui Ueyama   return 0;
814e2ee72b5SGeorge Rimar }
815e2ee72b5SGeorge Rimar 
816e38cbab5SGeorge Rimar template <class ELFT>
817e38cbab5SGeorge Rimar static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
818e38cbab5SGeorge Rimar   const endianness E = ELFT::TargetEndianness;
819e38cbab5SGeorge Rimar 
820e38cbab5SGeorge Rimar   switch (Size) {
821e38cbab5SGeorge Rimar   case 1:
822e38cbab5SGeorge Rimar     *Buf = (uint8_t)Data;
823e38cbab5SGeorge Rimar     break;
824e38cbab5SGeorge Rimar   case 2:
825e38cbab5SGeorge Rimar     write16<E>(Buf, Data);
826e38cbab5SGeorge Rimar     break;
827e38cbab5SGeorge Rimar   case 4:
828e38cbab5SGeorge Rimar     write32<E>(Buf, Data);
829e38cbab5SGeorge Rimar     break;
830e38cbab5SGeorge Rimar   case 8:
831e38cbab5SGeorge Rimar     write64<E>(Buf, Data);
832e38cbab5SGeorge Rimar     break;
833e38cbab5SGeorge Rimar   default:
834e38cbab5SGeorge Rimar     llvm_unreachable("unsupported Size argument");
835e38cbab5SGeorge Rimar   }
836e38cbab5SGeorge Rimar }
837e38cbab5SGeorge Rimar 
838e38cbab5SGeorge Rimar template <class ELFT>
839e38cbab5SGeorge Rimar void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
840e38cbab5SGeorge Rimar   int I = getSectionIndex(Name);
841e38cbab5SGeorge Rimar   if (I == INT_MAX)
842e38cbab5SGeorge Rimar     return;
843e38cbab5SGeorge Rimar 
8446e68c5e5SRui Ueyama   auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
8456e68c5e5SRui Ueyama   for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
8466e68c5e5SRui Ueyama     if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
84795c7d8d2SMeador Inge       writeInt<ELFT>(Buf + Data->Offset, Data->Expression(0), Data->Size);
848e38cbab5SGeorge Rimar }
849e38cbab5SGeorge Rimar 
850b71d6f7aSEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
8518ceadb38SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
8528ceadb38SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
853b71d6f7aSEugene Leviant       if (Cmd->LMAExpr && Cmd->Name == Name)
854b71d6f7aSEugene Leviant         return true;
855b71d6f7aSEugene Leviant   return false;
8568ceadb38SGeorge Rimar }
8578ceadb38SGeorge Rimar 
858c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
859c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
860c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
861c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
862076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
8636e68c5e5SRui Ueyama   for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
8646e68c5e5SRui Ueyama     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
865076fe157SGeorge Rimar       if (Cmd->Name == Name)
866f510fa6bSRui Ueyama         return I;
867f510fa6bSRui Ueyama   return INT_MAX;
86871b26e94SGeorge Rimar }
86971b26e94SGeorge Rimar 
870bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
871bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
872bbe38602SEugene Leviant }
873bbe38602SEugene Leviant 
8749e69450eSGeorge Rimar template <class ELFT>
875ed30ce7aSEugene Leviant const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(const Twine &Loc,
876ed30ce7aSEugene Leviant                                                               StringRef Name) {
877afaa9343SEugene Leviant   static OutputSectionBase FakeSec("", 0, 0);
87896659df0SGeorge Rimar 
879e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections)
880b71d6f7aSEugene Leviant     if (Sec->getName() == Name)
881afaa9343SEugene Leviant       return Sec;
882ed30ce7aSEugene Leviant 
883ed30ce7aSEugene Leviant   error(Loc + ": undefined section " + Name);
884afaa9343SEugene Leviant   return &FakeSec;
88536fac7f0SEugene Leviant }
88636fac7f0SEugene Leviant 
887edf75e79SRui Ueyama // This function is essentially the same as getOutputSection(Name)->Size,
888edf75e79SRui Ueyama // but it won't print out an error message if a given section is not found.
889edf75e79SRui Ueyama //
890edf75e79SRui Ueyama // Linker script does not create an output section if its content is empty.
891edf75e79SRui Ueyama // We want to allow SIZEOF(.foo) where .foo is a section which happened to
892edf75e79SRui Ueyama // be empty. That is why this function is different from getOutputSection().
893edf75e79SRui Ueyama template <class ELFT>
894edf75e79SRui Ueyama uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
895edf75e79SRui Ueyama   for (OutputSectionBase *Sec : *OutputSections)
896edf75e79SRui Ueyama     if (Sec->getName() == Name)
897edf75e79SRui Ueyama       return Sec->Size;
898edf75e79SRui Ueyama   return 0;
899edf75e79SRui Ueyama }
900edf75e79SRui Ueyama 
901884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
9020d4b6d5cSRafael Espindola   return elf::getHeaderSize<ELFT>();
903e32a3598SGeorge Rimar }
904e32a3598SGeorge Rimar 
905884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
906884e786dSGeorge Rimar   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
907884e786dSGeorge Rimar     return B->getVA<ELFT>();
908884e786dSGeorge Rimar   error("symbol not found: " + S);
909884e786dSGeorge Rimar   return 0;
910884e786dSGeorge Rimar }
911884e786dSGeorge Rimar 
912f34f45fdSGeorge Rimar template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
913f34f45fdSGeorge Rimar   return Symtab<ELFT>::X->find(S) != nullptr;
914f34f45fdSGeorge Rimar }
915f34f45fdSGeorge Rimar 
9162f831dcaSRafael Espindola template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
9172f831dcaSRafael Espindola   SymbolBody *Sym = Symtab<ELFT>::X->find(S);
9182f831dcaSRafael Espindola   auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
9192f831dcaSRafael Espindola   return DR && !DR->Section;
9202f831dcaSRafael Espindola }
9212f831dcaSRafael Espindola 
922afaa9343SEugene Leviant // Gets section symbol belongs to. Symbol "." doesn't belong to any
923afaa9343SEugene Leviant // specific section but isn't absolute at the same time, so we try
924afaa9343SEugene Leviant // to find suitable section for it as well.
925afaa9343SEugene Leviant template <class ELFT>
926afaa9343SEugene Leviant const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
927afaa9343SEugene Leviant   SymbolBody *Sym = Symtab<ELFT>::X->find(S);
928afaa9343SEugene Leviant   if (!Sym) {
929afaa9343SEugene Leviant     if (OutputSections->empty())
930afaa9343SEugene Leviant       return nullptr;
931afaa9343SEugene Leviant     return CurOutSec ? CurOutSec : (*OutputSections)[0];
932afaa9343SEugene Leviant   }
933afaa9343SEugene Leviant 
934afaa9343SEugene Leviant   if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
935afaa9343SEugene Leviant     return DR->Section ? DR->Section->OutSec : nullptr;
936afaa9343SEugene Leviant   if (auto *DS = dyn_cast_or_null<DefinedSynthetic<ELFT>>(Sym))
937afaa9343SEugene Leviant     return DS->Section;
938afaa9343SEugene Leviant 
939afaa9343SEugene Leviant   return nullptr;
940afaa9343SEugene Leviant }
941afaa9343SEugene Leviant 
942bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
943bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
944bbe38602SEugene Leviant // PHDRS {} script block.
945bbe38602SEugene Leviant template <class ELFT>
946edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
947076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
948076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
949edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
95031d842f5SGeorge Rimar       continue;
95131d842f5SGeorge Rimar 
95229c5a2a9SRui Ueyama     std::vector<size_t> Ret;
95329c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
9542a942c4bSEugene Leviant       Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
95529c5a2a9SRui Ueyama     return Ret;
956bbe38602SEugene Leviant   }
95731d842f5SGeorge Rimar   return {};
95831d842f5SGeorge Rimar }
959bbe38602SEugene Leviant 
96029c5a2a9SRui Ueyama template <class ELFT>
9612a942c4bSEugene Leviant size_t LinkerScript<ELFT>::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
96229c5a2a9SRui Ueyama   size_t I = 0;
96329c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
96429c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
96529c5a2a9SRui Ueyama       return I;
96629c5a2a9SRui Ueyama     ++I;
96729c5a2a9SRui Ueyama   }
9682a942c4bSEugene Leviant   error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
96929c5a2a9SRui Ueyama   return 0;
97029c5a2a9SRui Ueyama }
97129c5a2a9SRui Ueyama 
97203ff0166SEugene Leviant class elf::ScriptParser final : public ScriptParserBase {
973c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
974c3794e58SGeorge Rimar 
975f7c5fbb1SRui Ueyama public:
97622375f24SRui Ueyama   ScriptParser(MemoryBufferRef MB)
97722375f24SRui Ueyama       : ScriptParserBase(MB),
97822375f24SRui Ueyama         IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
979f23b2320SGeorge Rimar 
98020b6598cSGeorge Rimar   void readLinkerScript();
98120b6598cSGeorge Rimar   void readVersionScript();
982d0ebd84cSRafael Espindola   void readDynamicList();
983f7c5fbb1SRui Ueyama 
984f7c5fbb1SRui Ueyama private:
98552a1509eSRui Ueyama   void addFile(StringRef Path);
98652a1509eSRui Ueyama 
987f7c5fbb1SRui Ueyama   void readAsNeeded();
98890c5099eSDenis Protivensky   void readEntry();
98983f406cfSGeorge Rimar   void readExtern();
990f7c5fbb1SRui Ueyama   void readGroup();
99131aa1f83SRui Ueyama   void readInclude();
992ee59282bSRui Ueyama   void readOutput();
9939159ce93SDavide Italiano   void readOutputArch();
994f7c5fbb1SRui Ueyama   void readOutputFormat();
995bbe38602SEugene Leviant   void readPhdrs();
99668a39a65SDavide Italiano   void readSearchDir();
9978e3b38abSDenis Protivensky   void readSections();
99895769b4aSRui Ueyama   void readVersion();
99995769b4aSRui Ueyama   void readVersionScriptCommand();
10008e3b38abSDenis Protivensky 
1001113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
1002e38cbab5SGeorge Rimar   BytesDataCommand *readBytesDataCommand(StringRef Tok);
100316068aebSRui Ueyama   uint32_t readFill();
100410416564SRui Ueyama   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
100516068aebSRui Ueyama   uint32_t readOutputSectionFiller(StringRef Tok);
1006bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
1007a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionDescription(StringRef Tok);
1008db688454SEugene Leviant   StringMatcher readFilePatterns();
100907171f21SGeorge Rimar   std::vector<SectionPattern> readInputSectionsList();
1010a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
1011bbe38602SEugene Leviant   unsigned readPhdrType();
1012be394db3SGeorge Rimar   SortSectionPolicy readSortKind();
1013a35e39caSPetr Hosek   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
1014c96da110SRafael Espindola   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
101503fc010eSGeorge Rimar   void readSort();
1016eefa758eSGeorge Rimar   Expr readAssert();
1017708019c4SRui Ueyama 
1018708019c4SRui Ueyama   Expr readExpr();
1019708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
1020b71d6f7aSEugene Leviant   StringRef readParenLiteral();
1021708019c4SRui Ueyama   Expr readPrimary();
1022708019c4SRui Ueyama   Expr readTernary(Expr Cond);
10236ad7dfccSRui Ueyama   Expr readParenExpr();
1024f7c5fbb1SRui Ueyama 
102520b6598cSGeorge Rimar   // For parsing version script.
102612450b20SRui Ueyama   std::vector<SymbolVersion> readVersionExtern();
102712450b20SRui Ueyama   void readAnonymousDeclaration();
102895769b4aSRui Ueyama   void readVersionDeclaration(StringRef VerStr);
102912450b20SRui Ueyama   std::vector<SymbolVersion> readSymbols();
103020b6598cSGeorge Rimar 
103107320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
103216b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
1033f7c5fbb1SRui Ueyama };
1034f7c5fbb1SRui Ueyama 
1035d0ebd84cSRafael Espindola void ScriptParser::readDynamicList() {
1036d0ebd84cSRafael Espindola   expect("{");
1037d0ebd84cSRafael Espindola   readAnonymousDeclaration();
1038d0ebd84cSRafael Espindola   if (!atEOF())
1039d0ebd84cSRafael Espindola     setError("EOF expected, but got " + next());
1040d0ebd84cSRafael Espindola }
1041d0ebd84cSRafael Espindola 
104220b6598cSGeorge Rimar void ScriptParser::readVersionScript() {
104395769b4aSRui Ueyama   readVersionScriptCommand();
104420b6598cSGeorge Rimar   if (!atEOF())
104595769b4aSRui Ueyama     setError("EOF expected, but got " + next());
104695769b4aSRui Ueyama }
104795769b4aSRui Ueyama 
104895769b4aSRui Ueyama void ScriptParser::readVersionScriptCommand() {
104983043f23SRui Ueyama   if (consume("{")) {
105012450b20SRui Ueyama     readAnonymousDeclaration();
105120b6598cSGeorge Rimar     return;
105220b6598cSGeorge Rimar   }
105320b6598cSGeorge Rimar 
105495769b4aSRui Ueyama   while (!atEOF() && !Error && peek() != "}") {
105520b6598cSGeorge Rimar     StringRef VerStr = next();
105620b6598cSGeorge Rimar     if (VerStr == "{") {
105795769b4aSRui Ueyama       setError("anonymous version definition is used in "
105895769b4aSRui Ueyama                "combination with other version definitions");
105920b6598cSGeorge Rimar       return;
106020b6598cSGeorge Rimar     }
106120b6598cSGeorge Rimar     expect("{");
106295769b4aSRui Ueyama     readVersionDeclaration(VerStr);
106320b6598cSGeorge Rimar   }
106420b6598cSGeorge Rimar }
106520b6598cSGeorge Rimar 
106695769b4aSRui Ueyama void ScriptParser::readVersion() {
106795769b4aSRui Ueyama   expect("{");
106895769b4aSRui Ueyama   readVersionScriptCommand();
106995769b4aSRui Ueyama   expect("}");
107095769b4aSRui Ueyama }
107195769b4aSRui Ueyama 
107220b6598cSGeorge Rimar void ScriptParser::readLinkerScript() {
1073f7c5fbb1SRui Ueyama   while (!atEOF()) {
1074f7c5fbb1SRui Ueyama     StringRef Tok = next();
1075a27eeccaSRui Ueyama     if (Tok == ";")
1076a27eeccaSRui Ueyama       continue;
1077a27eeccaSRui Ueyama 
107820d03194SEugene Leviant     if (Tok == "ASSERT") {
107920d03194SEugene Leviant       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
108020d03194SEugene Leviant     } else if (Tok == "ENTRY") {
1081a27eeccaSRui Ueyama       readEntry();
1082a27eeccaSRui Ueyama     } else if (Tok == "EXTERN") {
1083a27eeccaSRui Ueyama       readExtern();
1084a27eeccaSRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
1085a27eeccaSRui Ueyama       readGroup();
1086a27eeccaSRui Ueyama     } else if (Tok == "INCLUDE") {
1087a27eeccaSRui Ueyama       readInclude();
1088a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT") {
1089a27eeccaSRui Ueyama       readOutput();
1090a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
1091a27eeccaSRui Ueyama       readOutputArch();
1092a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
1093a27eeccaSRui Ueyama       readOutputFormat();
1094a27eeccaSRui Ueyama     } else if (Tok == "PHDRS") {
1095a27eeccaSRui Ueyama       readPhdrs();
1096a27eeccaSRui Ueyama     } else if (Tok == "SEARCH_DIR") {
1097a27eeccaSRui Ueyama       readSearchDir();
1098a27eeccaSRui Ueyama     } else if (Tok == "SECTIONS") {
1099a27eeccaSRui Ueyama       readSections();
1100a27eeccaSRui Ueyama     } else if (Tok == "VERSION") {
1101a27eeccaSRui Ueyama       readVersion();
1102c96da110SRafael Espindola     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
11030df80befSPetr Hosek       Opt.Commands.emplace_back(Cmd);
1104e5d3ca50SPetr Hosek     } else {
11055761042dSGeorge Rimar       setError("unknown directive: " + Tok);
1106f7c5fbb1SRui Ueyama     }
1107f7c5fbb1SRui Ueyama   }
1108e5d3ca50SPetr Hosek }
1109f7c5fbb1SRui Ueyama 
1110717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
111116b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
11125af1687fSJustin Bogner     SmallString<128> PathData;
11135af1687fSJustin Bogner     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
111416b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
11155af1687fSJustin Bogner       Driver->addFile(Saver.save(Path));
111616b0cc9eSSimon Atanasyan       return;
111716b0cc9eSSimon Atanasyan     }
111816b0cc9eSSimon Atanasyan   }
111916b0cc9eSSimon Atanasyan 
1120f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
112152a1509eSRui Ueyama     Driver->addFile(S);
112252a1509eSRui Ueyama   } else if (S.startswith("=")) {
112352a1509eSRui Ueyama     if (Config->Sysroot.empty())
112452a1509eSRui Ueyama       Driver->addFile(S.substr(1));
112552a1509eSRui Ueyama     else
112652a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
112752a1509eSRui Ueyama   } else if (S.startswith("-l")) {
112821eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
1129a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
1130a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
113152a1509eSRui Ueyama   } else {
1132061f9286SRui Ueyama     if (Optional<std::string> Path = findFromSearchPaths(S))
1133061f9286SRui Ueyama       Driver->addFile(Saver.save(*Path));
1134025d59b1SRui Ueyama     else
1135061f9286SRui Ueyama       setError("unable to find " + S);
113652a1509eSRui Ueyama   }
113752a1509eSRui Ueyama }
113852a1509eSRui Ueyama 
1139717677afSRui Ueyama void ScriptParser::readAsNeeded() {
1140f7c5fbb1SRui Ueyama   expect("(");
114135da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
114235da9b6eSRui Ueyama   Config->AsNeeded = true;
114383043f23SRui Ueyama   while (!Error && !consume(")"))
1144cd574a5eSGeorge Rimar     addFile(unquote(next()));
114535da9b6eSRui Ueyama   Config->AsNeeded = Orig;
1146f7c5fbb1SRui Ueyama }
1147f7c5fbb1SRui Ueyama 
1148717677afSRui Ueyama void ScriptParser::readEntry() {
114990c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
115090c5099eSDenis Protivensky   expect("(");
115190c5099eSDenis Protivensky   StringRef Tok = next();
115290c5099eSDenis Protivensky   if (Config->Entry.empty())
115390c5099eSDenis Protivensky     Config->Entry = Tok;
115490c5099eSDenis Protivensky   expect(")");
115590c5099eSDenis Protivensky }
115690c5099eSDenis Protivensky 
1157717677afSRui Ueyama void ScriptParser::readExtern() {
115883f406cfSGeorge Rimar   expect("(");
115983043f23SRui Ueyama   while (!Error && !consume(")"))
1160a2acc931SRui Ueyama     Config->Undefined.push_back(next());
116183f406cfSGeorge Rimar }
116283f406cfSGeorge Rimar 
1163717677afSRui Ueyama void ScriptParser::readGroup() {
1164f7c5fbb1SRui Ueyama   expect("(");
116583043f23SRui Ueyama   while (!Error && !consume(")")) {
1166f7c5fbb1SRui Ueyama     StringRef Tok = next();
1167a2acc931SRui Ueyama     if (Tok == "AS_NEEDED")
1168f7c5fbb1SRui Ueyama       readAsNeeded();
1169a2acc931SRui Ueyama     else
1170cd574a5eSGeorge Rimar       addFile(unquote(Tok));
1171f7c5fbb1SRui Ueyama   }
1172f7c5fbb1SRui Ueyama }
1173f7c5fbb1SRui Ueyama 
1174717677afSRui Ueyama void ScriptParser::readInclude() {
117531aa1f83SRui Ueyama   StringRef Tok = next();
1176cd574a5eSGeorge Rimar   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
1177025d59b1SRui Ueyama   if (!MBOrErr) {
11785761042dSGeorge Rimar     setError("cannot open " + Tok);
1179025d59b1SRui Ueyama     return;
1180025d59b1SRui Ueyama   }
118131aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
1182*4fb6e79cSGeorge Rimar   tokenize({Saver.save(MB->getBuffer()), unquote(Tok)});
118331aa1f83SRui Ueyama }
118431aa1f83SRui Ueyama 
1185717677afSRui Ueyama void ScriptParser::readOutput() {
1186ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
1187ee59282bSRui Ueyama   expect("(");
1188ee59282bSRui Ueyama   StringRef Tok = next();
1189ee59282bSRui Ueyama   if (Config->OutputFile.empty())
1190cd574a5eSGeorge Rimar     Config->OutputFile = unquote(Tok);
1191ee59282bSRui Ueyama   expect(")");
1192ee59282bSRui Ueyama }
1193ee59282bSRui Ueyama 
1194717677afSRui Ueyama void ScriptParser::readOutputArch() {
11959159ce93SDavide Italiano   // Error checking only for now.
11969159ce93SDavide Italiano   expect("(");
11975424e7c7SJustin Bogner   skip();
11989159ce93SDavide Italiano   expect(")");
11999159ce93SDavide Italiano }
12009159ce93SDavide Italiano 
1201717677afSRui Ueyama void ScriptParser::readOutputFormat() {
1202f7c5fbb1SRui Ueyama   // Error checking only for now.
1203f7c5fbb1SRui Ueyama   expect("(");
12045424e7c7SJustin Bogner   skip();
12056836c618SDavide Italiano   StringRef Tok = next();
12066836c618SDavide Italiano   if (Tok == ")")
12076836c618SDavide Italiano     return;
1208025d59b1SRui Ueyama   if (Tok != ",") {
12095761042dSGeorge Rimar     setError("unexpected token: " + Tok);
1210025d59b1SRui Ueyama     return;
1211025d59b1SRui Ueyama   }
12125424e7c7SJustin Bogner   skip();
12136836c618SDavide Italiano   expect(",");
12145424e7c7SJustin Bogner   skip();
1215f7c5fbb1SRui Ueyama   expect(")");
1216f7c5fbb1SRui Ueyama }
1217f7c5fbb1SRui Ueyama 
1218bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
1219bbe38602SEugene Leviant   expect("{");
122083043f23SRui Ueyama   while (!Error && !consume("}")) {
1221bbe38602SEugene Leviant     StringRef Tok = next();
122256b21c86SEugene Leviant     Opt.PhdrsCommands.push_back(
122356b21c86SEugene Leviant         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1224bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1225bbe38602SEugene Leviant 
1226bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
1227bbe38602SEugene Leviant     do {
1228bbe38602SEugene Leviant       Tok = next();
1229bbe38602SEugene Leviant       if (Tok == ";")
1230bbe38602SEugene Leviant         break;
1231bbe38602SEugene Leviant       if (Tok == "FILEHDR")
1232bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
1233bbe38602SEugene Leviant       else if (Tok == "PHDRS")
1234bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
123556b21c86SEugene Leviant       else if (Tok == "AT")
123656b21c86SEugene Leviant         PhdrCmd.LMAExpr = readParenExpr();
1237865bf863SEugene Leviant       else if (Tok == "FLAGS") {
1238865bf863SEugene Leviant         expect("(");
1239eb685cd7SRafael Espindola         // Passing 0 for the value of dot is a bit of a hack. It means that
1240eb685cd7SRafael Espindola         // we accept expressions like ".|1".
1241eb685cd7SRafael Espindola         PhdrCmd.Flags = readExpr()(0);
1242865bf863SEugene Leviant         expect(")");
1243865bf863SEugene Leviant       } else
1244bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
1245bbe38602SEugene Leviant     } while (!Error);
1246bbe38602SEugene Leviant   }
1247bbe38602SEugene Leviant }
1248bbe38602SEugene Leviant 
1249717677afSRui Ueyama void ScriptParser::readSearchDir() {
125068a39a65SDavide Italiano   expect("(");
125186c5fb82SRui Ueyama   StringRef Tok = next();
12526c7ad13fSRui Ueyama   if (!Config->Nostdlib)
1253cd574a5eSGeorge Rimar     Config->SearchPaths.push_back(unquote(Tok));
125468a39a65SDavide Italiano   expect(")");
125568a39a65SDavide Italiano }
125668a39a65SDavide Italiano 
1257717677afSRui Ueyama void ScriptParser::readSections() {
1258e05336ffSEugene Leviant   Opt.HasSections = true;
125918a30962SGeorge Rimar   // -no-rosegment is used to avoid placing read only non-executable sections in
126018a30962SGeorge Rimar   // their own segment. We do the same if SECTIONS command is present in linker
126118a30962SGeorge Rimar   // script. See comment for computeFlags().
126218a30962SGeorge Rimar   Config->SingleRoRx = true;
126318a30962SGeorge Rimar 
12648e3b38abSDenis Protivensky   expect("{");
126583043f23SRui Ueyama   while (!Error && !consume("}")) {
1266113cdec9SRui Ueyama     StringRef Tok = next();
1267c96da110SRafael Espindola     BaseCommand *Cmd = readProvideOrAssignment(Tok);
1268ceabe80eSEugene Leviant     if (!Cmd) {
1269ceabe80eSEugene Leviant       if (Tok == "ASSERT")
1270eefa758eSGeorge Rimar         Cmd = new AssertCommand(readAssert());
1271ceabe80eSEugene Leviant       else
127210416564SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
12738e3b38abSDenis Protivensky     }
127410416564SRui Ueyama     Opt.Commands.emplace_back(Cmd);
1275652852c5SGeorge Rimar   }
1276708019c4SRui Ueyama }
12778e3b38abSDenis Protivensky 
1278708019c4SRui Ueyama static int precedence(StringRef Op) {
1279708019c4SRui Ueyama   return StringSwitch<int>(Op)
12800120e3f2SRui Ueyama       .Cases("*", "/", 5)
12810120e3f2SRui Ueyama       .Cases("+", "-", 4)
12820120e3f2SRui Ueyama       .Cases("<<", ">>", 3)
12839c4ac5f2SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
12840120e3f2SRui Ueyama       .Cases("&", "|", 1)
1285708019c4SRui Ueyama       .Default(-1);
1286708019c4SRui Ueyama }
1287708019c4SRui Ueyama 
1288db688454SEugene Leviant StringMatcher ScriptParser::readFilePatterns() {
128910416564SRui Ueyama   std::vector<StringRef> V;
129083043f23SRui Ueyama   while (!Error && !consume(")"))
129110416564SRui Ueyama     V.push_back(next());
1292f91282e1SRui Ueyama   return StringMatcher(V);
12930702c4e8SGeorge Rimar }
12940702c4e8SGeorge Rimar 
1295be394db3SGeorge Rimar SortSectionPolicy ScriptParser::readSortKind() {
129683043f23SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
1297be394db3SGeorge Rimar     return SortSectionPolicy::Name;
129883043f23SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
1299be394db3SGeorge Rimar     return SortSectionPolicy::Alignment;
130083043f23SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
1301be394db3SGeorge Rimar     return SortSectionPolicy::Priority;
130283043f23SRui Ueyama   if (consume("SORT_NONE"))
1303be394db3SGeorge Rimar     return SortSectionPolicy::None;
1304b2a0abdfSRui Ueyama   return SortSectionPolicy::Default;
1305be394db3SGeorge Rimar }
1306be394db3SGeorge Rimar 
1307395281cfSGeorge Rimar // Method reads a list of sequence of excluded files and section globs given in
1308395281cfSGeorge Rimar // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1309395281cfSGeorge Rimar // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1310af03be19SGeorge Rimar // The semantics of that is next:
1311af03be19SGeorge Rimar // * Include .foo.1 from every file.
1312af03be19SGeorge Rimar // * Include .foo.2 from every file but a.o
1313af03be19SGeorge Rimar // * Include .foo.3 from every file but b.o
131407171f21SGeorge Rimar std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
131507171f21SGeorge Rimar   std::vector<SectionPattern> Ret;
1316601e9898SGeorge Rimar   while (!Error && peek() != ")") {
1317f91282e1SRui Ueyama     StringMatcher ExcludeFilePat;
131883043f23SRui Ueyama     if (consume("EXCLUDE_FILE")) {
1319395281cfSGeorge Rimar       expect("(");
1320f91282e1SRui Ueyama       ExcludeFilePat = readFilePatterns();
1321395281cfSGeorge Rimar     }
1322395281cfSGeorge Rimar 
1323601e9898SGeorge Rimar     std::vector<StringRef> V;
1324601e9898SGeorge Rimar     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1325395281cfSGeorge Rimar       V.push_back(next());
1326601e9898SGeorge Rimar 
1327601e9898SGeorge Rimar     if (!V.empty())
1328f91282e1SRui Ueyama       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
1329601e9898SGeorge Rimar     else
1330601e9898SGeorge Rimar       setError("section pattern is expected");
1331395281cfSGeorge Rimar   }
133207171f21SGeorge Rimar   return Ret;
1333395281cfSGeorge Rimar }
1334395281cfSGeorge Rimar 
1335f8f6f1e7SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a
1336f8f6f1e7SRui Ueyama // list of glob patterns for input sections. The grammar is as follows.
1337f8f6f1e7SRui Ueyama //
1338f8f6f1e7SRui Ueyama // <patterns> ::= <section-list>
1339f8f6f1e7SRui Ueyama //              | <sort> "(" <section-list> ")"
1340f8f6f1e7SRui Ueyama //              | <sort> "(" <sort> "(" <section-list> ")" ")"
1341f8f6f1e7SRui Ueyama //
1342f8f6f1e7SRui Ueyama // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1343f8f6f1e7SRui Ueyama //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1344f8f6f1e7SRui Ueyama //
1345f8f6f1e7SRui Ueyama // <section-list> is parsed by readInputSectionsList().
1346a2496cbeSGeorge Rimar InputSectionDescription *
1347a2496cbeSGeorge Rimar ScriptParser::readInputSectionRules(StringRef FilePattern) {
1348c91930a1SGeorge Rimar   auto *Cmd = new InputSectionDescription(FilePattern);
13490ed42b0cSDavide Italiano   expect("(");
1350f373dd76SRui Ueyama   while (!Error && !consume(")")) {
135107171f21SGeorge Rimar     SortSectionPolicy Outer = readSortKind();
135207171f21SGeorge Rimar     SortSectionPolicy Inner = SortSectionPolicy::Default;
135307171f21SGeorge Rimar     std::vector<SectionPattern> V;
135407171f21SGeorge Rimar     if (Outer != SortSectionPolicy::Default) {
13550702c4e8SGeorge Rimar       expect("(");
135607171f21SGeorge Rimar       Inner = readSortKind();
135707171f21SGeorge Rimar       if (Inner != SortSectionPolicy::Default) {
1358350ece4eSGeorge Rimar         expect("(");
135907171f21SGeorge Rimar         V = readInputSectionsList();
13600702c4e8SGeorge Rimar         expect(")");
1361350ece4eSGeorge Rimar       } else {
136207171f21SGeorge Rimar         V = readInputSectionsList();
1363350ece4eSGeorge Rimar       }
1364350ece4eSGeorge Rimar       expect(")");
136507171f21SGeorge Rimar     } else {
136607171f21SGeorge Rimar       V = readInputSectionsList();
13670659800eSGeorge Rimar     }
13680702c4e8SGeorge Rimar 
136907171f21SGeorge Rimar     for (SectionPattern &Pat : V) {
137007171f21SGeorge Rimar       Pat.SortInner = Inner;
137107171f21SGeorge Rimar       Pat.SortOuter = Outer;
137207171f21SGeorge Rimar     }
137307171f21SGeorge Rimar 
137407171f21SGeorge Rimar     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
137507171f21SGeorge Rimar   }
137610416564SRui Ueyama   return Cmd;
13770659800eSGeorge Rimar }
13780659800eSGeorge Rimar 
1379a2496cbeSGeorge Rimar InputSectionDescription *
1380a2496cbeSGeorge Rimar ScriptParser::readInputSectionDescription(StringRef Tok) {
13810659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
13820659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1383a2496cbeSGeorge Rimar   if (Tok == "KEEP") {
1384e7282797SDavide Italiano     expect("(");
1385a2496cbeSGeorge Rimar     StringRef FilePattern = next();
1386a2496cbeSGeorge Rimar     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
13870ed42b0cSDavide Italiano     expect(")");
1388cf43f179SEugene Leviant     Opt.KeptSections.push_back(Cmd);
138910416564SRui Ueyama     return Cmd;
139010416564SRui Ueyama   }
1391a2496cbeSGeorge Rimar   return readInputSectionRules(Tok);
13920659800eSGeorge Rimar }
13930659800eSGeorge Rimar 
139403fc010eSGeorge Rimar void ScriptParser::readSort() {
139503fc010eSGeorge Rimar   expect("(");
139603fc010eSGeorge Rimar   expect("CONSTRUCTORS");
139703fc010eSGeorge Rimar   expect(")");
139803fc010eSGeorge Rimar }
139903fc010eSGeorge Rimar 
1400eefa758eSGeorge Rimar Expr ScriptParser::readAssert() {
1401eefa758eSGeorge Rimar   expect("(");
1402eefa758eSGeorge Rimar   Expr E = readExpr();
1403eefa758eSGeorge Rimar   expect(",");
1404cd574a5eSGeorge Rimar   StringRef Msg = unquote(next());
1405eefa758eSGeorge Rimar   expect(")");
1406eefa758eSGeorge Rimar   return [=](uint64_t Dot) {
1407eefa758eSGeorge Rimar     uint64_t V = E(Dot);
1408eefa758eSGeorge Rimar     if (!V)
1409eefa758eSGeorge Rimar       error(Msg);
1410eefa758eSGeorge Rimar     return V;
1411eefa758eSGeorge Rimar   };
1412eefa758eSGeorge Rimar }
1413eefa758eSGeorge Rimar 
141425150e8bSRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
141525150e8bSRui Ueyama // alias for =fillexp section attribute, which is different from
141625150e8bSRui Ueyama // what GNU linkers do.
141725150e8bSRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
141816068aebSRui Ueyama uint32_t ScriptParser::readFill() {
1419ff1f29e0SGeorge Rimar   expect("(");
142016068aebSRui Ueyama   uint32_t V = readOutputSectionFiller(next());
1421ff1f29e0SGeorge Rimar   expect(")");
1422ff1f29e0SGeorge Rimar   expect(";");
1423ff1f29e0SGeorge Rimar   return V;
1424ff1f29e0SGeorge Rimar }
1425ff1f29e0SGeorge Rimar 
142610416564SRui Ueyama OutputSectionCommand *
142710416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1428076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
14292a942c4bSEugene Leviant   Cmd->Location = getCurrentLocation();
143058e5c4dcSGeorge Rimar 
143158e5c4dcSGeorge Rimar   // Read an address expression.
143258e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
143358e5c4dcSGeorge Rimar   if (peek() != ":")
143458e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
143558e5c4dcSGeorge Rimar 
14368e3b38abSDenis Protivensky   expect(":");
1437246f681eSDavide Italiano 
143883043f23SRui Ueyama   if (consume("AT"))
1439b71d6f7aSEugene Leviant     Cmd->LMAExpr = readParenExpr();
144083043f23SRui Ueyama   if (consume("ALIGN"))
14416ad7dfccSRui Ueyama     Cmd->AlignExpr = readParenExpr();
144283043f23SRui Ueyama   if (consume("SUBALIGN"))
1443db24d9c3SGeorge Rimar     Cmd->SubalignExpr = readParenExpr();
1444630c6179SGeorge Rimar 
1445246f681eSDavide Italiano   // Parse constraints.
144683043f23SRui Ueyama   if (consume("ONLY_IF_RO"))
1447efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
144883043f23SRui Ueyama   if (consume("ONLY_IF_RW"))
1449efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
14508e3b38abSDenis Protivensky   expect("{");
14518ec77e64SRui Ueyama 
145283043f23SRui Ueyama   while (!Error && !consume("}")) {
1453ceabe80eSEugene Leviant     StringRef Tok = next();
1454b2d99d6aSMeador Inge     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
1455ceabe80eSEugene Leviant       Cmd->Commands.emplace_back(Assignment);
1456b2d99d6aSMeador Inge     } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
1457e38cbab5SGeorge Rimar       Cmd->Commands.emplace_back(Data);
1458b2d99d6aSMeador Inge     } else if (Tok == "ASSERT") {
1459b2d99d6aSMeador Inge       Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1460b2d99d6aSMeador Inge       expect(";");
1461b2d99d6aSMeador Inge     } else if (Tok == "FILL") {
1462ff1f29e0SGeorge Rimar       Cmd->Filler = readFill();
1463b2d99d6aSMeador Inge     } else if (Tok == "SORT") {
146403fc010eSGeorge Rimar       readSort();
1465b2d99d6aSMeador Inge     } else if (peek() == "(") {
1466a2496cbeSGeorge Rimar       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1467b2d99d6aSMeador Inge     } else {
1468ceabe80eSEugene Leviant       setError("unknown command " + Tok);
14698e3b38abSDenis Protivensky     }
1470b2d99d6aSMeador Inge   }
1471076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
14724ebc5620SGeorge Rimar 
147383043f23SRui Ueyama   if (consume("="))
14744ebc5620SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next());
14754ebc5620SGeorge Rimar   else if (peek().startswith("="))
1476ff1f29e0SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next().drop_front());
14774ebc5620SGeorge Rimar 
147810416564SRui Ueyama   return Cmd;
1479f71caa2bSRui Ueyama }
14808ec77e64SRui Ueyama 
14812c8f1f04SRui Ueyama // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
14822c8f1f04SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
14832c8f1f04SRui Ueyama //
14842c8f1f04SRui Ueyama // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
14852c8f1f04SRui Ueyama // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
14862c8f1f04SRui Ueyama // as 32-bit big-endian values. We will do the same as ld.gold does
14872c8f1f04SRui Ueyama // because it's simpler than what ld.bfd does.
148816068aebSRui Ueyama uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
1489965827d6SRui Ueyama   uint32_t V;
149016068aebSRui Ueyama   if (!Tok.getAsInteger(0, V))
149116068aebSRui Ueyama     return V;
1492965827d6SRui Ueyama   setError("invalid filler expression: " + Tok);
149316068aebSRui Ueyama   return 0;
14948e3b38abSDenis Protivensky }
14958e3b38abSDenis Protivensky 
1496a35e39caSPetr Hosek SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1497a31c91b1SEugene Leviant   expect("(");
1498174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
1499a35e39caSPetr Hosek   Cmd->Provide = Provide;
1500174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
1501a31c91b1SEugene Leviant   expect(")");
1502a31c91b1SEugene Leviant   expect(";");
150310416564SRui Ueyama   return Cmd;
1504eda81a1bSEugene Leviant }
1505eda81a1bSEugene Leviant 
1506c96da110SRafael Espindola SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1507ceabe80eSEugene Leviant   SymbolAssignment *Cmd = nullptr;
1508ceabe80eSEugene Leviant   if (peek() == "=" || peek() == "+=") {
1509ceabe80eSEugene Leviant     Cmd = readAssignment(Tok);
1510ceabe80eSEugene Leviant     expect(";");
1511ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE") {
1512a35e39caSPetr Hosek     Cmd = readProvideHidden(true, false);
1513a35e39caSPetr Hosek   } else if (Tok == "HIDDEN") {
1514a35e39caSPetr Hosek     Cmd = readProvideHidden(false, true);
1515ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE_HIDDEN") {
1516a35e39caSPetr Hosek     Cmd = readProvideHidden(true, true);
1517ceabe80eSEugene Leviant   }
1518ceabe80eSEugene Leviant   return Cmd;
1519ceabe80eSEugene Leviant }
1520ceabe80eSEugene Leviant 
152130835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
152230835ea4SGeorge Rimar   if (S == ".")
152330835ea4SGeorge Rimar     return Dot;
1524884e786dSGeorge Rimar   return ScriptBase->getSymbolValue(S);
1525e32a3598SGeorge Rimar }
1526e32a3598SGeorge Rimar 
15272f831dcaSRafael Espindola static bool isAbsolute(StringRef S) {
15282f831dcaSRafael Espindola   if (S == ".")
15292f831dcaSRafael Espindola     return false;
15302f831dcaSRafael Espindola   return ScriptBase->isAbsolute(S);
15312f831dcaSRafael Espindola }
15322f831dcaSRafael Espindola 
153330835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
153430835ea4SGeorge Rimar   StringRef Op = next();
1535db741e72SEugene Leviant   Expr E;
153630835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
153783043f23SRui Ueyama   if (consume("ABSOLUTE")) {
15387c1381a0SRui Ueyama     // The RHS may be something like "ABSOLUTE(.) & 0xff".
15397c1381a0SRui Ueyama     // Call readExpr1 to read the whole expression.
15407c1381a0SRui Ueyama     E = readExpr1(readParenExpr(), 0);
1541009d1742SRui Ueyama     E.IsAbsolute = [] { return true; };
1542db741e72SEugene Leviant   } else {
1543db741e72SEugene Leviant     E = readExpr();
1544db741e72SEugene Leviant   }
154530835ea4SGeorge Rimar   if (Op == "+=")
154630835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1547f661393aSRafael Espindola   return new SymbolAssignment(Name, E);
154830835ea4SGeorge Rimar }
154930835ea4SGeorge Rimar 
155030835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
155130835ea4SGeorge Rimar // script expression.
155230835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
155330835ea4SGeorge Rimar 
155436c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
155536c1cd23SRui Ueyama   if (Op == "*")
155636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
155736c1cd23SRui Ueyama   if (Op == "/") {
155836c1cd23SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
155936c1cd23SRui Ueyama       uint64_t RHS = R(Dot);
156036c1cd23SRui Ueyama       if (RHS == 0) {
156136c1cd23SRui Ueyama         error("division by zero");
156236c1cd23SRui Ueyama         return 0;
156336c1cd23SRui Ueyama       }
156436c1cd23SRui Ueyama       return L(Dot) / RHS;
156536c1cd23SRui Ueyama     };
156636c1cd23SRui Ueyama   }
156736c1cd23SRui Ueyama   if (Op == "+")
15682f831dcaSRafael Espindola     return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1569009d1742SRui Ueyama             [=] { return L.IsAbsolute() && R.IsAbsolute(); },
1570009d1742SRui Ueyama             [=] {
1571afaa9343SEugene Leviant               const OutputSectionBase *S = L.Section();
1572afaa9343SEugene Leviant               return S ? S : R.Section();
1573afaa9343SEugene Leviant             }};
157436c1cd23SRui Ueyama   if (Op == "-")
157536c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1576c8ccd1f1SGeorge Rimar   if (Op == "<<")
1577c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1578c8ccd1f1SGeorge Rimar   if (Op == ">>")
1579c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
158036c1cd23SRui Ueyama   if (Op == "<")
158136c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
158236c1cd23SRui Ueyama   if (Op == ">")
158336c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
158436c1cd23SRui Ueyama   if (Op == ">=")
158536c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
158636c1cd23SRui Ueyama   if (Op == "<=")
158736c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
158836c1cd23SRui Ueyama   if (Op == "==")
158936c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
159036c1cd23SRui Ueyama   if (Op == "!=")
159136c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
159236c1cd23SRui Ueyama   if (Op == "&")
159336c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1594cc3dd629SRafael Espindola   if (Op == "|")
1595cc3dd629SRafael Espindola     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
159636c1cd23SRui Ueyama   llvm_unreachable("invalid operator");
159736c1cd23SRui Ueyama }
159836c1cd23SRui Ueyama 
1599708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
1600708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
1601708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1602708019c4SRui Ueyama   while (!atEOF() && !Error) {
1603708019c4SRui Ueyama     // Read an operator and an expression.
160446247b85SRui Ueyama     if (consume("?"))
1605708019c4SRui Ueyama       return readTernary(Lhs);
160646247b85SRui Ueyama     StringRef Op1 = peek();
1607708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
1608a31c91b1SEugene Leviant       break;
16095424e7c7SJustin Bogner     skip();
1610708019c4SRui Ueyama     Expr Rhs = readPrimary();
1611708019c4SRui Ueyama 
1612708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
1613708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
1614708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
1615708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
1616708019c4SRui Ueyama     while (!atEOF()) {
1617708019c4SRui Ueyama       StringRef Op2 = peek();
1618708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
1619eda81a1bSEugene Leviant         break;
1620708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
1621eda81a1bSEugene Leviant     }
1622708019c4SRui Ueyama 
1623708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
1624708019c4SRui Ueyama   }
1625708019c4SRui Ueyama   return Lhs;
1626708019c4SRui Ueyama }
1627708019c4SRui Ueyama 
1628708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
1629e2cc07bcSMichael J. Spencer   if (S == "COMMONPAGESIZE")
1630708019c4SRui Ueyama     return Target->PageSize;
1631e2cc07bcSMichael J. Spencer   if (S == "MAXPAGESIZE")
1632997f8838SPetr Hosek     return Config->MaxPageSize;
1633708019c4SRui Ueyama   error("unknown constant: " + S);
1634708019c4SRui Ueyama   return 0;
1635708019c4SRui Ueyama }
1636708019c4SRui Ueyama 
1637626e0b08SRui Ueyama // Parses Tok as an integer. Returns true if successful.
1638626e0b08SRui Ueyama // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1639626e0b08SRui Ueyama // and decimal numbers. Decimal numbers may have "K" (kilo) or
1640626e0b08SRui Ueyama // "M" (mega) prefixes.
16419f2f7ad9SGeorge Rimar static bool readInteger(StringRef Tok, uint64_t &Result) {
164246247b85SRui Ueyama   // Negative number
1643eaeafb2bSSimon Atanasyan   if (Tok.startswith("-")) {
1644eaeafb2bSSimon Atanasyan     if (!readInteger(Tok.substr(1), Result))
1645eaeafb2bSSimon Atanasyan       return false;
1646eaeafb2bSSimon Atanasyan     Result = -Result;
1647eaeafb2bSSimon Atanasyan     return true;
1648eaeafb2bSSimon Atanasyan   }
164946247b85SRui Ueyama 
165046247b85SRui Ueyama   // Hexadecimal
16519f2f7ad9SGeorge Rimar   if (Tok.startswith_lower("0x"))
16529f2f7ad9SGeorge Rimar     return !Tok.substr(2).getAsInteger(16, Result);
16539f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("H"))
16549f2f7ad9SGeorge Rimar     return !Tok.drop_back().getAsInteger(16, Result);
16559f2f7ad9SGeorge Rimar 
165646247b85SRui Ueyama   // Decimal
16579f2f7ad9SGeorge Rimar   int Suffix = 1;
16589f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("K")) {
16599f2f7ad9SGeorge Rimar     Suffix = 1024;
16609f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
16619f2f7ad9SGeorge Rimar   } else if (Tok.endswith_lower("M")) {
16629f2f7ad9SGeorge Rimar     Suffix = 1024 * 1024;
16639f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
16649f2f7ad9SGeorge Rimar   }
16659f2f7ad9SGeorge Rimar   if (Tok.getAsInteger(10, Result))
16669f2f7ad9SGeorge Rimar     return false;
16679f2f7ad9SGeorge Rimar   Result *= Suffix;
16689f2f7ad9SGeorge Rimar   return true;
16699f2f7ad9SGeorge Rimar }
16709f2f7ad9SGeorge Rimar 
1671e38cbab5SGeorge Rimar BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1672e38cbab5SGeorge Rimar   int Size = StringSwitch<unsigned>(Tok)
1673e38cbab5SGeorge Rimar                  .Case("BYTE", 1)
1674e38cbab5SGeorge Rimar                  .Case("SHORT", 2)
1675e38cbab5SGeorge Rimar                  .Case("LONG", 4)
1676e38cbab5SGeorge Rimar                  .Case("QUAD", 8)
1677e38cbab5SGeorge Rimar                  .Default(-1);
1678e38cbab5SGeorge Rimar   if (Size == -1)
1679e38cbab5SGeorge Rimar     return nullptr;
1680e38cbab5SGeorge Rimar 
168195c7d8d2SMeador Inge   return new BytesDataCommand(readParenExpr(), Size);
1682e38cbab5SGeorge Rimar }
1683e38cbab5SGeorge Rimar 
1684b71d6f7aSEugene Leviant StringRef ScriptParser::readParenLiteral() {
1685b71d6f7aSEugene Leviant   expect("(");
1686b71d6f7aSEugene Leviant   StringRef Tok = next();
1687b71d6f7aSEugene Leviant   expect(")");
1688b71d6f7aSEugene Leviant   return Tok;
1689b71d6f7aSEugene Leviant }
1690b71d6f7aSEugene Leviant 
1691708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
16926ad7dfccSRui Ueyama   if (peek() == "(")
16936ad7dfccSRui Ueyama     return readParenExpr();
1694708019c4SRui Ueyama 
16956ad7dfccSRui Ueyama   StringRef Tok = next();
1696b5f1c3ecSRui Ueyama   std::string Location = getCurrentLocation();
1697708019c4SRui Ueyama 
1698eaeafb2bSSimon Atanasyan   if (Tok == "~") {
1699eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1700eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return ~E(Dot); };
1701eaeafb2bSSimon Atanasyan   }
1702eaeafb2bSSimon Atanasyan   if (Tok == "-") {
1703eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1704eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return -E(Dot); };
1705eaeafb2bSSimon Atanasyan   }
1706eaeafb2bSSimon Atanasyan 
1707708019c4SRui Ueyama   // Built-in functions are parsed here.
1708708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
170996659df0SGeorge Rimar   if (Tok == "ADDR") {
1710b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1711ed30ce7aSEugene Leviant     return {[=](uint64_t Dot) {
1712ed30ce7aSEugene Leviant               return ScriptBase->getOutputSection(Location, Name)->Addr;
1713ed30ce7aSEugene Leviant             },
1714009d1742SRui Ueyama             [=] { return false; },
1715ed30ce7aSEugene Leviant             [=] { return ScriptBase->getOutputSection(Location, Name); }};
171696659df0SGeorge Rimar   }
1717b71d6f7aSEugene Leviant   if (Tok == "LOADADDR") {
1718b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1719afaa9343SEugene Leviant     return [=](uint64_t Dot) {
1720ed30ce7aSEugene Leviant       return ScriptBase->getOutputSection(Location, Name)->getLMA();
1721afaa9343SEugene Leviant     };
1722b71d6f7aSEugene Leviant   }
1723eefa758eSGeorge Rimar   if (Tok == "ASSERT")
1724eefa758eSGeorge Rimar     return readAssert();
1725708019c4SRui Ueyama   if (Tok == "ALIGN") {
17265d804dc8SRui Ueyama     expect("(");
17275d804dc8SRui Ueyama     Expr E = readExpr();
17285d804dc8SRui Ueyama     if (consume(",")) {
17295d804dc8SRui Ueyama       Expr E2 = readExpr();
17305d804dc8SRui Ueyama       expect(")");
17315d804dc8SRui Ueyama       return [=](uint64_t Dot) { return alignTo(E(Dot), E2(Dot)); };
17325d804dc8SRui Ueyama     }
17335d804dc8SRui Ueyama     expect(")");
1734708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1735708019c4SRui Ueyama   }
1736708019c4SRui Ueyama   if (Tok == "CONSTANT") {
1737b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1738b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return getConstant(Name); };
1739708019c4SRui Ueyama   }
1740f34f45fdSGeorge Rimar   if (Tok == "DEFINED") {
17410ee25a69SRui Ueyama     StringRef Name = readParenLiteral();
17420ee25a69SRui Ueyama     return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
1743f34f45fdSGeorge Rimar   }
174454c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
174554c145ceSRafael Espindola     expect("(");
17465424e7c7SJustin Bogner     skip();
174754c145ceSRafael Espindola     expect(",");
17488c658bf8SGeorge Rimar     Expr E = readExpr();
174954c145ceSRafael Espindola     expect(")");
17508c658bf8SGeorge Rimar     return [=](uint64_t Dot) { return E(Dot); };
175154c145ceSRafael Espindola   }
1752708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
1753708019c4SRui Ueyama     expect("(");
1754708019c4SRui Ueyama     Expr E = readExpr();
1755708019c4SRui Ueyama     expect(",");
1756708019c4SRui Ueyama     readExpr();
1757708019c4SRui Ueyama     expect(")");
1758f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1759708019c4SRui Ueyama   }
1760708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
1761708019c4SRui Ueyama     expect("(");
1762708019c4SRui Ueyama     expect(".");
1763708019c4SRui Ueyama     expect(")");
1764708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
1765708019c4SRui Ueyama   }
1766276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
1767276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1768276b4e64SGeorge Rimar   // the next page boundary for simplicity.
1769276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
1770276b4e64SGeorge Rimar     expect("(");
177197bdc722SRafael Espindola     readExpr();
1772276b4e64SGeorge Rimar     expect(",");
1773276b4e64SGeorge Rimar     readExpr();
1774276b4e64SGeorge Rimar     expect(")");
1775276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1776276b4e64SGeorge Rimar   }
17779e69450eSGeorge Rimar   if (Tok == "SIZEOF") {
1778b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1779edf75e79SRui Ueyama     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
17809e69450eSGeorge Rimar   }
178136fac7f0SEugene Leviant   if (Tok == "ALIGNOF") {
1782b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1783afaa9343SEugene Leviant     return [=](uint64_t Dot) {
1784ed30ce7aSEugene Leviant       return ScriptBase->getOutputSection(Location, Name)->Addralign;
1785afaa9343SEugene Leviant     };
178636fac7f0SEugene Leviant   }
1787e32a3598SGeorge Rimar   if (Tok == "SIZEOF_HEADERS")
1788b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1789708019c4SRui Ueyama 
17909f2f7ad9SGeorge Rimar   // Tok is a literal number.
17919f2f7ad9SGeorge Rimar   uint64_t V;
17929f2f7ad9SGeorge Rimar   if (readInteger(Tok, V))
1793b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return V; };
17949f2f7ad9SGeorge Rimar 
17959f2f7ad9SGeorge Rimar   // Tok is a symbol name.
179630835ea4SGeorge Rimar   if (Tok != "." && !isValidCIdentifier(Tok))
1797708019c4SRui Ueyama     setError("malformed number: " + Tok);
17982f831dcaSRafael Espindola   return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
1799009d1742SRui Ueyama           [=] { return isAbsolute(Tok); },
1800009d1742SRui Ueyama           [=] { return ScriptBase->getSymbolSection(Tok); }};
1801a9c5a528SGeorge Rimar }
1802708019c4SRui Ueyama 
1803708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
1804708019c4SRui Ueyama   Expr L = readExpr();
1805708019c4SRui Ueyama   expect(":");
1806708019c4SRui Ueyama   Expr R = readExpr();
1807708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1808708019c4SRui Ueyama }
1809708019c4SRui Ueyama 
18106ad7dfccSRui Ueyama Expr ScriptParser::readParenExpr() {
18116ad7dfccSRui Ueyama   expect("(");
18126ad7dfccSRui Ueyama   Expr E = readExpr();
18136ad7dfccSRui Ueyama   expect(")");
18146ad7dfccSRui Ueyama   return E;
18156ad7dfccSRui Ueyama }
18166ad7dfccSRui Ueyama 
1817bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1818bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
1819bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
1820bbe38602SEugene Leviant     StringRef Tok = next();
1821da841c16SGeorge Rimar     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1822bbe38602SEugene Leviant   }
1823bbe38602SEugene Leviant   return Phdrs;
1824bbe38602SEugene Leviant }
1825bbe38602SEugene Leviant 
182695dd718cSGeorge Rimar // Read a program header type name. The next token must be a
182795dd718cSGeorge Rimar // name of a program header type or a constant (e.g. "0x3").
1828bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
1829bbe38602SEugene Leviant   StringRef Tok = next();
183095dd718cSGeorge Rimar   uint64_t Val;
183195dd718cSGeorge Rimar   if (readInteger(Tok, Val))
183295dd718cSGeorge Rimar     return Val;
183395dd718cSGeorge Rimar 
1834b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
1835b0f6c590SRui Ueyama                      .Case("PT_NULL", PT_NULL)
1836b0f6c590SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
1837b0f6c590SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1838b0f6c590SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
1839b0f6c590SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
1840b0f6c590SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
1841b0f6c590SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
1842b0f6c590SRui Ueyama                      .Case("PT_TLS", PT_TLS)
1843b0f6c590SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1844b0f6c590SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1845b0f6c590SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1846270173f2SGeorge Rimar                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1847cc6e567cSGeorge Rimar                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1848a2a32c2cSGeorge Rimar                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1849b0f6c590SRui Ueyama                      .Default(-1);
1850bbe38602SEugene Leviant 
1851b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1852b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1853b0f6c590SRui Ueyama     return PT_NULL;
1854b0f6c590SRui Ueyama   }
1855b0f6c590SRui Ueyama   return Ret;
1856bbe38602SEugene Leviant }
1857bbe38602SEugene Leviant 
185812450b20SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
185912450b20SRui Ueyama void ScriptParser::readAnonymousDeclaration() {
186012450b20SRui Ueyama   // Read global symbols first. "global:" is default, so if there's
186112450b20SRui Ueyama   // no label, we assume global symbols.
186212450b20SRui Ueyama   if (consume("global:") || peek() != "local:")
186312450b20SRui Ueyama     Config->VersionScriptGlobals = readSymbols();
186412450b20SRui Ueyama 
186512450b20SRui Ueyama   // Next, read local symbols.
186612450b20SRui Ueyama   if (consume("local:")) {
186712450b20SRui Ueyama     if (consume("*")) {
186812450b20SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
186912450b20SRui Ueyama       expect(";");
187012450b20SRui Ueyama     } else {
187112450b20SRui Ueyama       setError("local symbol list for anonymous version is not supported");
187212450b20SRui Ueyama     }
187312450b20SRui Ueyama   }
187412450b20SRui Ueyama   expect("}");
187512450b20SRui Ueyama   expect(";");
187612450b20SRui Ueyama }
187712450b20SRui Ueyama 
187812450b20SRui Ueyama // Reads a list of symbols, e.g. "VerStr { global: foo; bar; local: *; };".
187995769b4aSRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
188020b6598cSGeorge Rimar   // Identifiers start at 2 because 0 and 1 are reserved
188120b6598cSGeorge Rimar   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1882da805c48SRui Ueyama   uint16_t VersionId = Config->VersionDefinitions.size() + 2;
188320b6598cSGeorge Rimar   Config->VersionDefinitions.push_back({VerStr, VersionId});
188420b6598cSGeorge Rimar 
188512450b20SRui Ueyama   // Read global symbols.
188683043f23SRui Ueyama   if (consume("global:") || peek() != "local:")
188712450b20SRui Ueyama     Config->VersionDefinitions.back().Globals = readSymbols();
188812450b20SRui Ueyama 
188912450b20SRui Ueyama   // Read local symbols.
189012450b20SRui Ueyama   if (consume("local:")) {
189112450b20SRui Ueyama     if (consume("*")) {
189212450b20SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
189312450b20SRui Ueyama       expect(";");
189412450b20SRui Ueyama     } else {
189512450b20SRui Ueyama       for (SymbolVersion V : readSymbols())
189612450b20SRui Ueyama         Config->VersionScriptLocals.push_back(V);
189712450b20SRui Ueyama     }
189812450b20SRui Ueyama   }
189920b6598cSGeorge Rimar   expect("}");
190020b6598cSGeorge Rimar 
190112450b20SRui Ueyama   // Each version may have a parent version. For example, "Ver2"
190212450b20SRui Ueyama   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
190312450b20SRui Ueyama   // as a parent. This version hierarchy is, probably against your
190412450b20SRui Ueyama   // instinct, purely for hint; the runtime doesn't care about it
190512450b20SRui Ueyama   // at all. In LLD, we simply ignore it.
190612450b20SRui Ueyama   if (peek() != ";")
19075424e7c7SJustin Bogner     skip();
190820b6598cSGeorge Rimar   expect(";");
190920b6598cSGeorge Rimar }
191020b6598cSGeorge Rimar 
191112450b20SRui Ueyama // Reads a list of symbols for a versions cript.
191212450b20SRui Ueyama std::vector<SymbolVersion> ScriptParser::readSymbols() {
191312450b20SRui Ueyama   std::vector<SymbolVersion> Ret;
1914e0fc2421SGeorge Rimar   for (;;) {
19151ef90d2fSRafael Espindola     if (consume("extern")) {
191612450b20SRui Ueyama       for (SymbolVersion V : readVersionExtern())
191712450b20SRui Ueyama         Ret.push_back(V);
19181ef90d2fSRafael Espindola       continue;
19191ef90d2fSRafael Espindola     }
1920e0fc2421SGeorge Rimar 
19210ee25a69SRui Ueyama     if (peek() == "}" || peek() == "local:" || Error)
192212450b20SRui Ueyama       break;
19230ee25a69SRui Ueyama     StringRef Tok = next();
192412450b20SRui Ueyama     Ret.push_back({unquote(Tok), false, hasWildcard(Tok)});
1925e0fc2421SGeorge Rimar     expect(";");
1926e0fc2421SGeorge Rimar   }
192712450b20SRui Ueyama   return Ret;
1928e0fc2421SGeorge Rimar }
1929e0fc2421SGeorge Rimar 
193012450b20SRui Ueyama // Reads an "extern C++" directive, e.g.,
193112450b20SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };"
193212450b20SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
19337e71415cSRafael Espindola   StringRef Tok = next();
19347e71415cSRafael Espindola   bool IsCXX = Tok == "\"C++\"";
19357e71415cSRafael Espindola   if (!IsCXX && Tok != "\"C\"")
1936d0ebd84cSRafael Espindola     setError("Unknown language");
193720b6598cSGeorge Rimar   expect("{");
193820b6598cSGeorge Rimar 
193912450b20SRui Ueyama   std::vector<SymbolVersion> Ret;
19400ee25a69SRui Ueyama   while (!Error && peek() != "}") {
19410ee25a69SRui Ueyama     StringRef Tok = next();
19420ee25a69SRui Ueyama     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
19437e71415cSRafael Espindola     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
194420b6598cSGeorge Rimar     expect(";");
194520b6598cSGeorge Rimar   }
194620b6598cSGeorge Rimar 
194720b6598cSGeorge Rimar   expect("}");
194820b6598cSGeorge Rimar   expect(";");
194912450b20SRui Ueyama   return Ret;
195020b6598cSGeorge Rimar }
195120b6598cSGeorge Rimar 
195207320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
195322375f24SRui Ueyama   ScriptParser(MB).readLinkerScript();
195420b6598cSGeorge Rimar }
195520b6598cSGeorge Rimar 
195620b6598cSGeorge Rimar void elf::readVersionScript(MemoryBufferRef MB) {
195722375f24SRui Ueyama   ScriptParser(MB).readVersionScript();
1958f7c5fbb1SRui Ueyama }
19591ebc8ed7SRui Ueyama 
1960d0ebd84cSRafael Espindola void elf::readDynamicList(MemoryBufferRef MB) {
1961d0ebd84cSRafael Espindola   ScriptParser(MB).readDynamicList();
1962d0ebd84cSRafael Espindola }
1963d0ebd84cSRafael Espindola 
196407320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
196507320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
196607320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
196707320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1968