1f7c5fbb1SRui Ueyama //===- LinkerScript.cpp ---------------------------------------------------===//
2f7c5fbb1SRui Ueyama //
3f7c5fbb1SRui Ueyama //                             The LLVM Linker
4f7c5fbb1SRui Ueyama //
5f7c5fbb1SRui Ueyama // This file is distributed under the University of Illinois Open Source
6f7c5fbb1SRui Ueyama // License. See LICENSE.TXT for details.
7f7c5fbb1SRui Ueyama //
8f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
9f7c5fbb1SRui Ueyama //
10f7c5fbb1SRui Ueyama // This file contains the parser/evaluator of the linker script.
11629e0aa5SRui Ueyama // It parses a linker script and write the result to Config or ScriptConfig
12629e0aa5SRui Ueyama // objects.
13629e0aa5SRui Ueyama //
14629e0aa5SRui Ueyama // If SECTIONS command is used, a ScriptConfig contains an AST
15629e0aa5SRui Ueyama // of the command which will later be consumed by createSections() and
16629e0aa5SRui Ueyama // assignAddresses().
17f7c5fbb1SRui Ueyama //
18f7c5fbb1SRui Ueyama //===----------------------------------------------------------------------===//
19f7c5fbb1SRui Ueyama 
20717677afSRui Ueyama #include "LinkerScript.h"
21f7c5fbb1SRui Ueyama #include "Config.h"
22f7c5fbb1SRui Ueyama #include "Driver.h"
231ebc8ed7SRui Ueyama #include "InputSection.h"
2455518e7dSRui Ueyama #include "Memory.h"
25652852c5SGeorge Rimar #include "OutputSections.h"
26e77b5bf6SAdhemerval Zanella #include "ScriptParser.h"
2793c9af42SRui Ueyama #include "Strings.h"
28f7c5fbb1SRui Ueyama #include "SymbolTable.h"
2955518e7dSRui Ueyama #include "Symbols.h"
30467c4d55SEugene Leviant #include "Target.h"
31bbe38602SEugene Leviant #include "Writer.h"
3222886a28SEugene Zelenko #include "llvm/ADT/STLExtras.h"
338c6a5aafSRui Ueyama #include "llvm/ADT/SmallString.h"
3422886a28SEugene Zelenko #include "llvm/ADT/StringRef.h"
35960504b9SRui Ueyama #include "llvm/ADT/StringSwitch.h"
3622886a28SEugene Zelenko #include "llvm/Support/Casting.h"
37652852c5SGeorge Rimar #include "llvm/Support/ELF.h"
3822886a28SEugene Zelenko #include "llvm/Support/Endian.h"
3922886a28SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
40f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h"
4122886a28SEugene Zelenko #include "llvm/Support/MathExtras.h"
42f7c5fbb1SRui Ueyama #include "llvm/Support/MemoryBuffer.h"
43f03f3cc1SRui Ueyama #include "llvm/Support/Path.h"
4422886a28SEugene Zelenko #include <algorithm>
4522886a28SEugene Zelenko #include <cassert>
4622886a28SEugene Zelenko #include <cstddef>
4722886a28SEugene Zelenko #include <cstdint>
4822886a28SEugene Zelenko #include <iterator>
4922886a28SEugene Zelenko #include <limits>
5022886a28SEugene Zelenko #include <memory>
5122886a28SEugene Zelenko #include <string>
5222886a28SEugene Zelenko #include <tuple>
5322886a28SEugene Zelenko #include <vector>
54f7c5fbb1SRui Ueyama 
55f7c5fbb1SRui Ueyama using namespace llvm;
56652852c5SGeorge Rimar using namespace llvm::ELF;
571ebc8ed7SRui Ueyama using namespace llvm::object;
58e38cbab5SGeorge Rimar using namespace llvm::support::endian;
59f7c5fbb1SRui Ueyama using namespace lld;
60e0df00b9SRafael Espindola using namespace lld::elf;
61f7c5fbb1SRui Ueyama 
62884e786dSGeorge Rimar LinkerScriptBase *elf::ScriptBase;
6307320e40SRui Ueyama ScriptConfiguration *elf::ScriptConfig;
64717677afSRui Ueyama 
656c55f0e3SGeorge Rimar template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
663dabfc6bSRafael Espindola   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
671bdaf3e3SRui Ueyama   Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
68463984d4SGeorge Rimar                                             0, 0, STB_GLOBAL, nullptr, nullptr);
691602421cSRui Ueyama   Cmd->Sym = Sym->body();
7020d03194SEugene Leviant 
7120d03194SEugene Leviant   // If we have no SECTIONS then we don't have '.' and don't call
7220d03194SEugene Leviant   // assignAddresses(). We calculate symbol value immediately in this case.
7320d03194SEugene Leviant   if (!ScriptConfig->HasSections)
7420d03194SEugene Leviant     cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
75ceabe80eSEugene Leviant }
76ceabe80eSEugene Leviant 
770c70d3ccSRui Ueyama template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
78afaa9343SEugene Leviant   // If we have SECTIONS block then output sections haven't been created yet.
79afaa9343SEugene Leviant   const OutputSectionBase *Sec =
80afaa9343SEugene Leviant       ScriptConfig->HasSections ? nullptr : Cmd->Expression.Section();
81e1937bb5SGeorge Rimar   Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
82afaa9343SEugene Leviant       Cmd->Name, Sec, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
831602421cSRui Ueyama   Cmd->Sym = Sym->body();
84afaa9343SEugene Leviant 
85afaa9343SEugene Leviant   // If we already know section then we can calculate symbol value immediately.
86afaa9343SEugene Leviant   if (Sec)
87afaa9343SEugene Leviant     cast<DefinedSynthetic<ELFT>>(Cmd->Sym)->Value =
88afaa9343SEugene Leviant         Cmd->Expression(0) - Sec->Addr;
89ceabe80eSEugene Leviant }
90ceabe80eSEugene Leviant 
91db741e72SEugene Leviant template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
922f831dcaSRafael Espindola   if (Cmd->Expression.IsAbsolute())
93db741e72SEugene Leviant     addRegular<ELFT>(Cmd);
94db741e72SEugene Leviant   else
95db741e72SEugene Leviant     addSynthetic<ELFT>(Cmd);
96db741e72SEugene Leviant }
971602421cSRui Ueyama // If a symbol was in PROVIDE(), we need to define it only when
981602421cSRui Ueyama // it is an undefined symbol.
991602421cSRui Ueyama template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
1001602421cSRui Ueyama   if (Cmd->Name == ".")
101ceabe80eSEugene Leviant     return false;
1021602421cSRui Ueyama   if (!Cmd->Provide)
103ceabe80eSEugene Leviant     return true;
1041602421cSRui Ueyama   SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
1051602421cSRui Ueyama   return B && B->isUndefined();
106ceabe80eSEugene Leviant }
107ceabe80eSEugene Leviant 
108076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
109076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
110076fe157SGeorge Rimar }
111076fe157SGeorge Rimar 
112076fe157SGeorge Rimar bool OutputSectionCommand::classof(const BaseCommand *C) {
113076fe157SGeorge Rimar   return C->Kind == OutputSectionKind;
114076fe157SGeorge Rimar }
115076fe157SGeorge Rimar 
116eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
117eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
118eea3114fSGeorge Rimar }
119eea3114fSGeorge Rimar 
120eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
121eefa758eSGeorge Rimar   return C->Kind == AssertKind;
122eefa758eSGeorge Rimar }
123eefa758eSGeorge Rimar 
124e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) {
125e38cbab5SGeorge Rimar   return C->Kind == BytesDataKind;
126e38cbab5SGeorge Rimar }
127e38cbab5SGeorge Rimar 
12822886a28SEugene Zelenko template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
12922886a28SEugene Zelenko template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
130f34d0e08SRui Ueyama 
13107320e40SRui Ueyama template <class ELFT>
13207320e40SRui Ueyama bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
133cf43f179SEugene Leviant   for (InputSectionDescription *ID : Opt.KeptSections) {
134cf43f179SEugene Leviant     StringRef Filename = S->getFile()->getName();
135f91282e1SRui Ueyama     if (!ID->FilePat.match(sys::path::filename(Filename)))
136cf43f179SEugene Leviant       continue;
137cf43f179SEugene Leviant 
138cf43f179SEugene Leviant     for (SectionPattern &P : ID->SectionPatterns)
139f91282e1SRui Ueyama       if (P.SectionPat.match(S->Name))
140eea3114fSGeorge Rimar         return true;
141cf43f179SEugene Leviant   }
142eea3114fSGeorge Rimar   return false;
143eea3114fSGeorge Rimar }
144eea3114fSGeorge Rimar 
145575208caSGeorge Rimar static bool comparePriority(InputSectionData *A, InputSectionData *B) {
146575208caSGeorge Rimar   return getPriority(A->Name) < getPriority(B->Name);
147575208caSGeorge Rimar }
148575208caSGeorge Rimar 
149c0028d3dSRafael Espindola static bool compareName(InputSectionData *A, InputSectionData *B) {
150042a3f20SRafael Espindola   return A->Name < B->Name;
1510702c4e8SGeorge Rimar }
152742c3836SRui Ueyama 
153c0028d3dSRafael Espindola static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
154742c3836SRui Ueyama   // ">" is not a mistake. Larger alignments are placed before smaller
155742c3836SRui Ueyama   // alignments in order to reduce the amount of padding necessary.
156742c3836SRui Ueyama   // This is compatible with GNU.
157742c3836SRui Ueyama   return A->Alignment > B->Alignment;
158742c3836SRui Ueyama }
159742c3836SRui Ueyama 
160c0028d3dSRafael Espindola static std::function<bool(InputSectionData *, InputSectionData *)>
161be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
162be394db3SGeorge Rimar   switch (K) {
163be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
164c0028d3dSRafael Espindola     return compareAlignment;
165be394db3SGeorge Rimar   case SortSectionPolicy::Name:
166be394db3SGeorge Rimar     return compareName;
167be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
168be394db3SGeorge Rimar     return comparePriority;
169be394db3SGeorge Rimar   default:
170be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
171be394db3SGeorge Rimar   }
172742c3836SRui Ueyama }
1730702c4e8SGeorge Rimar 
17448c3f1ceSRui Ueyama template <class ELFT>
175e71a3f8aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
17606ae6836SGeorge Rimar                              ConstraintKind Kind) {
1778f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
1788f66df92SGeorge Rimar     return true;
179e746e52cSRafael Espindola   bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
180d3190795SRafael Espindola     auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
1811854a8ebSRafael Espindola     return Sec->Flags & SHF_WRITE;
18206ae6836SGeorge Rimar   });
183e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
184e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
18506ae6836SGeorge Rimar }
18606ae6836SGeorge Rimar 
18707171f21SGeorge Rimar static void sortSections(InputSectionData **Begin, InputSectionData **End,
188ee924709SRui Ueyama                          SortSectionPolicy K) {
189ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
19007171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
191ee924709SRui Ueyama }
192ee924709SRui Ueyama 
193d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
194be94e1b6SRafael Espindola template <class ELFT>
195e71a3f8aSRafael Espindola void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
1964dc07becSRui Ueyama   // Collects all sections that satisfy constraints of I
1974dc07becSRui Ueyama   // and attach them to I.
1984dc07becSRui Ueyama   for (SectionPattern &Pat : I->SectionPatterns) {
19907171f21SGeorge Rimar     size_t SizeBefore = I->Sections.size();
2008c6a5aafSRui Ueyama 
2018c6a5aafSRui Ueyama     for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
2028f9026baSRafael Espindola       if (!S->Live || S->OutSec)
2038c6a5aafSRui Ueyama         continue;
2048c6a5aafSRui Ueyama 
2058c6a5aafSRui Ueyama       StringRef Filename;
2068c6a5aafSRui Ueyama       if (elf::ObjectFile<ELFT> *F = S->getFile())
2078c6a5aafSRui Ueyama         Filename = sys::path::filename(F->getName());
2088c6a5aafSRui Ueyama 
209e8a6102fSRui Ueyama       if (I->FilePat.match(Filename) && !Pat.ExcludedFilePat.match(Filename) &&
210e8a6102fSRui Ueyama           Pat.SectionPat.match(S->Name))
211d3190795SRafael Espindola         I->Sections.push_back(S);
212395281cfSGeorge Rimar     }
213d3190795SRafael Espindola 
214ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
215ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
216ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
217ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
218ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
219ee924709SRui Ueyama     //
220ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
221ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
222ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
223ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
224ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
22507171f21SGeorge Rimar     InputSectionData **Begin = I->Sections.data() + SizeBefore;
22607171f21SGeorge Rimar     InputSectionData **End = I->Sections.data() + I->Sections.size();
22707171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
22807171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
22907171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
230ee924709SRui Ueyama       else
23107171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
23207171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
23307171f21SGeorge Rimar     }
234ee924709SRui Ueyama   }
235d3190795SRafael Espindola 
236d3190795SRafael Espindola   // We do not add duplicate input sections, so mark them with a dummy output
237d3190795SRafael Espindola   // section for now.
238d3190795SRafael Espindola   for (InputSectionData *S : I->Sections) {
239d3190795SRafael Espindola     auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
240e08e78dfSRafael Espindola     S2->OutSec = (OutputSectionBase *)-1;
241d3190795SRafael Espindola   }
242be94e1b6SRafael Espindola }
243be94e1b6SRafael Espindola 
244be94e1b6SRafael Espindola template <class ELFT>
245be94e1b6SRafael Espindola void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
246be94e1b6SRafael Espindola   for (InputSectionBase<ELFT> *S : V) {
247be94e1b6SRafael Espindola     S->Live = false;
248be94e1b6SRafael Espindola     reportDiscarded(S);
249be94e1b6SRafael Espindola   }
250be94e1b6SRafael Espindola }
251be94e1b6SRafael Espindola 
25206ae6836SGeorge Rimar template <class ELFT>
2530b9ce6a4SRui Ueyama std::vector<InputSectionBase<ELFT> *>
25406ae6836SGeorge Rimar LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
2550b9ce6a4SRui Ueyama   std::vector<InputSectionBase<ELFT> *> Ret;
256e7f912cdSRui Ueyama 
25706ae6836SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
2587c3ff2ebSRafael Espindola     auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
2597c3ff2ebSRafael Espindola     if (!Cmd)
2600b9ce6a4SRui Ueyama       continue;
261e71a3f8aSRafael Espindola     computeInputSections(Cmd);
262d3190795SRafael Espindola     for (InputSectionData *S : Cmd->Sections)
263d3190795SRafael Espindola       Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
2640b9ce6a4SRui Ueyama   }
265e71a3f8aSRafael Espindola 
266cc1ba8c7SEugene Leviant   // After we created final list we should now set OutSec pointer to null,
267cc1ba8c7SEugene Leviant   // instead of -1. Otherwise we may get a crash when writing relocs, in
268cc1ba8c7SEugene Leviant   // case section is discarded by linker script
269cc1ba8c7SEugene Leviant   for (InputSectionBase<ELFT> *S : Ret)
270cc1ba8c7SEugene Leviant     S->OutSec = nullptr;
271cc1ba8c7SEugene Leviant 
2720b9ce6a4SRui Ueyama   return Ret;
2730b9ce6a4SRui Ueyama }
2740b9ce6a4SRui Ueyama 
275e5d3ca50SPetr Hosek template <class ELFT>
27610897f18SRafael Espindola static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
27710897f18SRafael Espindola                                             StringRef OutsecName) {
27810897f18SRafael Espindola   // When using linker script the merge rules are different.
27910897f18SRafael Espindola   // Unfortunately, linker scripts are name based. This means that expressions
28010897f18SRafael Espindola   // like *(.foo*) can refer to multiple input sections that would normally be
28110897f18SRafael Espindola   // placed in different output sections. We cannot put them in different
28210897f18SRafael Espindola   // output sections or we would produce wrong results for
28310897f18SRafael Espindola   // start = .; *(.foo.*) end = .; *(.bar)
28410897f18SRafael Espindola   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
28510897f18SRafael Espindola   // another. The problem is that there is no way to layout those output
28610897f18SRafael Espindola   // sections such that the .foo sections are the only thing between the
28710897f18SRafael Espindola   // start and end symbols.
28810897f18SRafael Espindola 
28910897f18SRafael Espindola   // An extra annoyance is that we cannot simply disable merging of the contents
29010897f18SRafael Espindola   // of SHF_MERGE sections, but our implementation requires one output section
29110897f18SRafael Espindola   // per "kind" (string or not, which size/aligment).
29210897f18SRafael Espindola   // Fortunately, creating symbols in the middle of a merge section is not
29310897f18SRafael Espindola   // supported by bfd or gold, so we can just create multiple section in that
29410897f18SRafael Espindola   // case.
29510897f18SRafael Espindola   typedef typename ELFT::uint uintX_t;
2961854a8ebSRafael Espindola   uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
29710897f18SRafael Espindola 
29810897f18SRafael Espindola   uintX_t Alignment = 0;
29910897f18SRafael Espindola   if (isa<MergeInputSection<ELFT>>(C))
3001854a8ebSRafael Espindola     Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
30110897f18SRafael Espindola 
30210897f18SRafael Espindola   return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
30310897f18SRafael Espindola }
30410897f18SRafael Espindola 
30510897f18SRafael Espindola template <class ELFT>
30620d03194SEugene Leviant void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
30720d03194SEugene Leviant                                     InputSectionBase<ELFT> *Sec,
30820d03194SEugene Leviant                                     StringRef Name) {
309e08e78dfSRafael Espindola   OutputSectionBase *OutSec;
31028c1597aSRafael Espindola   bool IsNew;
31110897f18SRafael Espindola   std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
31228c1597aSRafael Espindola   if (IsNew)
31328c1597aSRafael Espindola     OutputSections->push_back(OutSec);
31420d03194SEugene Leviant   OutSec->addSection(Sec);
31520d03194SEugene Leviant }
31620d03194SEugene Leviant 
31720d03194SEugene Leviant template <class ELFT>
31820d03194SEugene Leviant void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
3197c3ff2ebSRafael Espindola   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
3207c3ff2ebSRafael Espindola     auto Iter = Opt.Commands.begin() + I;
3217c3ff2ebSRafael Espindola     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
3222ab5f73dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
3232ab5f73dSRui Ueyama       if (shouldDefine<ELFT>(Cmd))
324b0de56b5SRafael Espindola         addSymbol<ELFT>(Cmd);
3252ab5f73dSRui Ueyama       continue;
3262ab5f73dSRui Ueyama     }
32720d03194SEugene Leviant     if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
32820d03194SEugene Leviant       // If we don't have SECTIONS then output sections have already been
329194470cdSGeorge Rimar       // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
33020d03194SEugene Leviant       // will not be called, so ASSERT should be evaluated now.
33120d03194SEugene Leviant       if (!Opt.HasSections)
33220d03194SEugene Leviant         Cmd->Expression(0);
33320d03194SEugene Leviant       continue;
33420d03194SEugene Leviant     }
3352ab5f73dSRui Ueyama 
336ceabe80eSEugene Leviant     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
3377bd37870SRafael Espindola       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
3387bd37870SRafael Espindola 
33948c3f1ceSRui Ueyama       if (Cmd->Name == "/DISCARD/") {
3407bd37870SRafael Espindola         discard(V);
34148c3f1ceSRui Ueyama         continue;
34248c3f1ceSRui Ueyama       }
3430b9ce6a4SRui Ueyama 
3447c3ff2ebSRafael Espindola       if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
3457c3ff2ebSRafael Espindola         for (InputSectionBase<ELFT> *S : V)
3467c3ff2ebSRafael Espindola           S->OutSec = nullptr;
3477c3ff2ebSRafael Espindola         Opt.Commands.erase(Iter);
348dfbbbc86SGeorge Rimar         --I;
3497c3ff2ebSRafael Espindola         continue;
3507c3ff2ebSRafael Espindola       }
3517c3ff2ebSRafael Espindola 
3527c3ff2ebSRafael Espindola       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
3537c3ff2ebSRafael Espindola         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
3547c3ff2ebSRafael Espindola           if (shouldDefine<ELFT>(OutCmd))
3557c3ff2ebSRafael Espindola             addSymbol<ELFT>(OutCmd);
3567c3ff2ebSRafael Espindola 
35797403d15SEugene Leviant       if (V.empty())
3580b9ce6a4SRui Ueyama         continue;
3590b9ce6a4SRui Ueyama 
360a14b13d8SGeorge Rimar       for (InputSectionBase<ELFT> *Sec : V) {
36120d03194SEugene Leviant         addSection(Factory, Sec, Cmd->Name);
36220d03194SEugene Leviant         if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
363db24d9c3SGeorge Rimar           Sec->Alignment = Subalign;
36420d03194SEugene Leviant       }
365eea3114fSGeorge Rimar     }
36648c3f1ceSRui Ueyama   }
367db24d9c3SGeorge Rimar }
368e63d81bdSEugene Leviant 
36920d03194SEugene Leviant template <class ELFT>
37020d03194SEugene Leviant void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
37120d03194SEugene Leviant   processCommands(Factory);
3728c6a5aafSRui Ueyama 
3730b9ce6a4SRui Ueyama   // Add orphan sections.
3748c6a5aafSRui Ueyama   for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
3758f9026baSRafael Espindola     if (S->Live && !S->OutSec)
37655518e7dSRui Ueyama       addSection(Factory, S, getOutputSectionName(S->Name));
377e63d81bdSEugene Leviant }
378e63d81bdSEugene Leviant 
379db741e72SEugene Leviant // Sets value of a section-defined symbol. Two kinds of
380db741e72SEugene Leviant // symbols are processed: synthetic symbols, whose value
381db741e72SEugene Leviant // is an offset from beginning of section and regular
382db741e72SEugene Leviant // symbols whose value is absolute.
383db741e72SEugene Leviant template <class ELFT>
384afaa9343SEugene Leviant static void assignSectionSymbol(SymbolAssignment *Cmd,
385498ed714SRafael Espindola                                 typename ELFT::uint Value) {
386db741e72SEugene Leviant   if (!Cmd->Sym)
387db741e72SEugene Leviant     return;
388db741e72SEugene Leviant 
389db741e72SEugene Leviant   if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
390afaa9343SEugene Leviant     Body->Section = Cmd->Expression.Section();
391afaa9343SEugene Leviant     Body->Value = Cmd->Expression(Value) - Body->Section->Addr;
392db741e72SEugene Leviant     return;
393db741e72SEugene Leviant   }
394db741e72SEugene Leviant   auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
395498ed714SRafael Espindola   Body->Value = Cmd->Expression(Value);
396db741e72SEugene Leviant }
397db741e72SEugene Leviant 
398e08e78dfSRafael Espindola template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
39904a2e348SRafael Espindola   return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
400a940e539SRafael Espindola }
401a940e539SRafael Espindola 
402d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
403d3190795SRafael Espindola   if (!AlreadyOutputIS.insert(S).second)
404ceabe80eSEugene Leviant     return;
405e08e78dfSRafael Espindola   bool IsTbss = isTbss<ELFT>(CurOutSec);
406d3190795SRafael Espindola 
407d3190795SRafael Espindola   uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
408d3190795SRafael Espindola   Pos = alignTo(Pos, S->Alignment);
40904a2e348SRafael Espindola   S->OutSecOff = Pos - CurOutSec->Addr;
410d3190795SRafael Espindola   Pos += S->getSize();
411d3190795SRafael Espindola 
412d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
413d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
414d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
41504a2e348SRafael Espindola   CurOutSec->Size = Pos - CurOutSec->Addr;
416d3190795SRafael Espindola 
4177252ae52SRafael Espindola   if (IsTbss)
4187252ae52SRafael Espindola     ThreadBssOffset = Pos - Dot;
4197252ae52SRafael Espindola   else
420d3190795SRafael Espindola     Dot = Pos;
4212de509c3SRui Ueyama }
422ceabe80eSEugene Leviant 
423d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::flush() {
42465499b90SRafael Espindola   if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
42565499b90SRafael Espindola     return;
42665499b90SRafael Espindola   if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
427d3190795SRafael Espindola     for (InputSection<ELFT> *I : OutSec->Sections)
428d3190795SRafael Espindola       output(I);
42965499b90SRafael Espindola   } else {
43004a2e348SRafael Espindola     Dot += CurOutSec->Size;
431d3190795SRafael Espindola   }
432d3190795SRafael Espindola }
43397403d15SEugene Leviant 
434d3190795SRafael Espindola template <class ELFT>
435e08e78dfSRafael Espindola void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
436d3190795SRafael Espindola   if (CurOutSec == Sec)
437d3190795SRafael Espindola     return;
438d3190795SRafael Espindola   if (AlreadyOutputOS.count(Sec))
439d3190795SRafael Espindola     return;
440d3190795SRafael Espindola 
441d3190795SRafael Espindola   flush();
442d3190795SRafael Espindola   CurOutSec = Sec;
443d3190795SRafael Espindola 
44404a2e348SRafael Espindola   Dot = alignTo(Dot, CurOutSec->Addralign);
445e08e78dfSRafael Espindola   CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
446b71d6f7aSEugene Leviant 
447b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
448b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
449b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
450b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
451b71d6f7aSEugene Leviant   CurOutSec->setLMAOffset(LMAOffset);
452d3190795SRafael Espindola }
453d3190795SRafael Espindola 
454d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
455e38cbab5SGeorge Rimar   // This handles the assignments to symbol or to a location counter (.)
456d3190795SRafael Espindola   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
45797403d15SEugene Leviant     if (AssignCmd->Name == ".") {
45897403d15SEugene Leviant       // Update to location counter means update to section size.
459d3190795SRafael Espindola       Dot = AssignCmd->Expression(Dot);
46004a2e348SRafael Espindola       CurOutSec->Size = Dot - CurOutSec->Addr;
461d3190795SRafael Espindola       return;
46297403d15SEugene Leviant     }
463afaa9343SEugene Leviant     assignSectionSymbol<ELFT>(AssignCmd, Dot);
464d3190795SRafael Espindola     return;
46597403d15SEugene Leviant   }
466e38cbab5SGeorge Rimar 
467e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
468e38cbab5SGeorge Rimar   if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
46904a2e348SRafael Espindola     DataCmd->Offset = Dot - CurOutSec->Addr;
470e38cbab5SGeorge Rimar     Dot += DataCmd->Size;
47104a2e348SRafael Espindola     CurOutSec->Size = Dot - CurOutSec->Addr;
472e38cbab5SGeorge Rimar     return;
473e38cbab5SGeorge Rimar   }
474e38cbab5SGeorge Rimar 
475e38cbab5SGeorge Rimar   // It handles single input section description command,
476e38cbab5SGeorge Rimar   // calculates and assigns the offsets for each section and also
477e38cbab5SGeorge Rimar   // updates the output section size.
478d3190795SRafael Espindola   auto &ICmd = cast<InputSectionDescription>(Base);
479d3190795SRafael Espindola   for (InputSectionData *ID : ICmd.Sections) {
480d3190795SRafael Espindola     auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
481d3190795SRafael Espindola     switchTo(IB->OutSec);
482d3190795SRafael Espindola     if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
483d3190795SRafael Espindola       output(I);
48465499b90SRafael Espindola     else
48565499b90SRafael Espindola       flush();
486ceabe80eSEugene Leviant   }
487ceabe80eSEugene Leviant }
488ceabe80eSEugene Leviant 
4898f66df92SGeorge Rimar template <class ELFT>
490e08e78dfSRafael Espindola static std::vector<OutputSectionBase *>
491e08e78dfSRafael Espindola findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
492e08e78dfSRafael Espindola   std::vector<OutputSectionBase *> Ret;
493e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : Sections)
4949257764dSEugene Leviant     if (Sec->getName() == Name)
495a14b13d8SGeorge Rimar       Ret.push_back(Sec);
496a14b13d8SGeorge Rimar   return Ret;
4978f66df92SGeorge Rimar }
4988f66df92SGeorge Rimar 
499d3190795SRafael Espindola template <class ELFT>
500d3190795SRafael Espindola void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
501b71d6f7aSEugene Leviant   if (Cmd->LMAExpr)
502b71d6f7aSEugene Leviant     LMAOffset = Cmd->LMAExpr(Dot) - Dot;
503e08e78dfSRafael Espindola   std::vector<OutputSectionBase *> Sections =
504e08e78dfSRafael Espindola       findSections<ELFT>(Cmd->Name, *OutputSections);
505d3190795SRafael Espindola   if (Sections.empty())
506d3190795SRafael Espindola     return;
507d3190795SRafael Espindola   switchTo(Sections[0]);
508d3190795SRafael Espindola   // Find the last section output location. We will output orphan sections
509d3190795SRafael Espindola   // there so that end symbols point to the correct location.
510d3190795SRafael Espindola   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
511d3190795SRafael Espindola                         [](const std::unique_ptr<BaseCommand> &Cmd) {
512d3190795SRafael Espindola                           return !isa<SymbolAssignment>(*Cmd);
513d3190795SRafael Espindola                         })
514d3190795SRafael Espindola                .base();
515d3190795SRafael Espindola   for (auto I = Cmd->Commands.begin(); I != E; ++I)
516d3190795SRafael Espindola     process(**I);
517e08e78dfSRafael Espindola   for (OutputSectionBase *Base : Sections)
518d3190795SRafael Espindola     switchTo(Base);
5192506cb4dSEugene Leviant   flush();
520b31dd370SGeorge Rimar   std::for_each(E, Cmd->Commands.end(),
521b31dd370SGeorge Rimar                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
522d3190795SRafael Espindola }
523d3190795SRafael Espindola 
52407fe6129SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
5256d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
5266d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
5276d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
5286d38e4dbSRafael Espindola   // clutter the output.
5296d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
5306d38e4dbSRafael Espindola   // more aggressive at removing them.
5316d38e4dbSRafael Espindola   auto Pos = std::remove_if(
5326d38e4dbSRafael Espindola       Opt.Commands.begin(), Opt.Commands.end(),
5336d38e4dbSRafael Espindola       [&](const std::unique_ptr<BaseCommand> &Base) {
5346d38e4dbSRafael Espindola         auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
5356d38e4dbSRafael Espindola         if (!Cmd)
5366d38e4dbSRafael Espindola           return false;
5376a53737cSRafael Espindola         return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
5386d38e4dbSRafael Espindola       });
5396d38e4dbSRafael Espindola   Opt.Commands.erase(Pos, Opt.Commands.end());
54007fe6129SRafael Espindola }
54107fe6129SRafael Espindola 
5426a53737cSRafael Espindola static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
5436a53737cSRafael Espindola   for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
5446a53737cSRafael Espindola     if (!isa<InputSectionDescription>(*I))
5456a53737cSRafael Espindola       return false;
5466a53737cSRafael Espindola   return true;
5476a53737cSRafael Espindola }
5486d38e4dbSRafael Espindola 
5496a53737cSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
5509546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
5519546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
5529546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
5539546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
5549546fffbSRafael Espindola   uintX_t Flags = SHF_ALLOC;
5559546fffbSRafael Espindola   uint32_t Type = 0;
5569546fffbSRafael Espindola   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
5579546fffbSRafael Espindola     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
5589546fffbSRafael Espindola     if (!Cmd)
5599546fffbSRafael Espindola       continue;
560e08e78dfSRafael Espindola     std::vector<OutputSectionBase *> Secs =
561e08e78dfSRafael Espindola         findSections<ELFT>(Cmd->Name, *OutputSections);
5629546fffbSRafael Espindola     if (!Secs.empty()) {
56304a2e348SRafael Espindola       Flags = Secs[0]->Flags;
56404a2e348SRafael Espindola       Type = Secs[0]->Type;
5659546fffbSRafael Espindola       continue;
5669546fffbSRafael Espindola     }
5679546fffbSRafael Espindola 
5686a53737cSRafael Espindola     if (isAllSectionDescription(*Cmd))
5696a53737cSRafael Espindola       continue;
5706a53737cSRafael Espindola 
57195642b95SRui Ueyama     auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
5729546fffbSRafael Espindola     OutputSections->push_back(OutSec);
5739546fffbSRafael Espindola   }
574f7a17448SRafael Espindola }
575f7a17448SRafael Espindola 
576f7a17448SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
577f7a17448SRafael Espindola   placeOrphanSections();
578f7a17448SRafael Espindola 
579f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
580f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
581f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
582f7a17448SRafael Espindola   // Below is an example of such linker script:
583f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
584f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
585f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
586f7a17448SRafael Espindola   auto FirstPtLoad =
587f7a17448SRafael Espindola       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
588f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
589f7a17448SRafael Espindola   if (FirstPtLoad != Opt.PhdrsCommands.end())
590f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
591f7a17448SRafael Espindola 
592f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
593f7a17448SRafael Espindola   // explicitly specify them.
594f7a17448SRafael Espindola   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
595f7a17448SRafael Espindola     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
596f7a17448SRafael Espindola     if (!Cmd)
597f7a17448SRafael Espindola       continue;
598f7a17448SRafael Espindola     if (Cmd->Phdrs.empty())
599f7a17448SRafael Espindola       Cmd->Phdrs = DefPhdrs;
600f7a17448SRafael Espindola     else
601f7a17448SRafael Espindola       DefPhdrs = Cmd->Phdrs;
602f7a17448SRafael Espindola   }
6036a53737cSRafael Espindola 
6046a53737cSRafael Espindola   removeEmptyCommands();
6059546fffbSRafael Espindola }
6069546fffbSRafael Espindola 
60715c57951SRafael Espindola // When placing orphan sections, we want to place them after symbol assignments
60815c57951SRafael Espindola // so that an orphan after
60915c57951SRafael Espindola //   begin_foo = .;
61015c57951SRafael Espindola //   foo : { *(foo) }
61115c57951SRafael Espindola //   end_foo = .;
61215c57951SRafael Espindola // doesn't break the intended meaning of the begin/end symbols.
61315c57951SRafael Espindola // We don't want to go over sections since Writer<ELFT>::sortSections is the
61415c57951SRafael Espindola // one in charge of deciding the order of the sections.
61515c57951SRafael Espindola // We don't want to go over alignments, since doing so in
61615c57951SRafael Espindola //  rx_sec : { *(rx_sec) }
61715c57951SRafael Espindola //  . = ALIGN(0x1000);
61815c57951SRafael Espindola //  /* The RW PT_LOAD starts here*/
61915c57951SRafael Espindola //  rw_sec : { *(rw_sec) }
62015c57951SRafael Espindola // would mean that the RW PT_LOAD would become unaligned.
62115c57951SRafael Espindola static bool shouldSkip(const BaseCommand &Cmd) {
62215c57951SRafael Espindola   if (isa<OutputSectionCommand>(Cmd))
62315c57951SRafael Espindola     return false;
62415c57951SRafael Espindola   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
62515c57951SRafael Espindola   if (!Assign)
62615c57951SRafael Espindola     return true;
62715c57951SRafael Espindola   return Assign->Name != ".";
62815c57951SRafael Espindola }
62915c57951SRafael Espindola 
630337f903cSRafael Espindola // Orphan sections are sections present in the input files which are not
631337f903cSRafael Espindola // explicitly placed into the output file by the linker script. This just
632337f903cSRafael Espindola // places them in the order already decided in OutputSections.
6336d91fce5SRafael Espindola template <class ELFT>
634337f903cSRafael Espindola void LinkerScript<ELFT>::placeOrphanSections() {
635aab6d5c5SRafael Espindola   // The OutputSections are already in the correct order.
636aab6d5c5SRafael Espindola   // This loops creates or moves commands as needed so that they are in the
637aab6d5c5SRafael Espindola   // correct order.
638aab6d5c5SRafael Espindola   int CmdIndex = 0;
639e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
640652852c5SGeorge Rimar     StringRef Name = Sec->getName();
641aab6d5c5SRafael Espindola 
642aab6d5c5SRafael Espindola     // Find the last spot where we can insert a command and still get the
64315c57951SRafael Espindola     // correct result.
644aab6d5c5SRafael Espindola     auto CmdIter = Opt.Commands.begin() + CmdIndex;
645aab6d5c5SRafael Espindola     auto E = Opt.Commands.end();
64615c57951SRafael Espindola     while (CmdIter != E && shouldSkip(**CmdIter)) {
647aab6d5c5SRafael Espindola       ++CmdIter;
648aab6d5c5SRafael Espindola       ++CmdIndex;
649aab6d5c5SRafael Espindola     }
650aab6d5c5SRafael Espindola 
651aab6d5c5SRafael Espindola     auto Pos =
652aab6d5c5SRafael Espindola         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
653aab6d5c5SRafael Espindola           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
654aab6d5c5SRafael Espindola           return Cmd && Cmd->Name == Name;
655aab6d5c5SRafael Espindola         });
656aab6d5c5SRafael Espindola     if (Pos == E) {
657aab6d5c5SRafael Espindola       Opt.Commands.insert(CmdIter,
658aab6d5c5SRafael Espindola                           llvm::make_unique<OutputSectionCommand>(Name));
659aab6d5c5SRafael Espindola       ++CmdIndex;
66015c57951SRafael Espindola       continue;
66115c57951SRafael Espindola     }
66215c57951SRafael Espindola 
66315c57951SRafael Espindola     // Continue from where we found it.
66415c57951SRafael Espindola     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
665652852c5SGeorge Rimar   }
666337f903cSRafael Espindola }
667337f903cSRafael Espindola 
668337f903cSRafael Espindola template <class ELFT>
669337f903cSRafael Espindola void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
6707c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
671be607334SRafael Espindola   Dot = 0;
672652852c5SGeorge Rimar 
673076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
674076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
6758d083e6aSRui Ueyama       if (Cmd->Name == ".") {
6768d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
6778d083e6aSRui Ueyama       } else if (Cmd->Sym) {
678afaa9343SEugene Leviant         assignSectionSymbol<ELFT>(Cmd, Dot);
6798d083e6aSRui Ueyama       }
68005ef4cffSRui Ueyama       continue;
681652852c5SGeorge Rimar     }
682652852c5SGeorge Rimar 
683eefa758eSGeorge Rimar     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
684eefa758eSGeorge Rimar       Cmd->Expression(Dot);
685eefa758eSGeorge Rimar       continue;
686eefa758eSGeorge Rimar     }
687eefa758eSGeorge Rimar 
688076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
689652852c5SGeorge Rimar 
69058e5c4dcSGeorge Rimar     if (Cmd->AddrExpr)
69158e5c4dcSGeorge Rimar       Dot = Cmd->AddrExpr(Dot);
69258e5c4dcSGeorge Rimar 
693d3190795SRafael Espindola     assignOffsets(Cmd);
694a14b13d8SGeorge Rimar   }
695467c4d55SEugene Leviant 
696aab6d5c5SRafael Espindola   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
697e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
69804a2e348SRafael Espindola     if (Sec->Flags & SHF_ALLOC)
699e08e78dfSRafael Espindola       MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
700aab6d5c5SRafael Espindola     else
70104a2e348SRafael Espindola       Sec->Addr = 0;
702aab6d5c5SRafael Espindola   }
703aab6d5c5SRafael Espindola 
7040d4b6d5cSRafael Espindola   uintX_t HeaderSize = getHeaderSize();
7056d91fce5SRafael Espindola   auto FirstPTLoad =
7066d91fce5SRafael Espindola       std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
7076d91fce5SRafael Espindola         return E.H.p_type == PT_LOAD;
7086d91fce5SRafael Espindola       });
709*d8b81d66SRafael Espindola   if (FirstPTLoad == Phdrs.end())
710*d8b81d66SRafael Espindola     return;
711db35fdf7SEugene Leviant 
712*d8b81d66SRafael Espindola   if (HeaderSize <= MinVA) {
713db35fdf7SEugene Leviant     // If linker script specifies program headers and first PT_LOAD doesn't
714db35fdf7SEugene Leviant     // have both PHDRS and FILEHDR attributes then do nothing
715db35fdf7SEugene Leviant     if (!Opt.PhdrsCommands.empty()) {
716db35fdf7SEugene Leviant       size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
717db35fdf7SEugene Leviant       if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
718db35fdf7SEugene Leviant           !Opt.PhdrsCommands[SegNum].HasFilehdr)
719db35fdf7SEugene Leviant         return;
720db35fdf7SEugene Leviant     }
72164c32d6fSRafael Espindola     // ELF and Program headers need to be right before the first section in
722b91e7118SGeorge Rimar     // memory. Set their addresses accordingly.
7234ec013acSRafael Espindola     MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
72404a2e348SRafael Espindola     Out<ELFT>::ElfHeader->Addr = MinVA;
72504a2e348SRafael Espindola     Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
7266d91fce5SRafael Espindola     FirstPTLoad->First = Out<ELFT>::ElfHeader;
7276d91fce5SRafael Espindola     if (!FirstPTLoad->Last)
7286d91fce5SRafael Espindola       FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
729cd8eaf89SEugene Leviant   } else if (!FirstPTLoad->First) {
730cd8eaf89SEugene Leviant     // Sometimes the very first PT_LOAD segment can be empty.
731cd8eaf89SEugene Leviant     // This happens if (all conditions met):
732cd8eaf89SEugene Leviant     //  - Linker script is used
733cd8eaf89SEugene Leviant     //  - First section in ELF image is not RO
734cd8eaf89SEugene Leviant     //  - Not enough space for program headers.
735cd8eaf89SEugene Leviant     // The code below removes empty PT_LOAD segment and updates
736cd8eaf89SEugene Leviant     // program headers size.
737cd8eaf89SEugene Leviant     Phdrs.erase(FirstPTLoad);
73804a2e348SRafael Espindola     Out<ELFT>::ProgramHeaders->Size =
73904a2e348SRafael Espindola         sizeof(typename ELFT::Phdr) * Phdrs.size();
7406d91fce5SRafael Espindola   }
741fb8978fcSDima Stepanov }
742652852c5SGeorge Rimar 
743464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
74407320e40SRui Ueyama template <class ELFT>
745a4b41dcaSRafael Espindola std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
746edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
747bbe38602SEugene Leviant 
748464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
749464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
750bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
751edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
752edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
753bbe38602SEugene Leviant 
754bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
755adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
756bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
757adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
75856b21c86SEugene Leviant 
75956b21c86SEugene Leviant     if (Cmd.LMAExpr) {
76056b21c86SEugene Leviant       Phdr.H.p_paddr = Cmd.LMAExpr(0);
76156b21c86SEugene Leviant       Phdr.HasLMA = true;
76256b21c86SEugene Leviant     }
763bbe38602SEugene Leviant   }
764bbe38602SEugene Leviant 
765464daadcSRui Ueyama   // Add output sections to program headers.
766e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
76704a2e348SRafael Espindola     if (!(Sec->Flags & SHF_ALLOC))
768bbe38602SEugene Leviant       break;
769bbe38602SEugene Leviant 
770bbe38602SEugene Leviant     // Assign headers specified by linker script
771f7a17448SRafael Espindola     for (size_t Id : getPhdrIndices(Sec->getName())) {
772edebbdf1SRui Ueyama       Ret[Id].add(Sec);
773865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
7740b113671SRafael Espindola         Ret[Id].H.p_flags |= Sec->getPhdrFlags();
775bbe38602SEugene Leviant     }
776bbe38602SEugene Leviant   }
777edebbdf1SRui Ueyama   return Ret;
778bbe38602SEugene Leviant }
779bbe38602SEugene Leviant 
780f9bc3bd2SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
781f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
782f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
783f9bc3bd2SEugene Leviant   return !Opt.PhdrsCommands.empty() &&
784f9bc3bd2SEugene Leviant          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
785f9bc3bd2SEugene Leviant            return Cmd.Type == PT_INTERP;
786f9bc3bd2SEugene Leviant          }) == Opt.PhdrsCommands.end();
787f9bc3bd2SEugene Leviant }
788f9bc3bd2SEugene Leviant 
789bbe38602SEugene Leviant template <class ELFT>
79007320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
791f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
792f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
793f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
794f6c3ccefSGeorge Rimar         return Cmd->Filler;
795e2ee72b5SGeorge Rimar   return {};
796e2ee72b5SGeorge Rimar }
797e2ee72b5SGeorge Rimar 
798e38cbab5SGeorge Rimar template <class ELFT>
799e38cbab5SGeorge Rimar static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
800e38cbab5SGeorge Rimar   const endianness E = ELFT::TargetEndianness;
801e38cbab5SGeorge Rimar 
802e38cbab5SGeorge Rimar   switch (Size) {
803e38cbab5SGeorge Rimar   case 1:
804e38cbab5SGeorge Rimar     *Buf = (uint8_t)Data;
805e38cbab5SGeorge Rimar     break;
806e38cbab5SGeorge Rimar   case 2:
807e38cbab5SGeorge Rimar     write16<E>(Buf, Data);
808e38cbab5SGeorge Rimar     break;
809e38cbab5SGeorge Rimar   case 4:
810e38cbab5SGeorge Rimar     write32<E>(Buf, Data);
811e38cbab5SGeorge Rimar     break;
812e38cbab5SGeorge Rimar   case 8:
813e38cbab5SGeorge Rimar     write64<E>(Buf, Data);
814e38cbab5SGeorge Rimar     break;
815e38cbab5SGeorge Rimar   default:
816e38cbab5SGeorge Rimar     llvm_unreachable("unsupported Size argument");
817e38cbab5SGeorge Rimar   }
818e38cbab5SGeorge Rimar }
819e38cbab5SGeorge Rimar 
820e38cbab5SGeorge Rimar template <class ELFT>
821e38cbab5SGeorge Rimar void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
822e38cbab5SGeorge Rimar   int I = getSectionIndex(Name);
823e38cbab5SGeorge Rimar   if (I == INT_MAX)
824e38cbab5SGeorge Rimar     return;
825e38cbab5SGeorge Rimar 
826e38cbab5SGeorge Rimar   OutputSectionCommand *Cmd =
827e38cbab5SGeorge Rimar       dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
828e38cbab5SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
829e38cbab5SGeorge Rimar     if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
830e38cbab5SGeorge Rimar       writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
831e38cbab5SGeorge Rimar }
832e38cbab5SGeorge Rimar 
833b71d6f7aSEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
8348ceadb38SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
8358ceadb38SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
836b71d6f7aSEugene Leviant       if (Cmd->LMAExpr && Cmd->Name == Name)
837b71d6f7aSEugene Leviant         return true;
838b71d6f7aSEugene Leviant   return false;
8398ceadb38SGeorge Rimar }
8408ceadb38SGeorge Rimar 
841c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
842c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
843c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
844c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
845076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
846f510fa6bSRui Ueyama   int I = 0;
847f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
848076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
849076fe157SGeorge Rimar       if (Cmd->Name == Name)
850f510fa6bSRui Ueyama         return I;
851f510fa6bSRui Ueyama     ++I;
852f510fa6bSRui Ueyama   }
853f510fa6bSRui Ueyama   return INT_MAX;
85471b26e94SGeorge Rimar }
85571b26e94SGeorge Rimar 
856bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
857bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
858bbe38602SEugene Leviant }
859bbe38602SEugene Leviant 
8609e69450eSGeorge Rimar template <class ELFT>
861afaa9343SEugene Leviant const OutputSectionBase *LinkerScript<ELFT>::getOutputSection(StringRef Name) {
862afaa9343SEugene Leviant   static OutputSectionBase FakeSec("", 0, 0);
86396659df0SGeorge Rimar 
864e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections)
865b71d6f7aSEugene Leviant     if (Sec->getName() == Name)
866afaa9343SEugene Leviant       return Sec;
867b71d6f7aSEugene Leviant   error("undefined section " + Name);
868afaa9343SEugene Leviant   return &FakeSec;
86936fac7f0SEugene Leviant }
87036fac7f0SEugene Leviant 
871884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
8720d4b6d5cSRafael Espindola   return elf::getHeaderSize<ELFT>();
873e32a3598SGeorge Rimar }
874e32a3598SGeorge Rimar 
875884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
876884e786dSGeorge Rimar   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
877884e786dSGeorge Rimar     return B->getVA<ELFT>();
878884e786dSGeorge Rimar   error("symbol not found: " + S);
879884e786dSGeorge Rimar   return 0;
880884e786dSGeorge Rimar }
881884e786dSGeorge Rimar 
882f34f45fdSGeorge Rimar template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
883f34f45fdSGeorge Rimar   return Symtab<ELFT>::X->find(S) != nullptr;
884f34f45fdSGeorge Rimar }
885f34f45fdSGeorge Rimar 
8862f831dcaSRafael Espindola template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
8872f831dcaSRafael Espindola   SymbolBody *Sym = Symtab<ELFT>::X->find(S);
8882f831dcaSRafael Espindola   auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
8892f831dcaSRafael Espindola   return DR && !DR->Section;
8902f831dcaSRafael Espindola }
8912f831dcaSRafael Espindola 
892afaa9343SEugene Leviant // Gets section symbol belongs to. Symbol "." doesn't belong to any
893afaa9343SEugene Leviant // specific section but isn't absolute at the same time, so we try
894afaa9343SEugene Leviant // to find suitable section for it as well.
895afaa9343SEugene Leviant template <class ELFT>
896afaa9343SEugene Leviant const OutputSectionBase *LinkerScript<ELFT>::getSymbolSection(StringRef S) {
897afaa9343SEugene Leviant   SymbolBody *Sym = Symtab<ELFT>::X->find(S);
898afaa9343SEugene Leviant   if (!Sym) {
899afaa9343SEugene Leviant     if (OutputSections->empty())
900afaa9343SEugene Leviant       return nullptr;
901afaa9343SEugene Leviant     return CurOutSec ? CurOutSec : (*OutputSections)[0];
902afaa9343SEugene Leviant   }
903afaa9343SEugene Leviant 
904afaa9343SEugene Leviant   if (auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym))
905afaa9343SEugene Leviant     return DR->Section ? DR->Section->OutSec : nullptr;
906afaa9343SEugene Leviant   if (auto *DS = dyn_cast_or_null<DefinedSynthetic<ELFT>>(Sym))
907afaa9343SEugene Leviant     return DS->Section;
908afaa9343SEugene Leviant 
909afaa9343SEugene Leviant   return nullptr;
910afaa9343SEugene Leviant }
911afaa9343SEugene Leviant 
912bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
913bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
914bbe38602SEugene Leviant // PHDRS {} script block.
915bbe38602SEugene Leviant template <class ELFT>
916edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
917076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
918076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
919edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
92031d842f5SGeorge Rimar       continue;
92131d842f5SGeorge Rimar 
92229c5a2a9SRui Ueyama     std::vector<size_t> Ret;
92329c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
92429c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
92529c5a2a9SRui Ueyama     return Ret;
926bbe38602SEugene Leviant   }
92731d842f5SGeorge Rimar   return {};
92831d842f5SGeorge Rimar }
929bbe38602SEugene Leviant 
93029c5a2a9SRui Ueyama template <class ELFT>
93129c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
93229c5a2a9SRui Ueyama   size_t I = 0;
93329c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
93429c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
93529c5a2a9SRui Ueyama       return I;
93629c5a2a9SRui Ueyama     ++I;
93729c5a2a9SRui Ueyama   }
93829c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
93929c5a2a9SRui Ueyama   return 0;
94029c5a2a9SRui Ueyama }
94129c5a2a9SRui Ueyama 
94207320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
943c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
944c3794e58SGeorge Rimar 
945f7c5fbb1SRui Ueyama public:
94607320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
947f23b2320SGeorge Rimar 
94820b6598cSGeorge Rimar   void readLinkerScript();
94920b6598cSGeorge Rimar   void readVersionScript();
950f7c5fbb1SRui Ueyama 
951f7c5fbb1SRui Ueyama private:
95252a1509eSRui Ueyama   void addFile(StringRef Path);
95352a1509eSRui Ueyama 
954f7c5fbb1SRui Ueyama   void readAsNeeded();
95590c5099eSDenis Protivensky   void readEntry();
95683f406cfSGeorge Rimar   void readExtern();
957f7c5fbb1SRui Ueyama   void readGroup();
95831aa1f83SRui Ueyama   void readInclude();
959ee59282bSRui Ueyama   void readOutput();
9609159ce93SDavide Italiano   void readOutputArch();
961f7c5fbb1SRui Ueyama   void readOutputFormat();
962bbe38602SEugene Leviant   void readPhdrs();
96368a39a65SDavide Italiano   void readSearchDir();
9648e3b38abSDenis Protivensky   void readSections();
96595769b4aSRui Ueyama   void readVersion();
96695769b4aSRui Ueyama   void readVersionScriptCommand();
9678e3b38abSDenis Protivensky 
968113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
969e38cbab5SGeorge Rimar   BytesDataCommand *readBytesDataCommand(StringRef Tok);
970ff1f29e0SGeorge Rimar   std::vector<uint8_t> readFill();
97110416564SRui Ueyama   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
972ff1f29e0SGeorge Rimar   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
973bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
974a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionDescription(StringRef Tok);
975db688454SEugene Leviant   StringMatcher readFilePatterns();
97607171f21SGeorge Rimar   std::vector<SectionPattern> readInputSectionsList();
977a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
978bbe38602SEugene Leviant   unsigned readPhdrType();
979be394db3SGeorge Rimar   SortSectionPolicy readSortKind();
980a35e39caSPetr Hosek   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
981c96da110SRafael Espindola   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
98203fc010eSGeorge Rimar   void readSort();
983eefa758eSGeorge Rimar   Expr readAssert();
984708019c4SRui Ueyama 
985708019c4SRui Ueyama   Expr readExpr();
986708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
987b71d6f7aSEugene Leviant   StringRef readParenLiteral();
988708019c4SRui Ueyama   Expr readPrimary();
989708019c4SRui Ueyama   Expr readTernary(Expr Cond);
9906ad7dfccSRui Ueyama   Expr readParenExpr();
991f7c5fbb1SRui Ueyama 
99220b6598cSGeorge Rimar   // For parsing version script.
9932a00b846SRui Ueyama   void readVersionExtern(std::vector<SymbolVersion> *Globals);
99495769b4aSRui Ueyama   void readVersionDeclaration(StringRef VerStr);
99520b6598cSGeorge Rimar   void readGlobal(StringRef VerStr);
996bb6c01e7SGeorge Rimar   void readLocal(StringRef VerStr);
997e0fc2421SGeorge Rimar   void readSymbols(std::vector<SymbolVersion> &V);
99820b6598cSGeorge Rimar 
99907320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
100016b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
1001f7c5fbb1SRui Ueyama };
1002f7c5fbb1SRui Ueyama 
100320b6598cSGeorge Rimar void ScriptParser::readVersionScript() {
100495769b4aSRui Ueyama   readVersionScriptCommand();
100520b6598cSGeorge Rimar   if (!atEOF())
100695769b4aSRui Ueyama     setError("EOF expected, but got " + next());
100795769b4aSRui Ueyama }
100895769b4aSRui Ueyama 
100995769b4aSRui Ueyama void ScriptParser::readVersionScriptCommand() {
101083043f23SRui Ueyama   if (consume("{")) {
101195769b4aSRui Ueyama     readVersionDeclaration("");
101220b6598cSGeorge Rimar     return;
101320b6598cSGeorge Rimar   }
101420b6598cSGeorge Rimar 
101595769b4aSRui Ueyama   while (!atEOF() && !Error && peek() != "}") {
101620b6598cSGeorge Rimar     StringRef VerStr = next();
101720b6598cSGeorge Rimar     if (VerStr == "{") {
101895769b4aSRui Ueyama       setError("anonymous version definition is used in "
101995769b4aSRui Ueyama                "combination with other version definitions");
102020b6598cSGeorge Rimar       return;
102120b6598cSGeorge Rimar     }
102220b6598cSGeorge Rimar     expect("{");
102395769b4aSRui Ueyama     readVersionDeclaration(VerStr);
102420b6598cSGeorge Rimar   }
102520b6598cSGeorge Rimar }
102620b6598cSGeorge Rimar 
102795769b4aSRui Ueyama void ScriptParser::readVersion() {
102895769b4aSRui Ueyama   expect("{");
102995769b4aSRui Ueyama   readVersionScriptCommand();
103095769b4aSRui Ueyama   expect("}");
103195769b4aSRui Ueyama }
103295769b4aSRui Ueyama 
103320b6598cSGeorge Rimar void ScriptParser::readLinkerScript() {
1034f7c5fbb1SRui Ueyama   while (!atEOF()) {
1035f7c5fbb1SRui Ueyama     StringRef Tok = next();
1036a27eeccaSRui Ueyama     if (Tok == ";")
1037a27eeccaSRui Ueyama       continue;
1038a27eeccaSRui Ueyama 
103920d03194SEugene Leviant     if (Tok == "ASSERT") {
104020d03194SEugene Leviant       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
104120d03194SEugene Leviant     } else if (Tok == "ENTRY") {
1042a27eeccaSRui Ueyama       readEntry();
1043a27eeccaSRui Ueyama     } else if (Tok == "EXTERN") {
1044a27eeccaSRui Ueyama       readExtern();
1045a27eeccaSRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
1046a27eeccaSRui Ueyama       readGroup();
1047a27eeccaSRui Ueyama     } else if (Tok == "INCLUDE") {
1048a27eeccaSRui Ueyama       readInclude();
1049a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT") {
1050a27eeccaSRui Ueyama       readOutput();
1051a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
1052a27eeccaSRui Ueyama       readOutputArch();
1053a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
1054a27eeccaSRui Ueyama       readOutputFormat();
1055a27eeccaSRui Ueyama     } else if (Tok == "PHDRS") {
1056a27eeccaSRui Ueyama       readPhdrs();
1057a27eeccaSRui Ueyama     } else if (Tok == "SEARCH_DIR") {
1058a27eeccaSRui Ueyama       readSearchDir();
1059a27eeccaSRui Ueyama     } else if (Tok == "SECTIONS") {
1060a27eeccaSRui Ueyama       readSections();
1061a27eeccaSRui Ueyama     } else if (Tok == "VERSION") {
1062a27eeccaSRui Ueyama       readVersion();
1063c96da110SRafael Espindola     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
10640df80befSPetr Hosek       Opt.Commands.emplace_back(Cmd);
1065e5d3ca50SPetr Hosek     } else {
10665761042dSGeorge Rimar       setError("unknown directive: " + Tok);
1067f7c5fbb1SRui Ueyama     }
1068f7c5fbb1SRui Ueyama   }
1069e5d3ca50SPetr Hosek }
1070f7c5fbb1SRui Ueyama 
1071717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
107216b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
10735af1687fSJustin Bogner     SmallString<128> PathData;
10745af1687fSJustin Bogner     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
107516b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
10765af1687fSJustin Bogner       Driver->addFile(Saver.save(Path));
107716b0cc9eSSimon Atanasyan       return;
107816b0cc9eSSimon Atanasyan     }
107916b0cc9eSSimon Atanasyan   }
108016b0cc9eSSimon Atanasyan 
1081f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
108252a1509eSRui Ueyama     Driver->addFile(S);
108352a1509eSRui Ueyama   } else if (S.startswith("=")) {
108452a1509eSRui Ueyama     if (Config->Sysroot.empty())
108552a1509eSRui Ueyama       Driver->addFile(S.substr(1));
108652a1509eSRui Ueyama     else
108752a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
108852a1509eSRui Ueyama   } else if (S.startswith("-l")) {
108921eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
1090a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
1091a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
109252a1509eSRui Ueyama   } else {
109352a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
109452a1509eSRui Ueyama     if (Path.empty())
1095777f9630SGeorge Rimar       setError("unable to find " + S);
1096025d59b1SRui Ueyama     else
109752a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
109852a1509eSRui Ueyama   }
109952a1509eSRui Ueyama }
110052a1509eSRui Ueyama 
1101717677afSRui Ueyama void ScriptParser::readAsNeeded() {
1102f7c5fbb1SRui Ueyama   expect("(");
110335da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
110435da9b6eSRui Ueyama   Config->AsNeeded = true;
110583043f23SRui Ueyama   while (!Error && !consume(")"))
1106cd574a5eSGeorge Rimar     addFile(unquote(next()));
110735da9b6eSRui Ueyama   Config->AsNeeded = Orig;
1108f7c5fbb1SRui Ueyama }
1109f7c5fbb1SRui Ueyama 
1110717677afSRui Ueyama void ScriptParser::readEntry() {
111190c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
111290c5099eSDenis Protivensky   expect("(");
111390c5099eSDenis Protivensky   StringRef Tok = next();
111490c5099eSDenis Protivensky   if (Config->Entry.empty())
111590c5099eSDenis Protivensky     Config->Entry = Tok;
111690c5099eSDenis Protivensky   expect(")");
111790c5099eSDenis Protivensky }
111890c5099eSDenis Protivensky 
1119717677afSRui Ueyama void ScriptParser::readExtern() {
112083f406cfSGeorge Rimar   expect("(");
112183043f23SRui Ueyama   while (!Error && !consume(")"))
1122a2acc931SRui Ueyama     Config->Undefined.push_back(next());
112383f406cfSGeorge Rimar }
112483f406cfSGeorge Rimar 
1125717677afSRui Ueyama void ScriptParser::readGroup() {
1126f7c5fbb1SRui Ueyama   expect("(");
112783043f23SRui Ueyama   while (!Error && !consume(")")) {
1128f7c5fbb1SRui Ueyama     StringRef Tok = next();
1129a2acc931SRui Ueyama     if (Tok == "AS_NEEDED")
1130f7c5fbb1SRui Ueyama       readAsNeeded();
1131a2acc931SRui Ueyama     else
1132cd574a5eSGeorge Rimar       addFile(unquote(Tok));
1133f7c5fbb1SRui Ueyama   }
1134f7c5fbb1SRui Ueyama }
1135f7c5fbb1SRui Ueyama 
1136717677afSRui Ueyama void ScriptParser::readInclude() {
113731aa1f83SRui Ueyama   StringRef Tok = next();
1138cd574a5eSGeorge Rimar   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
1139025d59b1SRui Ueyama   if (!MBOrErr) {
11405761042dSGeorge Rimar     setError("cannot open " + Tok);
1141025d59b1SRui Ueyama     return;
1142025d59b1SRui Ueyama   }
114331aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
1144a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1145a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
114631aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
114731aa1f83SRui Ueyama }
114831aa1f83SRui Ueyama 
1149717677afSRui Ueyama void ScriptParser::readOutput() {
1150ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
1151ee59282bSRui Ueyama   expect("(");
1152ee59282bSRui Ueyama   StringRef Tok = next();
1153ee59282bSRui Ueyama   if (Config->OutputFile.empty())
1154cd574a5eSGeorge Rimar     Config->OutputFile = unquote(Tok);
1155ee59282bSRui Ueyama   expect(")");
1156ee59282bSRui Ueyama }
1157ee59282bSRui Ueyama 
1158717677afSRui Ueyama void ScriptParser::readOutputArch() {
11599159ce93SDavide Italiano   // Error checking only for now.
11609159ce93SDavide Italiano   expect("(");
11615424e7c7SJustin Bogner   skip();
11629159ce93SDavide Italiano   expect(")");
11639159ce93SDavide Italiano }
11649159ce93SDavide Italiano 
1165717677afSRui Ueyama void ScriptParser::readOutputFormat() {
1166f7c5fbb1SRui Ueyama   // Error checking only for now.
1167f7c5fbb1SRui Ueyama   expect("(");
11685424e7c7SJustin Bogner   skip();
11696836c618SDavide Italiano   StringRef Tok = next();
11706836c618SDavide Italiano   if (Tok == ")")
11716836c618SDavide Italiano     return;
1172025d59b1SRui Ueyama   if (Tok != ",") {
11735761042dSGeorge Rimar     setError("unexpected token: " + Tok);
1174025d59b1SRui Ueyama     return;
1175025d59b1SRui Ueyama   }
11765424e7c7SJustin Bogner   skip();
11776836c618SDavide Italiano   expect(",");
11785424e7c7SJustin Bogner   skip();
1179f7c5fbb1SRui Ueyama   expect(")");
1180f7c5fbb1SRui Ueyama }
1181f7c5fbb1SRui Ueyama 
1182bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
1183bbe38602SEugene Leviant   expect("{");
118483043f23SRui Ueyama   while (!Error && !consume("}")) {
1185bbe38602SEugene Leviant     StringRef Tok = next();
118656b21c86SEugene Leviant     Opt.PhdrsCommands.push_back(
118756b21c86SEugene Leviant         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1188bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1189bbe38602SEugene Leviant 
1190bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
1191bbe38602SEugene Leviant     do {
1192bbe38602SEugene Leviant       Tok = next();
1193bbe38602SEugene Leviant       if (Tok == ";")
1194bbe38602SEugene Leviant         break;
1195bbe38602SEugene Leviant       if (Tok == "FILEHDR")
1196bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
1197bbe38602SEugene Leviant       else if (Tok == "PHDRS")
1198bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
119956b21c86SEugene Leviant       else if (Tok == "AT")
120056b21c86SEugene Leviant         PhdrCmd.LMAExpr = readParenExpr();
1201865bf863SEugene Leviant       else if (Tok == "FLAGS") {
1202865bf863SEugene Leviant         expect("(");
1203eb685cd7SRafael Espindola         // Passing 0 for the value of dot is a bit of a hack. It means that
1204eb685cd7SRafael Espindola         // we accept expressions like ".|1".
1205eb685cd7SRafael Espindola         PhdrCmd.Flags = readExpr()(0);
1206865bf863SEugene Leviant         expect(")");
1207865bf863SEugene Leviant       } else
1208bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
1209bbe38602SEugene Leviant     } while (!Error);
1210bbe38602SEugene Leviant   }
1211bbe38602SEugene Leviant }
1212bbe38602SEugene Leviant 
1213717677afSRui Ueyama void ScriptParser::readSearchDir() {
121468a39a65SDavide Italiano   expect("(");
121586c5fb82SRui Ueyama   StringRef Tok = next();
12166c7ad13fSRui Ueyama   if (!Config->Nostdlib)
1217cd574a5eSGeorge Rimar     Config->SearchPaths.push_back(unquote(Tok));
121868a39a65SDavide Italiano   expect(")");
121968a39a65SDavide Italiano }
122068a39a65SDavide Italiano 
1221717677afSRui Ueyama void ScriptParser::readSections() {
1222e05336ffSEugene Leviant   Opt.HasSections = true;
12238e3b38abSDenis Protivensky   expect("{");
122483043f23SRui Ueyama   while (!Error && !consume("}")) {
1225113cdec9SRui Ueyama     StringRef Tok = next();
1226c96da110SRafael Espindola     BaseCommand *Cmd = readProvideOrAssignment(Tok);
1227ceabe80eSEugene Leviant     if (!Cmd) {
1228ceabe80eSEugene Leviant       if (Tok == "ASSERT")
1229eefa758eSGeorge Rimar         Cmd = new AssertCommand(readAssert());
1230ceabe80eSEugene Leviant       else
123110416564SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
12328e3b38abSDenis Protivensky     }
123310416564SRui Ueyama     Opt.Commands.emplace_back(Cmd);
1234652852c5SGeorge Rimar   }
1235708019c4SRui Ueyama }
12368e3b38abSDenis Protivensky 
1237708019c4SRui Ueyama static int precedence(StringRef Op) {
1238708019c4SRui Ueyama   return StringSwitch<int>(Op)
12390120e3f2SRui Ueyama       .Cases("*", "/", 5)
12400120e3f2SRui Ueyama       .Cases("+", "-", 4)
12410120e3f2SRui Ueyama       .Cases("<<", ">>", 3)
12429c4ac5f2SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
12430120e3f2SRui Ueyama       .Cases("&", "|", 1)
1244708019c4SRui Ueyama       .Default(-1);
1245708019c4SRui Ueyama }
1246708019c4SRui Ueyama 
1247db688454SEugene Leviant StringMatcher ScriptParser::readFilePatterns() {
124810416564SRui Ueyama   std::vector<StringRef> V;
124983043f23SRui Ueyama   while (!Error && !consume(")"))
125010416564SRui Ueyama     V.push_back(next());
1251f91282e1SRui Ueyama   return StringMatcher(V);
12520702c4e8SGeorge Rimar }
12530702c4e8SGeorge Rimar 
1254be394db3SGeorge Rimar SortSectionPolicy ScriptParser::readSortKind() {
125583043f23SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
1256be394db3SGeorge Rimar     return SortSectionPolicy::Name;
125783043f23SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
1258be394db3SGeorge Rimar     return SortSectionPolicy::Alignment;
125983043f23SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
1260be394db3SGeorge Rimar     return SortSectionPolicy::Priority;
126183043f23SRui Ueyama   if (consume("SORT_NONE"))
1262be394db3SGeorge Rimar     return SortSectionPolicy::None;
1263b2a0abdfSRui Ueyama   return SortSectionPolicy::Default;
1264be394db3SGeorge Rimar }
1265be394db3SGeorge Rimar 
1266395281cfSGeorge Rimar // Method reads a list of sequence of excluded files and section globs given in
1267395281cfSGeorge Rimar // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1268395281cfSGeorge Rimar // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1269af03be19SGeorge Rimar // The semantics of that is next:
1270af03be19SGeorge Rimar // * Include .foo.1 from every file.
1271af03be19SGeorge Rimar // * Include .foo.2 from every file but a.o
1272af03be19SGeorge Rimar // * Include .foo.3 from every file but b.o
127307171f21SGeorge Rimar std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
127407171f21SGeorge Rimar   std::vector<SectionPattern> Ret;
1275601e9898SGeorge Rimar   while (!Error && peek() != ")") {
1276f91282e1SRui Ueyama     StringMatcher ExcludeFilePat;
127783043f23SRui Ueyama     if (consume("EXCLUDE_FILE")) {
1278395281cfSGeorge Rimar       expect("(");
1279f91282e1SRui Ueyama       ExcludeFilePat = readFilePatterns();
1280395281cfSGeorge Rimar     }
1281395281cfSGeorge Rimar 
1282601e9898SGeorge Rimar     std::vector<StringRef> V;
1283601e9898SGeorge Rimar     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1284395281cfSGeorge Rimar       V.push_back(next());
1285601e9898SGeorge Rimar 
1286601e9898SGeorge Rimar     if (!V.empty())
1287f91282e1SRui Ueyama       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
1288601e9898SGeorge Rimar     else
1289601e9898SGeorge Rimar       setError("section pattern is expected");
1290395281cfSGeorge Rimar   }
129107171f21SGeorge Rimar   return Ret;
1292395281cfSGeorge Rimar }
1293395281cfSGeorge Rimar 
129407171f21SGeorge Rimar // Section pattern grammar can have complex expressions, for example:
129507171f21SGeorge Rimar // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
129607171f21SGeorge Rimar // Generally is a sequence of globs and excludes that may be wrapped in a SORT()
129707171f21SGeorge Rimar // commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
129807171f21SGeorge Rimar // This methods handles wrapping sequences of excluded files and section globs
129907171f21SGeorge Rimar // into SORT() if that needed and reads them all.
1300a2496cbeSGeorge Rimar InputSectionDescription *
1301a2496cbeSGeorge Rimar ScriptParser::readInputSectionRules(StringRef FilePattern) {
1302c91930a1SGeorge Rimar   auto *Cmd = new InputSectionDescription(FilePattern);
13030ed42b0cSDavide Italiano   expect("(");
130483043f23SRui Ueyama   while (!HasError && !consume(")")) {
130507171f21SGeorge Rimar     SortSectionPolicy Outer = readSortKind();
130607171f21SGeorge Rimar     SortSectionPolicy Inner = SortSectionPolicy::Default;
130707171f21SGeorge Rimar     std::vector<SectionPattern> V;
130807171f21SGeorge Rimar     if (Outer != SortSectionPolicy::Default) {
13090702c4e8SGeorge Rimar       expect("(");
131007171f21SGeorge Rimar       Inner = readSortKind();
131107171f21SGeorge Rimar       if (Inner != SortSectionPolicy::Default) {
1312350ece4eSGeorge Rimar         expect("(");
131307171f21SGeorge Rimar         V = readInputSectionsList();
13140702c4e8SGeorge Rimar         expect(")");
1315350ece4eSGeorge Rimar       } else {
131607171f21SGeorge Rimar         V = readInputSectionsList();
1317350ece4eSGeorge Rimar       }
1318350ece4eSGeorge Rimar       expect(")");
131907171f21SGeorge Rimar     } else {
132007171f21SGeorge Rimar       V = readInputSectionsList();
13210659800eSGeorge Rimar     }
13220702c4e8SGeorge Rimar 
132307171f21SGeorge Rimar     for (SectionPattern &Pat : V) {
132407171f21SGeorge Rimar       Pat.SortInner = Inner;
132507171f21SGeorge Rimar       Pat.SortOuter = Outer;
132607171f21SGeorge Rimar     }
132707171f21SGeorge Rimar 
132807171f21SGeorge Rimar     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
132907171f21SGeorge Rimar   }
133010416564SRui Ueyama   return Cmd;
13310659800eSGeorge Rimar }
13320659800eSGeorge Rimar 
1333a2496cbeSGeorge Rimar InputSectionDescription *
1334a2496cbeSGeorge Rimar ScriptParser::readInputSectionDescription(StringRef Tok) {
13350659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
13360659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1337a2496cbeSGeorge Rimar   if (Tok == "KEEP") {
1338e7282797SDavide Italiano     expect("(");
1339a2496cbeSGeorge Rimar     StringRef FilePattern = next();
1340a2496cbeSGeorge Rimar     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
13410ed42b0cSDavide Italiano     expect(")");
1342cf43f179SEugene Leviant     Opt.KeptSections.push_back(Cmd);
134310416564SRui Ueyama     return Cmd;
134410416564SRui Ueyama   }
1345a2496cbeSGeorge Rimar   return readInputSectionRules(Tok);
13460659800eSGeorge Rimar }
13470659800eSGeorge Rimar 
134803fc010eSGeorge Rimar void ScriptParser::readSort() {
134903fc010eSGeorge Rimar   expect("(");
135003fc010eSGeorge Rimar   expect("CONSTRUCTORS");
135103fc010eSGeorge Rimar   expect(")");
135203fc010eSGeorge Rimar }
135303fc010eSGeorge Rimar 
1354eefa758eSGeorge Rimar Expr ScriptParser::readAssert() {
1355eefa758eSGeorge Rimar   expect("(");
1356eefa758eSGeorge Rimar   Expr E = readExpr();
1357eefa758eSGeorge Rimar   expect(",");
1358cd574a5eSGeorge Rimar   StringRef Msg = unquote(next());
1359eefa758eSGeorge Rimar   expect(")");
1360eefa758eSGeorge Rimar   return [=](uint64_t Dot) {
1361eefa758eSGeorge Rimar     uint64_t V = E(Dot);
1362eefa758eSGeorge Rimar     if (!V)
1363eefa758eSGeorge Rimar       error(Msg);
1364eefa758eSGeorge Rimar     return V;
1365eefa758eSGeorge Rimar   };
1366eefa758eSGeorge Rimar }
1367eefa758eSGeorge Rimar 
136825150e8bSRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
136925150e8bSRui Ueyama // alias for =fillexp section attribute, which is different from
137025150e8bSRui Ueyama // what GNU linkers do.
137125150e8bSRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1372ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readFill() {
1373ff1f29e0SGeorge Rimar   expect("(");
1374ff1f29e0SGeorge Rimar   std::vector<uint8_t> V = readOutputSectionFiller(next());
1375ff1f29e0SGeorge Rimar   expect(")");
1376ff1f29e0SGeorge Rimar   expect(";");
1377ff1f29e0SGeorge Rimar   return V;
1378ff1f29e0SGeorge Rimar }
1379ff1f29e0SGeorge Rimar 
138010416564SRui Ueyama OutputSectionCommand *
138110416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1382076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
138358e5c4dcSGeorge Rimar 
138458e5c4dcSGeorge Rimar   // Read an address expression.
138558e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
138658e5c4dcSGeorge Rimar   if (peek() != ":")
138758e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
138858e5c4dcSGeorge Rimar 
13898e3b38abSDenis Protivensky   expect(":");
1390246f681eSDavide Italiano 
139183043f23SRui Ueyama   if (consume("AT"))
1392b71d6f7aSEugene Leviant     Cmd->LMAExpr = readParenExpr();
139383043f23SRui Ueyama   if (consume("ALIGN"))
13946ad7dfccSRui Ueyama     Cmd->AlignExpr = readParenExpr();
139583043f23SRui Ueyama   if (consume("SUBALIGN"))
1396db24d9c3SGeorge Rimar     Cmd->SubalignExpr = readParenExpr();
1397630c6179SGeorge Rimar 
1398246f681eSDavide Italiano   // Parse constraints.
139983043f23SRui Ueyama   if (consume("ONLY_IF_RO"))
1400efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
140183043f23SRui Ueyama   if (consume("ONLY_IF_RW"))
1402efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
14038e3b38abSDenis Protivensky   expect("{");
14048ec77e64SRui Ueyama 
140583043f23SRui Ueyama   while (!Error && !consume("}")) {
1406ceabe80eSEugene Leviant     StringRef Tok = next();
1407c96da110SRafael Espindola     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1408ceabe80eSEugene Leviant       Cmd->Commands.emplace_back(Assignment);
1409e38cbab5SGeorge Rimar     else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1410e38cbab5SGeorge Rimar       Cmd->Commands.emplace_back(Data);
1411ff1f29e0SGeorge Rimar     else if (Tok == "FILL")
1412ff1f29e0SGeorge Rimar       Cmd->Filler = readFill();
1413ceabe80eSEugene Leviant     else if (Tok == "SORT")
141403fc010eSGeorge Rimar       readSort();
1415a2496cbeSGeorge Rimar     else if (peek() == "(")
1416a2496cbeSGeorge Rimar       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1417ceabe80eSEugene Leviant     else
1418ceabe80eSEugene Leviant       setError("unknown command " + Tok);
14198e3b38abSDenis Protivensky   }
1420076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
14214ebc5620SGeorge Rimar 
142283043f23SRui Ueyama   if (consume("="))
14234ebc5620SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next());
14244ebc5620SGeorge Rimar   else if (peek().startswith("="))
1425ff1f29e0SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next().drop_front());
14264ebc5620SGeorge Rimar 
142710416564SRui Ueyama   return Cmd;
1428f71caa2bSRui Ueyama }
14298ec77e64SRui Ueyama 
14302c8f1f04SRui Ueyama // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
14312c8f1f04SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
14322c8f1f04SRui Ueyama //
14332c8f1f04SRui Ueyama // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
14342c8f1f04SRui Ueyama // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
14352c8f1f04SRui Ueyama // as 32-bit big-endian values. We will do the same as ld.gold does
14362c8f1f04SRui Ueyama // because it's simpler than what ld.bfd does.
1437ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1438965827d6SRui Ueyama   uint32_t V;
1439ff1f29e0SGeorge Rimar   if (Tok.getAsInteger(0, V)) {
1440965827d6SRui Ueyama     setError("invalid filler expression: " + Tok);
1441f71caa2bSRui Ueyama     return {};
1442e2ee72b5SGeorge Rimar   }
1443965827d6SRui Ueyama   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
14448e3b38abSDenis Protivensky }
14458e3b38abSDenis Protivensky 
1446a35e39caSPetr Hosek SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1447a31c91b1SEugene Leviant   expect("(");
1448174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
1449a35e39caSPetr Hosek   Cmd->Provide = Provide;
1450174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
1451a31c91b1SEugene Leviant   expect(")");
1452a31c91b1SEugene Leviant   expect(";");
145310416564SRui Ueyama   return Cmd;
1454eda81a1bSEugene Leviant }
1455eda81a1bSEugene Leviant 
1456c96da110SRafael Espindola SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1457ceabe80eSEugene Leviant   SymbolAssignment *Cmd = nullptr;
1458ceabe80eSEugene Leviant   if (peek() == "=" || peek() == "+=") {
1459ceabe80eSEugene Leviant     Cmd = readAssignment(Tok);
1460ceabe80eSEugene Leviant     expect(";");
1461ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE") {
1462a35e39caSPetr Hosek     Cmd = readProvideHidden(true, false);
1463a35e39caSPetr Hosek   } else if (Tok == "HIDDEN") {
1464a35e39caSPetr Hosek     Cmd = readProvideHidden(false, true);
1465ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE_HIDDEN") {
1466a35e39caSPetr Hosek     Cmd = readProvideHidden(true, true);
1467ceabe80eSEugene Leviant   }
1468ceabe80eSEugene Leviant   return Cmd;
1469ceabe80eSEugene Leviant }
1470ceabe80eSEugene Leviant 
147130835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
147230835ea4SGeorge Rimar   if (S == ".")
147330835ea4SGeorge Rimar     return Dot;
1474884e786dSGeorge Rimar   return ScriptBase->getSymbolValue(S);
1475e32a3598SGeorge Rimar }
1476e32a3598SGeorge Rimar 
14772f831dcaSRafael Espindola static bool isAbsolute(StringRef S) {
14782f831dcaSRafael Espindola   if (S == ".")
14792f831dcaSRafael Espindola     return false;
14802f831dcaSRafael Espindola   return ScriptBase->isAbsolute(S);
14812f831dcaSRafael Espindola }
14822f831dcaSRafael Espindola 
148330835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
148430835ea4SGeorge Rimar   StringRef Op = next();
1485db741e72SEugene Leviant   Expr E;
148630835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
148783043f23SRui Ueyama   if (consume("ABSOLUTE")) {
14887c1381a0SRui Ueyama     // The RHS may be something like "ABSOLUTE(.) & 0xff".
14897c1381a0SRui Ueyama     // Call readExpr1 to read the whole expression.
14907c1381a0SRui Ueyama     E = readExpr1(readParenExpr(), 0);
14912f831dcaSRafael Espindola     E.IsAbsolute = []() { return true; };
1492db741e72SEugene Leviant   } else {
1493db741e72SEugene Leviant     E = readExpr();
1494db741e72SEugene Leviant   }
149530835ea4SGeorge Rimar   if (Op == "+=")
149630835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1497f661393aSRafael Espindola   return new SymbolAssignment(Name, E);
149830835ea4SGeorge Rimar }
149930835ea4SGeorge Rimar 
150030835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
150130835ea4SGeorge Rimar // script expression.
150230835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
150330835ea4SGeorge Rimar 
150436c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
150536c1cd23SRui Ueyama   if (Op == "*")
150636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
150736c1cd23SRui Ueyama   if (Op == "/") {
150836c1cd23SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
150936c1cd23SRui Ueyama       uint64_t RHS = R(Dot);
151036c1cd23SRui Ueyama       if (RHS == 0) {
151136c1cd23SRui Ueyama         error("division by zero");
151236c1cd23SRui Ueyama         return 0;
151336c1cd23SRui Ueyama       }
151436c1cd23SRui Ueyama       return L(Dot) / RHS;
151536c1cd23SRui Ueyama     };
151636c1cd23SRui Ueyama   }
151736c1cd23SRui Ueyama   if (Op == "+")
15182f831dcaSRafael Espindola     return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1519afaa9343SEugene Leviant             [=]() { return L.IsAbsolute() && R.IsAbsolute(); },
1520afaa9343SEugene Leviant             [=]() {
1521afaa9343SEugene Leviant               const OutputSectionBase *S = L.Section();
1522afaa9343SEugene Leviant               return S ? S : R.Section();
1523afaa9343SEugene Leviant             }};
152436c1cd23SRui Ueyama   if (Op == "-")
152536c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1526c8ccd1f1SGeorge Rimar   if (Op == "<<")
1527c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1528c8ccd1f1SGeorge Rimar   if (Op == ">>")
1529c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
153036c1cd23SRui Ueyama   if (Op == "<")
153136c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
153236c1cd23SRui Ueyama   if (Op == ">")
153336c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
153436c1cd23SRui Ueyama   if (Op == ">=")
153536c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
153636c1cd23SRui Ueyama   if (Op == "<=")
153736c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
153836c1cd23SRui Ueyama   if (Op == "==")
153936c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
154036c1cd23SRui Ueyama   if (Op == "!=")
154136c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
154236c1cd23SRui Ueyama   if (Op == "&")
154336c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1544cc3dd629SRafael Espindola   if (Op == "|")
1545cc3dd629SRafael Espindola     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
154636c1cd23SRui Ueyama   llvm_unreachable("invalid operator");
154736c1cd23SRui Ueyama }
154836c1cd23SRui Ueyama 
1549708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
1550708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
1551708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1552708019c4SRui Ueyama   while (!atEOF() && !Error) {
1553708019c4SRui Ueyama     // Read an operator and an expression.
1554708019c4SRui Ueyama     StringRef Op1 = peek();
1555708019c4SRui Ueyama     if (Op1 == "?")
1556708019c4SRui Ueyama       return readTernary(Lhs);
1557708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
1558a31c91b1SEugene Leviant       break;
15595424e7c7SJustin Bogner     skip();
1560708019c4SRui Ueyama     Expr Rhs = readPrimary();
1561708019c4SRui Ueyama 
1562708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
1563708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
1564708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
1565708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
1566708019c4SRui Ueyama     while (!atEOF()) {
1567708019c4SRui Ueyama       StringRef Op2 = peek();
1568708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
1569eda81a1bSEugene Leviant         break;
1570708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
1571eda81a1bSEugene Leviant     }
1572708019c4SRui Ueyama 
1573708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
1574708019c4SRui Ueyama   }
1575708019c4SRui Ueyama   return Lhs;
1576708019c4SRui Ueyama }
1577708019c4SRui Ueyama 
1578708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
1579e2cc07bcSMichael J. Spencer   if (S == "COMMONPAGESIZE")
1580708019c4SRui Ueyama     return Target->PageSize;
1581e2cc07bcSMichael J. Spencer   if (S == "MAXPAGESIZE")
1582997f8838SPetr Hosek     return Config->MaxPageSize;
1583708019c4SRui Ueyama   error("unknown constant: " + S);
1584708019c4SRui Ueyama   return 0;
1585708019c4SRui Ueyama }
1586708019c4SRui Ueyama 
1587626e0b08SRui Ueyama // Parses Tok as an integer. Returns true if successful.
1588626e0b08SRui Ueyama // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1589626e0b08SRui Ueyama // and decimal numbers. Decimal numbers may have "K" (kilo) or
1590626e0b08SRui Ueyama // "M" (mega) prefixes.
15919f2f7ad9SGeorge Rimar static bool readInteger(StringRef Tok, uint64_t &Result) {
1592eaeafb2bSSimon Atanasyan   if (Tok.startswith("-")) {
1593eaeafb2bSSimon Atanasyan     if (!readInteger(Tok.substr(1), Result))
1594eaeafb2bSSimon Atanasyan       return false;
1595eaeafb2bSSimon Atanasyan     Result = -Result;
1596eaeafb2bSSimon Atanasyan     return true;
1597eaeafb2bSSimon Atanasyan   }
15989f2f7ad9SGeorge Rimar   if (Tok.startswith_lower("0x"))
15999f2f7ad9SGeorge Rimar     return !Tok.substr(2).getAsInteger(16, Result);
16009f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("H"))
16019f2f7ad9SGeorge Rimar     return !Tok.drop_back().getAsInteger(16, Result);
16029f2f7ad9SGeorge Rimar 
16039f2f7ad9SGeorge Rimar   int Suffix = 1;
16049f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("K")) {
16059f2f7ad9SGeorge Rimar     Suffix = 1024;
16069f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
16079f2f7ad9SGeorge Rimar   } else if (Tok.endswith_lower("M")) {
16089f2f7ad9SGeorge Rimar     Suffix = 1024 * 1024;
16099f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
16109f2f7ad9SGeorge Rimar   }
16119f2f7ad9SGeorge Rimar   if (Tok.getAsInteger(10, Result))
16129f2f7ad9SGeorge Rimar     return false;
16139f2f7ad9SGeorge Rimar   Result *= Suffix;
16149f2f7ad9SGeorge Rimar   return true;
16159f2f7ad9SGeorge Rimar }
16169f2f7ad9SGeorge Rimar 
1617e38cbab5SGeorge Rimar BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1618e38cbab5SGeorge Rimar   int Size = StringSwitch<unsigned>(Tok)
1619e38cbab5SGeorge Rimar                  .Case("BYTE", 1)
1620e38cbab5SGeorge Rimar                  .Case("SHORT", 2)
1621e38cbab5SGeorge Rimar                  .Case("LONG", 4)
1622e38cbab5SGeorge Rimar                  .Case("QUAD", 8)
1623e38cbab5SGeorge Rimar                  .Default(-1);
1624e38cbab5SGeorge Rimar   if (Size == -1)
1625e38cbab5SGeorge Rimar     return nullptr;
1626e38cbab5SGeorge Rimar 
1627e38cbab5SGeorge Rimar   expect("(");
1628e38cbab5SGeorge Rimar   uint64_t Val = 0;
1629e38cbab5SGeorge Rimar   StringRef S = next();
1630e38cbab5SGeorge Rimar   if (!readInteger(S, Val))
1631e38cbab5SGeorge Rimar     setError("unexpected value: " + S);
1632e38cbab5SGeorge Rimar   expect(")");
1633e38cbab5SGeorge Rimar   return new BytesDataCommand(Val, Size);
1634e38cbab5SGeorge Rimar }
1635e38cbab5SGeorge Rimar 
1636b71d6f7aSEugene Leviant StringRef ScriptParser::readParenLiteral() {
1637b71d6f7aSEugene Leviant   expect("(");
1638b71d6f7aSEugene Leviant   StringRef Tok = next();
1639b71d6f7aSEugene Leviant   expect(")");
1640b71d6f7aSEugene Leviant   return Tok;
1641b71d6f7aSEugene Leviant }
1642b71d6f7aSEugene Leviant 
1643708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
16446ad7dfccSRui Ueyama   if (peek() == "(")
16456ad7dfccSRui Ueyama     return readParenExpr();
1646708019c4SRui Ueyama 
16476ad7dfccSRui Ueyama   StringRef Tok = next();
1648708019c4SRui Ueyama 
1649eaeafb2bSSimon Atanasyan   if (Tok == "~") {
1650eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1651eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return ~E(Dot); };
1652eaeafb2bSSimon Atanasyan   }
1653eaeafb2bSSimon Atanasyan   if (Tok == "-") {
1654eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1655eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return -E(Dot); };
1656eaeafb2bSSimon Atanasyan   }
1657eaeafb2bSSimon Atanasyan 
1658708019c4SRui Ueyama   // Built-in functions are parsed here.
1659708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
166096659df0SGeorge Rimar   if (Tok == "ADDR") {
1661b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1662afaa9343SEugene Leviant     return {
1663afaa9343SEugene Leviant         [=](uint64_t Dot) { return ScriptBase->getOutputSection(Name)->Addr; },
1664afaa9343SEugene Leviant         [=]() { return false; },
1665afaa9343SEugene Leviant         [=]() { return ScriptBase->getOutputSection(Name); }};
166696659df0SGeorge Rimar   }
1667b71d6f7aSEugene Leviant   if (Tok == "LOADADDR") {
1668b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1669afaa9343SEugene Leviant     return [=](uint64_t Dot) {
1670afaa9343SEugene Leviant       return ScriptBase->getOutputSection(Name)->getLMA();
1671afaa9343SEugene Leviant     };
1672b71d6f7aSEugene Leviant   }
1673eefa758eSGeorge Rimar   if (Tok == "ASSERT")
1674eefa758eSGeorge Rimar     return readAssert();
1675708019c4SRui Ueyama   if (Tok == "ALIGN") {
16766ad7dfccSRui Ueyama     Expr E = readParenExpr();
1677708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1678708019c4SRui Ueyama   }
1679708019c4SRui Ueyama   if (Tok == "CONSTANT") {
1680b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1681b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return getConstant(Name); };
1682708019c4SRui Ueyama   }
1683f34f45fdSGeorge Rimar   if (Tok == "DEFINED") {
16840ee25a69SRui Ueyama     StringRef Name = readParenLiteral();
16850ee25a69SRui Ueyama     return [=](uint64_t Dot) { return ScriptBase->isDefined(Name) ? 1 : 0; };
1686f34f45fdSGeorge Rimar   }
168754c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
168854c145ceSRafael Espindola     expect("(");
16895424e7c7SJustin Bogner     skip();
169054c145ceSRafael Espindola     expect(",");
16918c658bf8SGeorge Rimar     Expr E = readExpr();
169254c145ceSRafael Espindola     expect(")");
16938c658bf8SGeorge Rimar     return [=](uint64_t Dot) { return E(Dot); };
169454c145ceSRafael Espindola   }
1695708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
1696708019c4SRui Ueyama     expect("(");
1697708019c4SRui Ueyama     Expr E = readExpr();
1698708019c4SRui Ueyama     expect(",");
1699708019c4SRui Ueyama     readExpr();
1700708019c4SRui Ueyama     expect(")");
1701f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1702708019c4SRui Ueyama   }
1703708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
1704708019c4SRui Ueyama     expect("(");
1705708019c4SRui Ueyama     expect(".");
1706708019c4SRui Ueyama     expect(")");
1707708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
1708708019c4SRui Ueyama   }
1709276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
1710276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1711276b4e64SGeorge Rimar   // the next page boundary for simplicity.
1712276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
1713276b4e64SGeorge Rimar     expect("(");
171497bdc722SRafael Espindola     readExpr();
1715276b4e64SGeorge Rimar     expect(",");
1716276b4e64SGeorge Rimar     readExpr();
1717276b4e64SGeorge Rimar     expect(")");
1718276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1719276b4e64SGeorge Rimar   }
17209e69450eSGeorge Rimar   if (Tok == "SIZEOF") {
1721b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1722afaa9343SEugene Leviant     return
1723afaa9343SEugene Leviant         [=](uint64_t Dot) { return ScriptBase->getOutputSection(Name)->Size; };
17249e69450eSGeorge Rimar   }
172536fac7f0SEugene Leviant   if (Tok == "ALIGNOF") {
1726b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1727afaa9343SEugene Leviant     return [=](uint64_t Dot) {
1728afaa9343SEugene Leviant       return ScriptBase->getOutputSection(Name)->Addralign;
1729afaa9343SEugene Leviant     };
173036fac7f0SEugene Leviant   }
1731e32a3598SGeorge Rimar   if (Tok == "SIZEOF_HEADERS")
1732b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1733708019c4SRui Ueyama 
17349f2f7ad9SGeorge Rimar   // Tok is a literal number.
17359f2f7ad9SGeorge Rimar   uint64_t V;
17369f2f7ad9SGeorge Rimar   if (readInteger(Tok, V))
1737b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return V; };
17389f2f7ad9SGeorge Rimar 
17399f2f7ad9SGeorge Rimar   // Tok is a symbol name.
174030835ea4SGeorge Rimar   if (Tok != "." && !isValidCIdentifier(Tok))
1741708019c4SRui Ueyama     setError("malformed number: " + Tok);
17422f831dcaSRafael Espindola   return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
1743afaa9343SEugene Leviant           [=]() { return isAbsolute(Tok); },
1744afaa9343SEugene Leviant           [=]() { return ScriptBase->getSymbolSection(Tok); }};
1745a9c5a528SGeorge Rimar }
1746708019c4SRui Ueyama 
1747708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
17485424e7c7SJustin Bogner   skip();
1749708019c4SRui Ueyama   Expr L = readExpr();
1750708019c4SRui Ueyama   expect(":");
1751708019c4SRui Ueyama   Expr R = readExpr();
1752708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1753708019c4SRui Ueyama }
1754708019c4SRui Ueyama 
17556ad7dfccSRui Ueyama Expr ScriptParser::readParenExpr() {
17566ad7dfccSRui Ueyama   expect("(");
17576ad7dfccSRui Ueyama   Expr E = readExpr();
17586ad7dfccSRui Ueyama   expect(")");
17596ad7dfccSRui Ueyama   return E;
17606ad7dfccSRui Ueyama }
17616ad7dfccSRui Ueyama 
1762bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1763bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
1764bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
1765bbe38602SEugene Leviant     StringRef Tok = next();
1766da841c16SGeorge Rimar     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1767bbe38602SEugene Leviant   }
1768bbe38602SEugene Leviant   return Phdrs;
1769bbe38602SEugene Leviant }
1770bbe38602SEugene Leviant 
177195dd718cSGeorge Rimar // Read a program header type name. The next token must be a
177295dd718cSGeorge Rimar // name of a program header type or a constant (e.g. "0x3").
1773bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
1774bbe38602SEugene Leviant   StringRef Tok = next();
177595dd718cSGeorge Rimar   uint64_t Val;
177695dd718cSGeorge Rimar   if (readInteger(Tok, Val))
177795dd718cSGeorge Rimar     return Val;
177895dd718cSGeorge Rimar 
1779b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
1780b0f6c590SRui Ueyama                      .Case("PT_NULL", PT_NULL)
1781b0f6c590SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
1782b0f6c590SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1783b0f6c590SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
1784b0f6c590SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
1785b0f6c590SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
1786b0f6c590SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
1787b0f6c590SRui Ueyama                      .Case("PT_TLS", PT_TLS)
1788b0f6c590SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1789b0f6c590SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1790b0f6c590SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1791270173f2SGeorge Rimar                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1792cc6e567cSGeorge Rimar                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1793b0f6c590SRui Ueyama                      .Default(-1);
1794bbe38602SEugene Leviant 
1795b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1796b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1797b0f6c590SRui Ueyama     return PT_NULL;
1798b0f6c590SRui Ueyama   }
1799b0f6c590SRui Ueyama   return Ret;
1800bbe38602SEugene Leviant }
1801bbe38602SEugene Leviant 
180295769b4aSRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
180320b6598cSGeorge Rimar   // Identifiers start at 2 because 0 and 1 are reserved
180420b6598cSGeorge Rimar   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1805da805c48SRui Ueyama   uint16_t VersionId = Config->VersionDefinitions.size() + 2;
180620b6598cSGeorge Rimar   Config->VersionDefinitions.push_back({VerStr, VersionId});
180720b6598cSGeorge Rimar 
180883043f23SRui Ueyama   if (consume("global:") || peek() != "local:")
180920b6598cSGeorge Rimar     readGlobal(VerStr);
181083043f23SRui Ueyama   if (consume("local:"))
1811bb6c01e7SGeorge Rimar     readLocal(VerStr);
181220b6598cSGeorge Rimar   expect("}");
181320b6598cSGeorge Rimar 
181420b6598cSGeorge Rimar   // Each version may have a parent version. For example, "Ver2" defined as
181520b6598cSGeorge Rimar   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
181620b6598cSGeorge Rimar   // version hierarchy is, probably against your instinct, purely for human; the
181720b6598cSGeorge Rimar   // runtime doesn't care about them at all. In LLD, we simply skip the token.
181820b6598cSGeorge Rimar   if (!VerStr.empty() && peek() != ";")
18195424e7c7SJustin Bogner     skip();
182020b6598cSGeorge Rimar   expect(";");
182120b6598cSGeorge Rimar }
182220b6598cSGeorge Rimar 
1823e0fc2421SGeorge Rimar void ScriptParser::readSymbols(std::vector<SymbolVersion> &V) {
1824e0fc2421SGeorge Rimar   for (;;) {
1825e0fc2421SGeorge Rimar     if (consume("extern"))
1826e0fc2421SGeorge Rimar       readVersionExtern(&V);
1827e0fc2421SGeorge Rimar 
18280ee25a69SRui Ueyama     if (peek() == "}" || peek() == "local:" || Error)
1829e0fc2421SGeorge Rimar       return;
18300ee25a69SRui Ueyama     StringRef Tok = next();
18310ee25a69SRui Ueyama     V.push_back({unquote(Tok), false, hasWildcard(Tok)});
1832e0fc2421SGeorge Rimar     expect(";");
1833e0fc2421SGeorge Rimar   }
1834e0fc2421SGeorge Rimar }
1835e0fc2421SGeorge Rimar 
1836bb6c01e7SGeorge Rimar void ScriptParser::readLocal(StringRef VerStr) {
1837bb6c01e7SGeorge Rimar   if (consume("*")) {
183820b6598cSGeorge Rimar     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
183920b6598cSGeorge Rimar     expect(";");
1840bb6c01e7SGeorge Rimar     return;
1841bb6c01e7SGeorge Rimar   }
1842bb6c01e7SGeorge Rimar 
1843bb6c01e7SGeorge Rimar   if (VerStr.empty())
1844bb6c01e7SGeorge Rimar     setError("locals list for anonymous version is not supported");
1845bb6c01e7SGeorge Rimar 
184617c65af8SGeorge Rimar   readSymbols(Config->VersionScriptLocals);
184720b6598cSGeorge Rimar }
184820b6598cSGeorge Rimar 
1849e0fc2421SGeorge Rimar void ScriptParser::readVersionExtern(std::vector<SymbolVersion> *V) {
1850cd574a5eSGeorge Rimar   expect("\"C++\"");
185120b6598cSGeorge Rimar   expect("{");
185220b6598cSGeorge Rimar 
18530ee25a69SRui Ueyama   while (!Error && peek() != "}") {
18540ee25a69SRui Ueyama     StringRef Tok = next();
18550ee25a69SRui Ueyama     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
18560ee25a69SRui Ueyama     V->push_back({unquote(Tok), true, HasWildcard});
185720b6598cSGeorge Rimar     expect(";");
185820b6598cSGeorge Rimar   }
185920b6598cSGeorge Rimar 
186020b6598cSGeorge Rimar   expect("}");
186120b6598cSGeorge Rimar   expect(";");
186220b6598cSGeorge Rimar }
186320b6598cSGeorge Rimar 
186420b6598cSGeorge Rimar void ScriptParser::readGlobal(StringRef VerStr) {
186520b6598cSGeorge Rimar   if (VerStr.empty())
1866e0fc2421SGeorge Rimar     readSymbols(Config->VersionScriptGlobals);
186720b6598cSGeorge Rimar   else
1868e0fc2421SGeorge Rimar     readSymbols(Config->VersionDefinitions.back().Globals);
186920b6598cSGeorge Rimar }
187020b6598cSGeorge Rimar 
187116b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
187216b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
187316b0cc9eSSimon Atanasyan     return false;
187416b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
187516b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
187616b0cc9eSSimon Atanasyan       return true;
187716b0cc9eSSimon Atanasyan   return false;
187816b0cc9eSSimon Atanasyan }
187916b0cc9eSSimon Atanasyan 
188007320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
188116b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
188220b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
188320b6598cSGeorge Rimar }
188420b6598cSGeorge Rimar 
188520b6598cSGeorge Rimar void elf::readVersionScript(MemoryBufferRef MB) {
188620b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), false).readVersionScript();
1887f7c5fbb1SRui Ueyama }
18881ebc8ed7SRui Ueyama 
188907320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
189007320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
189107320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
189207320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1893