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) {
78e1937bb5SGeorge Rimar   Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
79e1937bb5SGeorge Rimar       Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
801602421cSRui Ueyama   Cmd->Sym = Sym->body();
81ceabe80eSEugene Leviant }
82ceabe80eSEugene Leviant 
83db741e72SEugene Leviant template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
842f831dcaSRafael Espindola   if (Cmd->Expression.IsAbsolute())
85db741e72SEugene Leviant     addRegular<ELFT>(Cmd);
86db741e72SEugene Leviant   else
87db741e72SEugene Leviant     addSynthetic<ELFT>(Cmd);
88db741e72SEugene Leviant }
891602421cSRui Ueyama // If a symbol was in PROVIDE(), we need to define it only when
901602421cSRui Ueyama // it is an undefined symbol.
911602421cSRui Ueyama template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
921602421cSRui Ueyama   if (Cmd->Name == ".")
93ceabe80eSEugene Leviant     return false;
941602421cSRui Ueyama   if (!Cmd->Provide)
95ceabe80eSEugene Leviant     return true;
961602421cSRui Ueyama   SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
971602421cSRui Ueyama   return B && B->isUndefined();
98ceabe80eSEugene Leviant }
99ceabe80eSEugene Leviant 
100076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
101076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
102076fe157SGeorge Rimar }
103076fe157SGeorge Rimar 
104076fe157SGeorge Rimar bool OutputSectionCommand::classof(const BaseCommand *C) {
105076fe157SGeorge Rimar   return C->Kind == OutputSectionKind;
106076fe157SGeorge Rimar }
107076fe157SGeorge Rimar 
108eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
109eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
110eea3114fSGeorge Rimar }
111eea3114fSGeorge Rimar 
112eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
113eefa758eSGeorge Rimar   return C->Kind == AssertKind;
114eefa758eSGeorge Rimar }
115eefa758eSGeorge Rimar 
116e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) {
117e38cbab5SGeorge Rimar   return C->Kind == BytesDataKind;
118e38cbab5SGeorge Rimar }
119e38cbab5SGeorge Rimar 
12022886a28SEugene Zelenko template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
12122886a28SEugene Zelenko template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
122f34d0e08SRui Ueyama 
12307320e40SRui Ueyama template <class ELFT>
12407320e40SRui Ueyama bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
125cf43f179SEugene Leviant   for (InputSectionDescription *ID : Opt.KeptSections) {
126cf43f179SEugene Leviant     StringRef Filename = S->getFile()->getName();
127f91282e1SRui Ueyama     if (!ID->FilePat.match(sys::path::filename(Filename)))
128cf43f179SEugene Leviant       continue;
129cf43f179SEugene Leviant 
130cf43f179SEugene Leviant     for (SectionPattern &P : ID->SectionPatterns)
131f91282e1SRui Ueyama       if (P.SectionPat.match(S->Name))
132eea3114fSGeorge Rimar         return true;
133cf43f179SEugene Leviant   }
134eea3114fSGeorge Rimar   return false;
135eea3114fSGeorge Rimar }
136eea3114fSGeorge Rimar 
137575208caSGeorge Rimar static bool comparePriority(InputSectionData *A, InputSectionData *B) {
138575208caSGeorge Rimar   return getPriority(A->Name) < getPriority(B->Name);
139575208caSGeorge Rimar }
140575208caSGeorge Rimar 
141c0028d3dSRafael Espindola static bool compareName(InputSectionData *A, InputSectionData *B) {
142042a3f20SRafael Espindola   return A->Name < B->Name;
1430702c4e8SGeorge Rimar }
144742c3836SRui Ueyama 
145c0028d3dSRafael Espindola static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
146742c3836SRui Ueyama   // ">" is not a mistake. Larger alignments are placed before smaller
147742c3836SRui Ueyama   // alignments in order to reduce the amount of padding necessary.
148742c3836SRui Ueyama   // This is compatible with GNU.
149742c3836SRui Ueyama   return A->Alignment > B->Alignment;
150742c3836SRui Ueyama }
151742c3836SRui Ueyama 
152c0028d3dSRafael Espindola static std::function<bool(InputSectionData *, InputSectionData *)>
153be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
154be394db3SGeorge Rimar   switch (K) {
155be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
156c0028d3dSRafael Espindola     return compareAlignment;
157be394db3SGeorge Rimar   case SortSectionPolicy::Name:
158be394db3SGeorge Rimar     return compareName;
159be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
160be394db3SGeorge Rimar     return comparePriority;
161be394db3SGeorge Rimar   default:
162be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
163be394db3SGeorge Rimar   }
164742c3836SRui Ueyama }
1650702c4e8SGeorge Rimar 
16648c3f1ceSRui Ueyama template <class ELFT>
167e71a3f8aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
16806ae6836SGeorge Rimar                              ConstraintKind Kind) {
1698f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
1708f66df92SGeorge Rimar     return true;
171e746e52cSRafael Espindola   bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
172d3190795SRafael Espindola     auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
1731854a8ebSRafael Espindola     return Sec->Flags & SHF_WRITE;
17406ae6836SGeorge Rimar   });
175e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
176e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
17706ae6836SGeorge Rimar }
17806ae6836SGeorge Rimar 
17907171f21SGeorge Rimar static void sortSections(InputSectionData **Begin, InputSectionData **End,
180ee924709SRui Ueyama                          SortSectionPolicy K) {
181ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
18207171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
183ee924709SRui Ueyama }
184ee924709SRui Ueyama 
185d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
186be94e1b6SRafael Espindola template <class ELFT>
187e71a3f8aSRafael Espindola void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
1884dc07becSRui Ueyama   // Collects all sections that satisfy constraints of I
1894dc07becSRui Ueyama   // and attach them to I.
1904dc07becSRui Ueyama   for (SectionPattern &Pat : I->SectionPatterns) {
19107171f21SGeorge Rimar     size_t SizeBefore = I->Sections.size();
1928c6a5aafSRui Ueyama 
1938c6a5aafSRui Ueyama     for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
1948f9026baSRafael Espindola       if (!S->Live || S->OutSec)
1958c6a5aafSRui Ueyama         continue;
1968c6a5aafSRui Ueyama 
1978c6a5aafSRui Ueyama       StringRef Filename;
1988c6a5aafSRui Ueyama       if (elf::ObjectFile<ELFT> *F = S->getFile())
1998c6a5aafSRui Ueyama         Filename = sys::path::filename(F->getName());
2008c6a5aafSRui Ueyama 
201e8a6102fSRui Ueyama       if (I->FilePat.match(Filename) && !Pat.ExcludedFilePat.match(Filename) &&
202e8a6102fSRui Ueyama           Pat.SectionPat.match(S->Name))
203d3190795SRafael Espindola         I->Sections.push_back(S);
204395281cfSGeorge Rimar     }
205d3190795SRafael Espindola 
206ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
207ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
208ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
209ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
210ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
211ee924709SRui Ueyama     //
212ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
213ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
214ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
215ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
216ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
21707171f21SGeorge Rimar     InputSectionData **Begin = I->Sections.data() + SizeBefore;
21807171f21SGeorge Rimar     InputSectionData **End = I->Sections.data() + I->Sections.size();
21907171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
22007171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
22107171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
222ee924709SRui Ueyama       else
22307171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
22407171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
22507171f21SGeorge Rimar     }
226ee924709SRui Ueyama   }
227d3190795SRafael Espindola 
228d3190795SRafael Espindola   // We do not add duplicate input sections, so mark them with a dummy output
229d3190795SRafael Espindola   // section for now.
230d3190795SRafael Espindola   for (InputSectionData *S : I->Sections) {
231d3190795SRafael Espindola     auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
232e08e78dfSRafael Espindola     S2->OutSec = (OutputSectionBase *)-1;
233d3190795SRafael Espindola   }
234be94e1b6SRafael Espindola }
235be94e1b6SRafael Espindola 
236be94e1b6SRafael Espindola template <class ELFT>
237be94e1b6SRafael Espindola void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
238be94e1b6SRafael Espindola   for (InputSectionBase<ELFT> *S : V) {
239be94e1b6SRafael Espindola     S->Live = false;
240be94e1b6SRafael Espindola     reportDiscarded(S);
241be94e1b6SRafael Espindola   }
242be94e1b6SRafael Espindola }
243be94e1b6SRafael Espindola 
24406ae6836SGeorge Rimar template <class ELFT>
2450b9ce6a4SRui Ueyama std::vector<InputSectionBase<ELFT> *>
24606ae6836SGeorge Rimar LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
2470b9ce6a4SRui Ueyama   std::vector<InputSectionBase<ELFT> *> Ret;
248e7f912cdSRui Ueyama 
24906ae6836SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
2507c3ff2ebSRafael Espindola     auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
2517c3ff2ebSRafael Espindola     if (!Cmd)
2520b9ce6a4SRui Ueyama       continue;
253e71a3f8aSRafael Espindola     computeInputSections(Cmd);
254d3190795SRafael Espindola     for (InputSectionData *S : Cmd->Sections)
255d3190795SRafael Espindola       Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
2560b9ce6a4SRui Ueyama   }
257e71a3f8aSRafael Espindola 
258cc1ba8c7SEugene Leviant   // After we created final list we should now set OutSec pointer to null,
259cc1ba8c7SEugene Leviant   // instead of -1. Otherwise we may get a crash when writing relocs, in
260cc1ba8c7SEugene Leviant   // case section is discarded by linker script
261cc1ba8c7SEugene Leviant   for (InputSectionBase<ELFT> *S : Ret)
262cc1ba8c7SEugene Leviant     S->OutSec = nullptr;
263cc1ba8c7SEugene Leviant 
2640b9ce6a4SRui Ueyama   return Ret;
2650b9ce6a4SRui Ueyama }
2660b9ce6a4SRui Ueyama 
267e5d3ca50SPetr Hosek template <class ELFT>
26810897f18SRafael Espindola static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
26910897f18SRafael Espindola                                             StringRef OutsecName) {
27010897f18SRafael Espindola   // When using linker script the merge rules are different.
27110897f18SRafael Espindola   // Unfortunately, linker scripts are name based. This means that expressions
27210897f18SRafael Espindola   // like *(.foo*) can refer to multiple input sections that would normally be
27310897f18SRafael Espindola   // placed in different output sections. We cannot put them in different
27410897f18SRafael Espindola   // output sections or we would produce wrong results for
27510897f18SRafael Espindola   // start = .; *(.foo.*) end = .; *(.bar)
27610897f18SRafael Espindola   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
27710897f18SRafael Espindola   // another. The problem is that there is no way to layout those output
27810897f18SRafael Espindola   // sections such that the .foo sections are the only thing between the
27910897f18SRafael Espindola   // start and end symbols.
28010897f18SRafael Espindola 
28110897f18SRafael Espindola   // An extra annoyance is that we cannot simply disable merging of the contents
28210897f18SRafael Espindola   // of SHF_MERGE sections, but our implementation requires one output section
28310897f18SRafael Espindola   // per "kind" (string or not, which size/aligment).
28410897f18SRafael Espindola   // Fortunately, creating symbols in the middle of a merge section is not
28510897f18SRafael Espindola   // supported by bfd or gold, so we can just create multiple section in that
28610897f18SRafael Espindola   // case.
28710897f18SRafael Espindola   typedef typename ELFT::uint uintX_t;
2881854a8ebSRafael Espindola   uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
28910897f18SRafael Espindola 
29010897f18SRafael Espindola   uintX_t Alignment = 0;
29110897f18SRafael Espindola   if (isa<MergeInputSection<ELFT>>(C))
2921854a8ebSRafael Espindola     Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
29310897f18SRafael Espindola 
29410897f18SRafael Espindola   return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
29510897f18SRafael Espindola }
29610897f18SRafael Espindola 
29710897f18SRafael Espindola template <class ELFT>
29820d03194SEugene Leviant void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
29920d03194SEugene Leviant                                     InputSectionBase<ELFT> *Sec,
30020d03194SEugene Leviant                                     StringRef Name) {
301e08e78dfSRafael Espindola   OutputSectionBase *OutSec;
30228c1597aSRafael Espindola   bool IsNew;
30310897f18SRafael Espindola   std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
30428c1597aSRafael Espindola   if (IsNew)
30528c1597aSRafael Espindola     OutputSections->push_back(OutSec);
30620d03194SEugene Leviant   OutSec->addSection(Sec);
30720d03194SEugene Leviant }
30820d03194SEugene Leviant 
30920d03194SEugene Leviant template <class ELFT>
31020d03194SEugene Leviant void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
3117c3ff2ebSRafael Espindola   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
3127c3ff2ebSRafael Espindola     auto Iter = Opt.Commands.begin() + I;
3137c3ff2ebSRafael Espindola     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
3142ab5f73dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
3152ab5f73dSRui Ueyama       if (shouldDefine<ELFT>(Cmd))
316b0de56b5SRafael Espindola         addSymbol<ELFT>(Cmd);
3172ab5f73dSRui Ueyama       continue;
3182ab5f73dSRui Ueyama     }
31920d03194SEugene Leviant     if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
32020d03194SEugene Leviant       // If we don't have SECTIONS then output sections have already been
321194470cdSGeorge Rimar       // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
32220d03194SEugene Leviant       // will not be called, so ASSERT should be evaluated now.
32320d03194SEugene Leviant       if (!Opt.HasSections)
32420d03194SEugene Leviant         Cmd->Expression(0);
32520d03194SEugene Leviant       continue;
32620d03194SEugene Leviant     }
3272ab5f73dSRui Ueyama 
328ceabe80eSEugene Leviant     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
3297bd37870SRafael Espindola       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
3307bd37870SRafael Espindola 
33148c3f1ceSRui Ueyama       if (Cmd->Name == "/DISCARD/") {
3327bd37870SRafael Espindola         discard(V);
33348c3f1ceSRui Ueyama         continue;
33448c3f1ceSRui Ueyama       }
3350b9ce6a4SRui Ueyama 
3367c3ff2ebSRafael Espindola       if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
3377c3ff2ebSRafael Espindola         for (InputSectionBase<ELFT> *S : V)
3387c3ff2ebSRafael Espindola           S->OutSec = nullptr;
3397c3ff2ebSRafael Espindola         Opt.Commands.erase(Iter);
340dfbbbc86SGeorge Rimar         --I;
3417c3ff2ebSRafael Espindola         continue;
3427c3ff2ebSRafael Espindola       }
3437c3ff2ebSRafael Espindola 
3447c3ff2ebSRafael Espindola       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
3457c3ff2ebSRafael Espindola         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
3467c3ff2ebSRafael Espindola           if (shouldDefine<ELFT>(OutCmd))
3477c3ff2ebSRafael Espindola             addSymbol<ELFT>(OutCmd);
3487c3ff2ebSRafael Espindola 
34997403d15SEugene Leviant       if (V.empty())
3500b9ce6a4SRui Ueyama         continue;
3510b9ce6a4SRui Ueyama 
352a14b13d8SGeorge Rimar       for (InputSectionBase<ELFT> *Sec : V) {
35320d03194SEugene Leviant         addSection(Factory, Sec, Cmd->Name);
35420d03194SEugene Leviant         if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
355db24d9c3SGeorge Rimar           Sec->Alignment = Subalign;
35620d03194SEugene Leviant       }
357eea3114fSGeorge Rimar     }
35848c3f1ceSRui Ueyama   }
359db24d9c3SGeorge Rimar }
360e63d81bdSEugene Leviant 
36120d03194SEugene Leviant template <class ELFT>
36220d03194SEugene Leviant void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
36320d03194SEugene Leviant   processCommands(Factory);
3648c6a5aafSRui Ueyama 
3650b9ce6a4SRui Ueyama   // Add orphan sections.
3668c6a5aafSRui Ueyama   for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
3678f9026baSRafael Espindola     if (S->Live && !S->OutSec)
36855518e7dSRui Ueyama       addSection(Factory, S, getOutputSectionName(S->Name));
369e63d81bdSEugene Leviant }
370e63d81bdSEugene Leviant 
371db741e72SEugene Leviant // Sets value of a section-defined symbol. Two kinds of
372db741e72SEugene Leviant // symbols are processed: synthetic symbols, whose value
373db741e72SEugene Leviant // is an offset from beginning of section and regular
374db741e72SEugene Leviant // symbols whose value is absolute.
375db741e72SEugene Leviant template <class ELFT>
376e08e78dfSRafael Espindola static void assignSectionSymbol(SymbolAssignment *Cmd, OutputSectionBase *Sec,
377498ed714SRafael Espindola                                 typename ELFT::uint Value) {
378db741e72SEugene Leviant   if (!Cmd->Sym)
379db741e72SEugene Leviant     return;
380db741e72SEugene Leviant 
381db741e72SEugene Leviant   if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
382db741e72SEugene Leviant     Body->Section = Sec;
38304a2e348SRafael Espindola     Body->Value = Cmd->Expression(Value) - Sec->Addr;
384db741e72SEugene Leviant     return;
385db741e72SEugene Leviant   }
386db741e72SEugene Leviant   auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
387498ed714SRafael Espindola   Body->Value = Cmd->Expression(Value);
388db741e72SEugene Leviant }
389db741e72SEugene Leviant 
390e08e78dfSRafael Espindola template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
39104a2e348SRafael Espindola   return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
392a940e539SRafael Espindola }
393a940e539SRafael Espindola 
394d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
395d3190795SRafael Espindola   if (!AlreadyOutputIS.insert(S).second)
396ceabe80eSEugene Leviant     return;
397e08e78dfSRafael Espindola   bool IsTbss = isTbss<ELFT>(CurOutSec);
398d3190795SRafael Espindola 
399d3190795SRafael Espindola   uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
400d3190795SRafael Espindola   Pos = alignTo(Pos, S->Alignment);
40104a2e348SRafael Espindola   S->OutSecOff = Pos - CurOutSec->Addr;
402d3190795SRafael Espindola   Pos += S->getSize();
403d3190795SRafael Espindola 
404d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
405d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
406d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
40704a2e348SRafael Espindola   CurOutSec->Size = Pos - CurOutSec->Addr;
408d3190795SRafael Espindola 
4097252ae52SRafael Espindola   if (IsTbss)
4107252ae52SRafael Espindola     ThreadBssOffset = Pos - Dot;
4117252ae52SRafael Espindola   else
412d3190795SRafael Espindola     Dot = Pos;
4132de509c3SRui Ueyama }
414ceabe80eSEugene Leviant 
415d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::flush() {
41665499b90SRafael Espindola   if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
41765499b90SRafael Espindola     return;
41865499b90SRafael Espindola   if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
419d3190795SRafael Espindola     for (InputSection<ELFT> *I : OutSec->Sections)
420d3190795SRafael Espindola       output(I);
42165499b90SRafael Espindola   } else {
42204a2e348SRafael Espindola     Dot += CurOutSec->Size;
423d3190795SRafael Espindola   }
424d3190795SRafael Espindola }
42597403d15SEugene Leviant 
426d3190795SRafael Espindola template <class ELFT>
427e08e78dfSRafael Espindola void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
428d3190795SRafael Espindola   if (CurOutSec == Sec)
429d3190795SRafael Espindola     return;
430d3190795SRafael Espindola   if (AlreadyOutputOS.count(Sec))
431d3190795SRafael Espindola     return;
432d3190795SRafael Espindola 
433d3190795SRafael Espindola   flush();
434d3190795SRafael Espindola   CurOutSec = Sec;
435d3190795SRafael Espindola 
43604a2e348SRafael Espindola   Dot = alignTo(Dot, CurOutSec->Addralign);
437e08e78dfSRafael Espindola   CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
438b71d6f7aSEugene Leviant 
439b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
440b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
441b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
442b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
443b71d6f7aSEugene Leviant   CurOutSec->setLMAOffset(LMAOffset);
444d3190795SRafael Espindola }
445d3190795SRafael Espindola 
446d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
447e38cbab5SGeorge Rimar   // This handles the assignments to symbol or to a location counter (.)
448d3190795SRafael Espindola   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
44997403d15SEugene Leviant     if (AssignCmd->Name == ".") {
45097403d15SEugene Leviant       // Update to location counter means update to section size.
451d3190795SRafael Espindola       Dot = AssignCmd->Expression(Dot);
45204a2e348SRafael Espindola       CurOutSec->Size = Dot - CurOutSec->Addr;
453d3190795SRafael Espindola       return;
45497403d15SEugene Leviant     }
455498ed714SRafael Espindola     assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot);
456d3190795SRafael Espindola     return;
45797403d15SEugene Leviant   }
458e38cbab5SGeorge Rimar 
459e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
460e38cbab5SGeorge Rimar   if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
46104a2e348SRafael Espindola     DataCmd->Offset = Dot - CurOutSec->Addr;
462e38cbab5SGeorge Rimar     Dot += DataCmd->Size;
46304a2e348SRafael Espindola     CurOutSec->Size = Dot - CurOutSec->Addr;
464e38cbab5SGeorge Rimar     return;
465e38cbab5SGeorge Rimar   }
466e38cbab5SGeorge Rimar 
467e38cbab5SGeorge Rimar   // It handles single input section description command,
468e38cbab5SGeorge Rimar   // calculates and assigns the offsets for each section and also
469e38cbab5SGeorge Rimar   // updates the output section size.
470d3190795SRafael Espindola   auto &ICmd = cast<InputSectionDescription>(Base);
471d3190795SRafael Espindola   for (InputSectionData *ID : ICmd.Sections) {
472d3190795SRafael Espindola     auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
473d3190795SRafael Espindola     switchTo(IB->OutSec);
474d3190795SRafael Espindola     if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
475d3190795SRafael Espindola       output(I);
47665499b90SRafael Espindola     else
47765499b90SRafael Espindola       flush();
478ceabe80eSEugene Leviant   }
479ceabe80eSEugene Leviant }
480ceabe80eSEugene Leviant 
4818f66df92SGeorge Rimar template <class ELFT>
482e08e78dfSRafael Espindola static std::vector<OutputSectionBase *>
483e08e78dfSRafael Espindola findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
484e08e78dfSRafael Espindola   std::vector<OutputSectionBase *> Ret;
485e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : Sections)
4869257764dSEugene Leviant     if (Sec->getName() == Name)
487a14b13d8SGeorge Rimar       Ret.push_back(Sec);
488a14b13d8SGeorge Rimar   return Ret;
4898f66df92SGeorge Rimar }
4908f66df92SGeorge Rimar 
491d3190795SRafael Espindola template <class ELFT>
492d3190795SRafael Espindola void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
493b71d6f7aSEugene Leviant   if (Cmd->LMAExpr)
494b71d6f7aSEugene Leviant     LMAOffset = Cmd->LMAExpr(Dot) - Dot;
495e08e78dfSRafael Espindola   std::vector<OutputSectionBase *> Sections =
496e08e78dfSRafael Espindola       findSections<ELFT>(Cmd->Name, *OutputSections);
497d3190795SRafael Espindola   if (Sections.empty())
498d3190795SRafael Espindola     return;
499d3190795SRafael Espindola   switchTo(Sections[0]);
500d3190795SRafael Espindola   // Find the last section output location. We will output orphan sections
501d3190795SRafael Espindola   // there so that end symbols point to the correct location.
502d3190795SRafael Espindola   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
503d3190795SRafael Espindola                         [](const std::unique_ptr<BaseCommand> &Cmd) {
504d3190795SRafael Espindola                           return !isa<SymbolAssignment>(*Cmd);
505d3190795SRafael Espindola                         })
506d3190795SRafael Espindola                .base();
507d3190795SRafael Espindola   for (auto I = Cmd->Commands.begin(); I != E; ++I)
508d3190795SRafael Espindola     process(**I);
509e08e78dfSRafael Espindola   for (OutputSectionBase *Base : Sections)
510d3190795SRafael Espindola     switchTo(Base);
5112506cb4dSEugene Leviant   flush();
512b31dd370SGeorge Rimar   std::for_each(E, Cmd->Commands.end(),
513b31dd370SGeorge Rimar                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
514d3190795SRafael Espindola }
515d3190795SRafael Espindola 
51607fe6129SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
5176d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
5186d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
5196d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
5206d38e4dbSRafael Espindola   // clutter the output.
5216d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
5226d38e4dbSRafael Espindola   // more aggressive at removing them.
5236d38e4dbSRafael Espindola   auto Pos = std::remove_if(
5246d38e4dbSRafael Espindola       Opt.Commands.begin(), Opt.Commands.end(),
5256d38e4dbSRafael Espindola       [&](const std::unique_ptr<BaseCommand> &Base) {
5266d38e4dbSRafael Espindola         auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
5276d38e4dbSRafael Espindola         if (!Cmd)
5286d38e4dbSRafael Espindola           return false;
5296a53737cSRafael Espindola         return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
5306d38e4dbSRafael Espindola       });
5316d38e4dbSRafael Espindola   Opt.Commands.erase(Pos, Opt.Commands.end());
53207fe6129SRafael Espindola }
53307fe6129SRafael Espindola 
5346a53737cSRafael Espindola static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
5356a53737cSRafael Espindola   for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
5366a53737cSRafael Espindola     if (!isa<InputSectionDescription>(*I))
5376a53737cSRafael Espindola       return false;
5386a53737cSRafael Espindola   return true;
5396a53737cSRafael Espindola }
5406d38e4dbSRafael Espindola 
5416a53737cSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
5429546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
5439546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
5449546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
5459546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
5469546fffbSRafael Espindola   uintX_t Flags = SHF_ALLOC;
5479546fffbSRafael Espindola   uint32_t Type = 0;
5489546fffbSRafael Espindola   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
5499546fffbSRafael Espindola     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
5509546fffbSRafael Espindola     if (!Cmd)
5519546fffbSRafael Espindola       continue;
552e08e78dfSRafael Espindola     std::vector<OutputSectionBase *> Secs =
553e08e78dfSRafael Espindola         findSections<ELFT>(Cmd->Name, *OutputSections);
5549546fffbSRafael Espindola     if (!Secs.empty()) {
55504a2e348SRafael Espindola       Flags = Secs[0]->Flags;
55604a2e348SRafael Espindola       Type = Secs[0]->Type;
5579546fffbSRafael Espindola       continue;
5589546fffbSRafael Espindola     }
5599546fffbSRafael Espindola 
5606a53737cSRafael Espindola     if (isAllSectionDescription(*Cmd))
5616a53737cSRafael Espindola       continue;
5626a53737cSRafael Espindola 
56395642b95SRui Ueyama     auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
5649546fffbSRafael Espindola     OutputSections->push_back(OutSec);
5659546fffbSRafael Espindola   }
566f7a17448SRafael Espindola }
567f7a17448SRafael Espindola 
568f7a17448SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
569f7a17448SRafael Espindola   placeOrphanSections();
570f7a17448SRafael Espindola 
571f7a17448SRafael Espindola   // If output section command doesn't specify any segments,
572f7a17448SRafael Espindola   // and we haven't previously assigned any section to segment,
573f7a17448SRafael Espindola   // then we simply assign section to the very first load segment.
574f7a17448SRafael Espindola   // Below is an example of such linker script:
575f7a17448SRafael Espindola   // PHDRS { seg PT_LOAD; }
576f7a17448SRafael Espindola   // SECTIONS { .aaa : { *(.aaa) } }
577f7a17448SRafael Espindola   std::vector<StringRef> DefPhdrs;
578f7a17448SRafael Espindola   auto FirstPtLoad =
579f7a17448SRafael Espindola       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
580f7a17448SRafael Espindola                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
581f7a17448SRafael Espindola   if (FirstPtLoad != Opt.PhdrsCommands.end())
582f7a17448SRafael Espindola     DefPhdrs.push_back(FirstPtLoad->Name);
583f7a17448SRafael Espindola 
584f7a17448SRafael Espindola   // Walk the commands and propagate the program headers to commands that don't
585f7a17448SRafael Espindola   // explicitly specify them.
586f7a17448SRafael Espindola   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
587f7a17448SRafael Espindola     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
588f7a17448SRafael Espindola     if (!Cmd)
589f7a17448SRafael Espindola       continue;
590f7a17448SRafael Espindola     if (Cmd->Phdrs.empty())
591f7a17448SRafael Espindola       Cmd->Phdrs = DefPhdrs;
592f7a17448SRafael Espindola     else
593f7a17448SRafael Espindola       DefPhdrs = Cmd->Phdrs;
594f7a17448SRafael Espindola   }
5956a53737cSRafael Espindola 
5966a53737cSRafael Espindola   removeEmptyCommands();
5979546fffbSRafael Espindola }
5989546fffbSRafael Espindola 
59915c57951SRafael Espindola // When placing orphan sections, we want to place them after symbol assignments
60015c57951SRafael Espindola // so that an orphan after
60115c57951SRafael Espindola //   begin_foo = .;
60215c57951SRafael Espindola //   foo : { *(foo) }
60315c57951SRafael Espindola //   end_foo = .;
60415c57951SRafael Espindola // doesn't break the intended meaning of the begin/end symbols.
60515c57951SRafael Espindola // We don't want to go over sections since Writer<ELFT>::sortSections is the
60615c57951SRafael Espindola // one in charge of deciding the order of the sections.
60715c57951SRafael Espindola // We don't want to go over alignments, since doing so in
60815c57951SRafael Espindola //  rx_sec : { *(rx_sec) }
60915c57951SRafael Espindola //  . = ALIGN(0x1000);
61015c57951SRafael Espindola //  /* The RW PT_LOAD starts here*/
61115c57951SRafael Espindola //  rw_sec : { *(rw_sec) }
61215c57951SRafael Espindola // would mean that the RW PT_LOAD would become unaligned.
61315c57951SRafael Espindola static bool shouldSkip(const BaseCommand &Cmd) {
61415c57951SRafael Espindola   if (isa<OutputSectionCommand>(Cmd))
61515c57951SRafael Espindola     return false;
61615c57951SRafael Espindola   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
61715c57951SRafael Espindola   if (!Assign)
61815c57951SRafael Espindola     return true;
61915c57951SRafael Espindola   return Assign->Name != ".";
62015c57951SRafael Espindola }
62115c57951SRafael Espindola 
622337f903cSRafael Espindola // Orphan sections are sections present in the input files which are not
623337f903cSRafael Espindola // explicitly placed into the output file by the linker script. This just
624337f903cSRafael Espindola // places them in the order already decided in OutputSections.
6256d91fce5SRafael Espindola template <class ELFT>
626337f903cSRafael Espindola void LinkerScript<ELFT>::placeOrphanSections() {
627aab6d5c5SRafael Espindola   // The OutputSections are already in the correct order.
628aab6d5c5SRafael Espindola   // This loops creates or moves commands as needed so that they are in the
629aab6d5c5SRafael Espindola   // correct order.
630aab6d5c5SRafael Espindola   int CmdIndex = 0;
631e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
632652852c5SGeorge Rimar     StringRef Name = Sec->getName();
633aab6d5c5SRafael Espindola 
634aab6d5c5SRafael Espindola     // Find the last spot where we can insert a command and still get the
63515c57951SRafael Espindola     // correct result.
636aab6d5c5SRafael Espindola     auto CmdIter = Opt.Commands.begin() + CmdIndex;
637aab6d5c5SRafael Espindola     auto E = Opt.Commands.end();
63815c57951SRafael Espindola     while (CmdIter != E && shouldSkip(**CmdIter)) {
639aab6d5c5SRafael Espindola       ++CmdIter;
640aab6d5c5SRafael Espindola       ++CmdIndex;
641aab6d5c5SRafael Espindola     }
642aab6d5c5SRafael Espindola 
643aab6d5c5SRafael Espindola     auto Pos =
644aab6d5c5SRafael Espindola         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
645aab6d5c5SRafael Espindola           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
646aab6d5c5SRafael Espindola           return Cmd && Cmd->Name == Name;
647aab6d5c5SRafael Espindola         });
648aab6d5c5SRafael Espindola     if (Pos == E) {
649aab6d5c5SRafael Espindola       Opt.Commands.insert(CmdIter,
650aab6d5c5SRafael Espindola                           llvm::make_unique<OutputSectionCommand>(Name));
651aab6d5c5SRafael Espindola       ++CmdIndex;
65215c57951SRafael Espindola       continue;
65315c57951SRafael Espindola     }
65415c57951SRafael Espindola 
65515c57951SRafael Espindola     // Continue from where we found it.
65615c57951SRafael Espindola     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
657652852c5SGeorge Rimar   }
658337f903cSRafael Espindola }
659337f903cSRafael Espindola 
660337f903cSRafael Espindola template <class ELFT>
661337f903cSRafael Espindola void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
6627c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
663be607334SRafael Espindola   Dot = 0;
664652852c5SGeorge Rimar 
665076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
666076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
6678d083e6aSRui Ueyama       if (Cmd->Name == ".") {
6688d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
6698d083e6aSRui Ueyama       } else if (Cmd->Sym) {
670e08e78dfSRafael Espindola         assignSectionSymbol<ELFT>(
671e08e78dfSRafael Espindola             Cmd, CurOutSec ? CurOutSec : (*OutputSections)[0], Dot);
6728d083e6aSRui Ueyama       }
67305ef4cffSRui Ueyama       continue;
674652852c5SGeorge Rimar     }
675652852c5SGeorge Rimar 
676eefa758eSGeorge Rimar     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
677eefa758eSGeorge Rimar       Cmd->Expression(Dot);
678eefa758eSGeorge Rimar       continue;
679eefa758eSGeorge Rimar     }
680eefa758eSGeorge Rimar 
681076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
682652852c5SGeorge Rimar 
68358e5c4dcSGeorge Rimar     if (Cmd->AddrExpr)
68458e5c4dcSGeorge Rimar       Dot = Cmd->AddrExpr(Dot);
68558e5c4dcSGeorge Rimar 
686d3190795SRafael Espindola     assignOffsets(Cmd);
687a14b13d8SGeorge Rimar   }
688467c4d55SEugene Leviant 
689aab6d5c5SRafael Espindola   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
690e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
69104a2e348SRafael Espindola     if (Sec->Flags & SHF_ALLOC)
692e08e78dfSRafael Espindola       MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
693aab6d5c5SRafael Espindola     else
69404a2e348SRafael Espindola       Sec->Addr = 0;
695aab6d5c5SRafael Espindola   }
696aab6d5c5SRafael Espindola 
6970d4b6d5cSRafael Espindola   uintX_t HeaderSize = getHeaderSize();
6986d91fce5SRafael Espindola   auto FirstPTLoad =
6996d91fce5SRafael Espindola       std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
7006d91fce5SRafael Espindola         return E.H.p_type == PT_LOAD;
7016d91fce5SRafael Espindola       });
702db35fdf7SEugene Leviant 
7036d91fce5SRafael Espindola   if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
704db35fdf7SEugene Leviant     // If linker script specifies program headers and first PT_LOAD doesn't
705db35fdf7SEugene Leviant     // have both PHDRS and FILEHDR attributes then do nothing
706db35fdf7SEugene Leviant     if (!Opt.PhdrsCommands.empty()) {
707db35fdf7SEugene Leviant       size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
708db35fdf7SEugene Leviant       if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
709db35fdf7SEugene Leviant           !Opt.PhdrsCommands[SegNum].HasFilehdr)
710db35fdf7SEugene Leviant         return;
711db35fdf7SEugene Leviant     }
71264c32d6fSRafael Espindola     // ELF and Program headers need to be right before the first section in
713b91e7118SGeorge Rimar     // memory. Set their addresses accordingly.
7144ec013acSRafael Espindola     MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
71504a2e348SRafael Espindola     Out<ELFT>::ElfHeader->Addr = MinVA;
71604a2e348SRafael Espindola     Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
7176d91fce5SRafael Espindola     FirstPTLoad->First = Out<ELFT>::ElfHeader;
7186d91fce5SRafael Espindola     if (!FirstPTLoad->Last)
7196d91fce5SRafael Espindola       FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
720cd8eaf89SEugene Leviant   } else if (!FirstPTLoad->First) {
721cd8eaf89SEugene Leviant     // Sometimes the very first PT_LOAD segment can be empty.
722cd8eaf89SEugene Leviant     // This happens if (all conditions met):
723cd8eaf89SEugene Leviant     //  - Linker script is used
724cd8eaf89SEugene Leviant     //  - First section in ELF image is not RO
725cd8eaf89SEugene Leviant     //  - Not enough space for program headers.
726cd8eaf89SEugene Leviant     // The code below removes empty PT_LOAD segment and updates
727cd8eaf89SEugene Leviant     // program headers size.
728cd8eaf89SEugene Leviant     Phdrs.erase(FirstPTLoad);
72904a2e348SRafael Espindola     Out<ELFT>::ProgramHeaders->Size =
73004a2e348SRafael Espindola         sizeof(typename ELFT::Phdr) * Phdrs.size();
7316d91fce5SRafael Espindola   }
732fb8978fcSDima Stepanov }
733652852c5SGeorge Rimar 
734464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
73507320e40SRui Ueyama template <class ELFT>
736a4b41dcaSRafael Espindola std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
737edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
738bbe38602SEugene Leviant 
739464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
740464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
741bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
742edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
743edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
744bbe38602SEugene Leviant 
745bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
746adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
747bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
748adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
74956b21c86SEugene Leviant 
75056b21c86SEugene Leviant     if (Cmd.LMAExpr) {
75156b21c86SEugene Leviant       Phdr.H.p_paddr = Cmd.LMAExpr(0);
75256b21c86SEugene Leviant       Phdr.HasLMA = true;
75356b21c86SEugene Leviant     }
754bbe38602SEugene Leviant   }
755bbe38602SEugene Leviant 
756464daadcSRui Ueyama   // Add output sections to program headers.
757e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
75804a2e348SRafael Espindola     if (!(Sec->Flags & SHF_ALLOC))
759bbe38602SEugene Leviant       break;
760bbe38602SEugene Leviant 
761bbe38602SEugene Leviant     // Assign headers specified by linker script
762f7a17448SRafael Espindola     for (size_t Id : getPhdrIndices(Sec->getName())) {
763edebbdf1SRui Ueyama       Ret[Id].add(Sec);
764865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
7650b113671SRafael Espindola         Ret[Id].H.p_flags |= Sec->getPhdrFlags();
766bbe38602SEugene Leviant     }
767bbe38602SEugene Leviant   }
768edebbdf1SRui Ueyama   return Ret;
769bbe38602SEugene Leviant }
770bbe38602SEugene Leviant 
771f9bc3bd2SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
772f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
773f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
774f9bc3bd2SEugene Leviant   return !Opt.PhdrsCommands.empty() &&
775f9bc3bd2SEugene Leviant          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
776f9bc3bd2SEugene Leviant            return Cmd.Type == PT_INTERP;
777f9bc3bd2SEugene Leviant          }) == Opt.PhdrsCommands.end();
778f9bc3bd2SEugene Leviant }
779f9bc3bd2SEugene Leviant 
780bbe38602SEugene Leviant template <class ELFT>
78107320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
782f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
783f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
784f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
785f6c3ccefSGeorge Rimar         return Cmd->Filler;
786e2ee72b5SGeorge Rimar   return {};
787e2ee72b5SGeorge Rimar }
788e2ee72b5SGeorge Rimar 
789e38cbab5SGeorge Rimar template <class ELFT>
790e38cbab5SGeorge Rimar static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
791e38cbab5SGeorge Rimar   const endianness E = ELFT::TargetEndianness;
792e38cbab5SGeorge Rimar 
793e38cbab5SGeorge Rimar   switch (Size) {
794e38cbab5SGeorge Rimar   case 1:
795e38cbab5SGeorge Rimar     *Buf = (uint8_t)Data;
796e38cbab5SGeorge Rimar     break;
797e38cbab5SGeorge Rimar   case 2:
798e38cbab5SGeorge Rimar     write16<E>(Buf, Data);
799e38cbab5SGeorge Rimar     break;
800e38cbab5SGeorge Rimar   case 4:
801e38cbab5SGeorge Rimar     write32<E>(Buf, Data);
802e38cbab5SGeorge Rimar     break;
803e38cbab5SGeorge Rimar   case 8:
804e38cbab5SGeorge Rimar     write64<E>(Buf, Data);
805e38cbab5SGeorge Rimar     break;
806e38cbab5SGeorge Rimar   default:
807e38cbab5SGeorge Rimar     llvm_unreachable("unsupported Size argument");
808e38cbab5SGeorge Rimar   }
809e38cbab5SGeorge Rimar }
810e38cbab5SGeorge Rimar 
811e38cbab5SGeorge Rimar template <class ELFT>
812e38cbab5SGeorge Rimar void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
813e38cbab5SGeorge Rimar   int I = getSectionIndex(Name);
814e38cbab5SGeorge Rimar   if (I == INT_MAX)
815e38cbab5SGeorge Rimar     return;
816e38cbab5SGeorge Rimar 
817e38cbab5SGeorge Rimar   OutputSectionCommand *Cmd =
818e38cbab5SGeorge Rimar       dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
819e38cbab5SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
820e38cbab5SGeorge Rimar     if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
821e38cbab5SGeorge Rimar       writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
822e38cbab5SGeorge Rimar }
823e38cbab5SGeorge Rimar 
824b71d6f7aSEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
8258ceadb38SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
8268ceadb38SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
827b71d6f7aSEugene Leviant       if (Cmd->LMAExpr && Cmd->Name == Name)
828b71d6f7aSEugene Leviant         return true;
829b71d6f7aSEugene Leviant   return false;
8308ceadb38SGeorge Rimar }
8318ceadb38SGeorge Rimar 
832c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
833c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
834c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
835c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
836076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
837f510fa6bSRui Ueyama   int I = 0;
838f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
839076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
840076fe157SGeorge Rimar       if (Cmd->Name == Name)
841f510fa6bSRui Ueyama         return I;
842f510fa6bSRui Ueyama     ++I;
843f510fa6bSRui Ueyama   }
844f510fa6bSRui Ueyama   return INT_MAX;
84571b26e94SGeorge Rimar }
84671b26e94SGeorge Rimar 
847bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
848bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
849bbe38602SEugene Leviant }
850bbe38602SEugene Leviant 
8519e69450eSGeorge Rimar template <class ELFT>
852884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
853e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections)
85496659df0SGeorge Rimar     if (Sec->getName() == Name)
85504a2e348SRafael Espindola       return Sec->Addr;
85696659df0SGeorge Rimar   error("undefined section " + Name);
85796659df0SGeorge Rimar   return 0;
85896659df0SGeorge Rimar }
85996659df0SGeorge Rimar 
86096659df0SGeorge Rimar template <class ELFT>
861b71d6f7aSEugene Leviant uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
862e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections)
863b71d6f7aSEugene Leviant     if (Sec->getName() == Name)
864b71d6f7aSEugene Leviant       return Sec->getLMA();
865b71d6f7aSEugene Leviant   error("undefined section " + Name);
866b71d6f7aSEugene Leviant   return 0;
867b71d6f7aSEugene Leviant }
868b71d6f7aSEugene Leviant 
869b71d6f7aSEugene Leviant template <class ELFT>
870884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
871e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections)
8729e69450eSGeorge Rimar     if (Sec->getName() == Name)
87304a2e348SRafael Espindola       return Sec->Size;
8749e69450eSGeorge Rimar   error("undefined section " + Name);
8759e69450eSGeorge Rimar   return 0;
8769e69450eSGeorge Rimar }
8779e69450eSGeorge Rimar 
87836fac7f0SEugene Leviant template <class ELFT>
87936fac7f0SEugene Leviant uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
880e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections)
88136fac7f0SEugene Leviant     if (Sec->getName() == Name)
88204a2e348SRafael Espindola       return Sec->Addralign;
88336fac7f0SEugene Leviant   error("undefined section " + Name);
88436fac7f0SEugene Leviant   return 0;
88536fac7f0SEugene Leviant }
88636fac7f0SEugene Leviant 
887884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
8880d4b6d5cSRafael Espindola   return elf::getHeaderSize<ELFT>();
889e32a3598SGeorge Rimar }
890e32a3598SGeorge Rimar 
891884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
892884e786dSGeorge Rimar   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
893884e786dSGeorge Rimar     return B->getVA<ELFT>();
894884e786dSGeorge Rimar   error("symbol not found: " + S);
895884e786dSGeorge Rimar   return 0;
896884e786dSGeorge Rimar }
897884e786dSGeorge Rimar 
898f34f45fdSGeorge Rimar template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
899f34f45fdSGeorge Rimar   return Symtab<ELFT>::X->find(S) != nullptr;
900f34f45fdSGeorge Rimar }
901f34f45fdSGeorge Rimar 
9022f831dcaSRafael Espindola template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
9032f831dcaSRafael Espindola   SymbolBody *Sym = Symtab<ELFT>::X->find(S);
9042f831dcaSRafael Espindola   auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
9052f831dcaSRafael Espindola   return DR && !DR->Section;
9062f831dcaSRafael Espindola }
9072f831dcaSRafael Espindola 
908bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
909bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
910bbe38602SEugene Leviant // PHDRS {} script block.
911bbe38602SEugene Leviant template <class ELFT>
912edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
913076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
914076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
915edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
91631d842f5SGeorge Rimar       continue;
91731d842f5SGeorge Rimar 
91829c5a2a9SRui Ueyama     std::vector<size_t> Ret;
91929c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
92029c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
92129c5a2a9SRui Ueyama     return Ret;
922bbe38602SEugene Leviant   }
92331d842f5SGeorge Rimar   return {};
92431d842f5SGeorge Rimar }
925bbe38602SEugene Leviant 
92629c5a2a9SRui Ueyama template <class ELFT>
92729c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
92829c5a2a9SRui Ueyama   size_t I = 0;
92929c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
93029c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
93129c5a2a9SRui Ueyama       return I;
93229c5a2a9SRui Ueyama     ++I;
93329c5a2a9SRui Ueyama   }
93429c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
93529c5a2a9SRui Ueyama   return 0;
93629c5a2a9SRui Ueyama }
93729c5a2a9SRui Ueyama 
93807320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
939c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
940c3794e58SGeorge Rimar 
941f7c5fbb1SRui Ueyama public:
94207320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
943f23b2320SGeorge Rimar 
94420b6598cSGeorge Rimar   void readLinkerScript();
94520b6598cSGeorge Rimar   void readVersionScript();
946f7c5fbb1SRui Ueyama 
947f7c5fbb1SRui Ueyama private:
94852a1509eSRui Ueyama   void addFile(StringRef Path);
94952a1509eSRui Ueyama 
950f7c5fbb1SRui Ueyama   void readAsNeeded();
95190c5099eSDenis Protivensky   void readEntry();
95283f406cfSGeorge Rimar   void readExtern();
953f7c5fbb1SRui Ueyama   void readGroup();
95431aa1f83SRui Ueyama   void readInclude();
955ee59282bSRui Ueyama   void readOutput();
9569159ce93SDavide Italiano   void readOutputArch();
957f7c5fbb1SRui Ueyama   void readOutputFormat();
958bbe38602SEugene Leviant   void readPhdrs();
95968a39a65SDavide Italiano   void readSearchDir();
9608e3b38abSDenis Protivensky   void readSections();
96195769b4aSRui Ueyama   void readVersion();
96295769b4aSRui Ueyama   void readVersionScriptCommand();
9638e3b38abSDenis Protivensky 
964113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
965e38cbab5SGeorge Rimar   BytesDataCommand *readBytesDataCommand(StringRef Tok);
966ff1f29e0SGeorge Rimar   std::vector<uint8_t> readFill();
96710416564SRui Ueyama   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
968ff1f29e0SGeorge Rimar   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
969bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
970a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionDescription(StringRef Tok);
971db688454SEugene Leviant   StringMatcher readFilePatterns();
97207171f21SGeorge Rimar   std::vector<SectionPattern> readInputSectionsList();
973a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
974bbe38602SEugene Leviant   unsigned readPhdrType();
975be394db3SGeorge Rimar   SortSectionPolicy readSortKind();
976a35e39caSPetr Hosek   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
977c96da110SRafael Espindola   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
97803fc010eSGeorge Rimar   void readSort();
979eefa758eSGeorge Rimar   Expr readAssert();
980708019c4SRui Ueyama 
981708019c4SRui Ueyama   Expr readExpr();
982708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
983b71d6f7aSEugene Leviant   StringRef readParenLiteral();
984708019c4SRui Ueyama   Expr readPrimary();
985708019c4SRui Ueyama   Expr readTernary(Expr Cond);
9866ad7dfccSRui Ueyama   Expr readParenExpr();
987f7c5fbb1SRui Ueyama 
98820b6598cSGeorge Rimar   // For parsing version script.
989*2a00b846SRui Ueyama   void readVersionExtern(std::vector<SymbolVersion> *Globals);
99095769b4aSRui Ueyama   void readVersionDeclaration(StringRef VerStr);
99120b6598cSGeorge Rimar   void readGlobal(StringRef VerStr);
992bb6c01e7SGeorge Rimar   void readLocal(StringRef VerStr);
99320b6598cSGeorge Rimar 
99407320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
99516b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
996f7c5fbb1SRui Ueyama };
997f7c5fbb1SRui Ueyama 
99820b6598cSGeorge Rimar void ScriptParser::readVersionScript() {
99995769b4aSRui Ueyama   readVersionScriptCommand();
100020b6598cSGeorge Rimar   if (!atEOF())
100195769b4aSRui Ueyama     setError("EOF expected, but got " + next());
100295769b4aSRui Ueyama }
100395769b4aSRui Ueyama 
100495769b4aSRui Ueyama void ScriptParser::readVersionScriptCommand() {
100583043f23SRui Ueyama   if (consume("{")) {
100695769b4aSRui Ueyama     readVersionDeclaration("");
100720b6598cSGeorge Rimar     return;
100820b6598cSGeorge Rimar   }
100920b6598cSGeorge Rimar 
101095769b4aSRui Ueyama   while (!atEOF() && !Error && peek() != "}") {
101120b6598cSGeorge Rimar     StringRef VerStr = next();
101220b6598cSGeorge Rimar     if (VerStr == "{") {
101395769b4aSRui Ueyama       setError("anonymous version definition is used in "
101495769b4aSRui Ueyama                "combination with other version definitions");
101520b6598cSGeorge Rimar       return;
101620b6598cSGeorge Rimar     }
101720b6598cSGeorge Rimar     expect("{");
101895769b4aSRui Ueyama     readVersionDeclaration(VerStr);
101920b6598cSGeorge Rimar   }
102020b6598cSGeorge Rimar }
102120b6598cSGeorge Rimar 
102295769b4aSRui Ueyama void ScriptParser::readVersion() {
102395769b4aSRui Ueyama   expect("{");
102495769b4aSRui Ueyama   readVersionScriptCommand();
102595769b4aSRui Ueyama   expect("}");
102695769b4aSRui Ueyama }
102795769b4aSRui Ueyama 
102820b6598cSGeorge Rimar void ScriptParser::readLinkerScript() {
1029f7c5fbb1SRui Ueyama   while (!atEOF()) {
1030f7c5fbb1SRui Ueyama     StringRef Tok = next();
1031a27eeccaSRui Ueyama     if (Tok == ";")
1032a27eeccaSRui Ueyama       continue;
1033a27eeccaSRui Ueyama 
103420d03194SEugene Leviant     if (Tok == "ASSERT") {
103520d03194SEugene Leviant       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
103620d03194SEugene Leviant     } else if (Tok == "ENTRY") {
1037a27eeccaSRui Ueyama       readEntry();
1038a27eeccaSRui Ueyama     } else if (Tok == "EXTERN") {
1039a27eeccaSRui Ueyama       readExtern();
1040a27eeccaSRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
1041a27eeccaSRui Ueyama       readGroup();
1042a27eeccaSRui Ueyama     } else if (Tok == "INCLUDE") {
1043a27eeccaSRui Ueyama       readInclude();
1044a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT") {
1045a27eeccaSRui Ueyama       readOutput();
1046a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
1047a27eeccaSRui Ueyama       readOutputArch();
1048a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
1049a27eeccaSRui Ueyama       readOutputFormat();
1050a27eeccaSRui Ueyama     } else if (Tok == "PHDRS") {
1051a27eeccaSRui Ueyama       readPhdrs();
1052a27eeccaSRui Ueyama     } else if (Tok == "SEARCH_DIR") {
1053a27eeccaSRui Ueyama       readSearchDir();
1054a27eeccaSRui Ueyama     } else if (Tok == "SECTIONS") {
1055a27eeccaSRui Ueyama       readSections();
1056a27eeccaSRui Ueyama     } else if (Tok == "VERSION") {
1057a27eeccaSRui Ueyama       readVersion();
1058c96da110SRafael Espindola     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
10590df80befSPetr Hosek       Opt.Commands.emplace_back(Cmd);
1060e5d3ca50SPetr Hosek     } else {
10615761042dSGeorge Rimar       setError("unknown directive: " + Tok);
1062f7c5fbb1SRui Ueyama     }
1063f7c5fbb1SRui Ueyama   }
1064e5d3ca50SPetr Hosek }
1065f7c5fbb1SRui Ueyama 
1066717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
106716b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
10685af1687fSJustin Bogner     SmallString<128> PathData;
10695af1687fSJustin Bogner     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
107016b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
10715af1687fSJustin Bogner       Driver->addFile(Saver.save(Path));
107216b0cc9eSSimon Atanasyan       return;
107316b0cc9eSSimon Atanasyan     }
107416b0cc9eSSimon Atanasyan   }
107516b0cc9eSSimon Atanasyan 
1076f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
107752a1509eSRui Ueyama     Driver->addFile(S);
107852a1509eSRui Ueyama   } else if (S.startswith("=")) {
107952a1509eSRui Ueyama     if (Config->Sysroot.empty())
108052a1509eSRui Ueyama       Driver->addFile(S.substr(1));
108152a1509eSRui Ueyama     else
108252a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
108352a1509eSRui Ueyama   } else if (S.startswith("-l")) {
108421eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
1085a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
1086a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
108752a1509eSRui Ueyama   } else {
108852a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
108952a1509eSRui Ueyama     if (Path.empty())
1090777f9630SGeorge Rimar       setError("unable to find " + S);
1091025d59b1SRui Ueyama     else
109252a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
109352a1509eSRui Ueyama   }
109452a1509eSRui Ueyama }
109552a1509eSRui Ueyama 
1096717677afSRui Ueyama void ScriptParser::readAsNeeded() {
1097f7c5fbb1SRui Ueyama   expect("(");
109835da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
109935da9b6eSRui Ueyama   Config->AsNeeded = true;
110083043f23SRui Ueyama   while (!Error && !consume(")"))
1101cd574a5eSGeorge Rimar     addFile(unquote(next()));
110235da9b6eSRui Ueyama   Config->AsNeeded = Orig;
1103f7c5fbb1SRui Ueyama }
1104f7c5fbb1SRui Ueyama 
1105717677afSRui Ueyama void ScriptParser::readEntry() {
110690c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
110790c5099eSDenis Protivensky   expect("(");
110890c5099eSDenis Protivensky   StringRef Tok = next();
110990c5099eSDenis Protivensky   if (Config->Entry.empty())
111090c5099eSDenis Protivensky     Config->Entry = Tok;
111190c5099eSDenis Protivensky   expect(")");
111290c5099eSDenis Protivensky }
111390c5099eSDenis Protivensky 
1114717677afSRui Ueyama void ScriptParser::readExtern() {
111583f406cfSGeorge Rimar   expect("(");
111683043f23SRui Ueyama   while (!Error && !consume(")"))
1117a2acc931SRui Ueyama     Config->Undefined.push_back(next());
111883f406cfSGeorge Rimar }
111983f406cfSGeorge Rimar 
1120717677afSRui Ueyama void ScriptParser::readGroup() {
1121f7c5fbb1SRui Ueyama   expect("(");
112283043f23SRui Ueyama   while (!Error && !consume(")")) {
1123f7c5fbb1SRui Ueyama     StringRef Tok = next();
1124a2acc931SRui Ueyama     if (Tok == "AS_NEEDED")
1125f7c5fbb1SRui Ueyama       readAsNeeded();
1126a2acc931SRui Ueyama     else
1127cd574a5eSGeorge Rimar       addFile(unquote(Tok));
1128f7c5fbb1SRui Ueyama   }
1129f7c5fbb1SRui Ueyama }
1130f7c5fbb1SRui Ueyama 
1131717677afSRui Ueyama void ScriptParser::readInclude() {
113231aa1f83SRui Ueyama   StringRef Tok = next();
1133cd574a5eSGeorge Rimar   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
1134025d59b1SRui Ueyama   if (!MBOrErr) {
11355761042dSGeorge Rimar     setError("cannot open " + Tok);
1136025d59b1SRui Ueyama     return;
1137025d59b1SRui Ueyama   }
113831aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
1139a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1140a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
114131aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
114231aa1f83SRui Ueyama }
114331aa1f83SRui Ueyama 
1144717677afSRui Ueyama void ScriptParser::readOutput() {
1145ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
1146ee59282bSRui Ueyama   expect("(");
1147ee59282bSRui Ueyama   StringRef Tok = next();
1148ee59282bSRui Ueyama   if (Config->OutputFile.empty())
1149cd574a5eSGeorge Rimar     Config->OutputFile = unquote(Tok);
1150ee59282bSRui Ueyama   expect(")");
1151ee59282bSRui Ueyama }
1152ee59282bSRui Ueyama 
1153717677afSRui Ueyama void ScriptParser::readOutputArch() {
11549159ce93SDavide Italiano   // Error checking only for now.
11559159ce93SDavide Italiano   expect("(");
11565424e7c7SJustin Bogner   skip();
11579159ce93SDavide Italiano   expect(")");
11589159ce93SDavide Italiano }
11599159ce93SDavide Italiano 
1160717677afSRui Ueyama void ScriptParser::readOutputFormat() {
1161f7c5fbb1SRui Ueyama   // Error checking only for now.
1162f7c5fbb1SRui Ueyama   expect("(");
11635424e7c7SJustin Bogner   skip();
11646836c618SDavide Italiano   StringRef Tok = next();
11656836c618SDavide Italiano   if (Tok == ")")
11666836c618SDavide Italiano     return;
1167025d59b1SRui Ueyama   if (Tok != ",") {
11685761042dSGeorge Rimar     setError("unexpected token: " + Tok);
1169025d59b1SRui Ueyama     return;
1170025d59b1SRui Ueyama   }
11715424e7c7SJustin Bogner   skip();
11726836c618SDavide Italiano   expect(",");
11735424e7c7SJustin Bogner   skip();
1174f7c5fbb1SRui Ueyama   expect(")");
1175f7c5fbb1SRui Ueyama }
1176f7c5fbb1SRui Ueyama 
1177bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
1178bbe38602SEugene Leviant   expect("{");
117983043f23SRui Ueyama   while (!Error && !consume("}")) {
1180bbe38602SEugene Leviant     StringRef Tok = next();
118156b21c86SEugene Leviant     Opt.PhdrsCommands.push_back(
118256b21c86SEugene Leviant         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1183bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1184bbe38602SEugene Leviant 
1185bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
1186bbe38602SEugene Leviant     do {
1187bbe38602SEugene Leviant       Tok = next();
1188bbe38602SEugene Leviant       if (Tok == ";")
1189bbe38602SEugene Leviant         break;
1190bbe38602SEugene Leviant       if (Tok == "FILEHDR")
1191bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
1192bbe38602SEugene Leviant       else if (Tok == "PHDRS")
1193bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
119456b21c86SEugene Leviant       else if (Tok == "AT")
119556b21c86SEugene Leviant         PhdrCmd.LMAExpr = readParenExpr();
1196865bf863SEugene Leviant       else if (Tok == "FLAGS") {
1197865bf863SEugene Leviant         expect("(");
1198eb685cd7SRafael Espindola         // Passing 0 for the value of dot is a bit of a hack. It means that
1199eb685cd7SRafael Espindola         // we accept expressions like ".|1".
1200eb685cd7SRafael Espindola         PhdrCmd.Flags = readExpr()(0);
1201865bf863SEugene Leviant         expect(")");
1202865bf863SEugene Leviant       } else
1203bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
1204bbe38602SEugene Leviant     } while (!Error);
1205bbe38602SEugene Leviant   }
1206bbe38602SEugene Leviant }
1207bbe38602SEugene Leviant 
1208717677afSRui Ueyama void ScriptParser::readSearchDir() {
120968a39a65SDavide Italiano   expect("(");
121086c5fb82SRui Ueyama   StringRef Tok = next();
12116c7ad13fSRui Ueyama   if (!Config->Nostdlib)
1212cd574a5eSGeorge Rimar     Config->SearchPaths.push_back(unquote(Tok));
121368a39a65SDavide Italiano   expect(")");
121468a39a65SDavide Italiano }
121568a39a65SDavide Italiano 
1216717677afSRui Ueyama void ScriptParser::readSections() {
1217e05336ffSEugene Leviant   Opt.HasSections = true;
12188e3b38abSDenis Protivensky   expect("{");
121983043f23SRui Ueyama   while (!Error && !consume("}")) {
1220113cdec9SRui Ueyama     StringRef Tok = next();
1221c96da110SRafael Espindola     BaseCommand *Cmd = readProvideOrAssignment(Tok);
1222ceabe80eSEugene Leviant     if (!Cmd) {
1223ceabe80eSEugene Leviant       if (Tok == "ASSERT")
1224eefa758eSGeorge Rimar         Cmd = new AssertCommand(readAssert());
1225ceabe80eSEugene Leviant       else
122610416564SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
12278e3b38abSDenis Protivensky     }
122810416564SRui Ueyama     Opt.Commands.emplace_back(Cmd);
1229652852c5SGeorge Rimar   }
1230708019c4SRui Ueyama }
12318e3b38abSDenis Protivensky 
1232708019c4SRui Ueyama static int precedence(StringRef Op) {
1233708019c4SRui Ueyama   return StringSwitch<int>(Op)
12340120e3f2SRui Ueyama       .Cases("*", "/", 5)
12350120e3f2SRui Ueyama       .Cases("+", "-", 4)
12360120e3f2SRui Ueyama       .Cases("<<", ">>", 3)
12379c4ac5f2SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
12380120e3f2SRui Ueyama       .Cases("&", "|", 1)
1239708019c4SRui Ueyama       .Default(-1);
1240708019c4SRui Ueyama }
1241708019c4SRui Ueyama 
1242db688454SEugene Leviant StringMatcher ScriptParser::readFilePatterns() {
124310416564SRui Ueyama   std::vector<StringRef> V;
124483043f23SRui Ueyama   while (!Error && !consume(")"))
124510416564SRui Ueyama     V.push_back(next());
1246f91282e1SRui Ueyama   return StringMatcher(V);
12470702c4e8SGeorge Rimar }
12480702c4e8SGeorge Rimar 
1249be394db3SGeorge Rimar SortSectionPolicy ScriptParser::readSortKind() {
125083043f23SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
1251be394db3SGeorge Rimar     return SortSectionPolicy::Name;
125283043f23SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
1253be394db3SGeorge Rimar     return SortSectionPolicy::Alignment;
125483043f23SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
1255be394db3SGeorge Rimar     return SortSectionPolicy::Priority;
125683043f23SRui Ueyama   if (consume("SORT_NONE"))
1257be394db3SGeorge Rimar     return SortSectionPolicy::None;
1258b2a0abdfSRui Ueyama   return SortSectionPolicy::Default;
1259be394db3SGeorge Rimar }
1260be394db3SGeorge Rimar 
1261395281cfSGeorge Rimar // Method reads a list of sequence of excluded files and section globs given in
1262395281cfSGeorge Rimar // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1263395281cfSGeorge Rimar // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1264af03be19SGeorge Rimar // The semantics of that is next:
1265af03be19SGeorge Rimar // * Include .foo.1 from every file.
1266af03be19SGeorge Rimar // * Include .foo.2 from every file but a.o
1267af03be19SGeorge Rimar // * Include .foo.3 from every file but b.o
126807171f21SGeorge Rimar std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
126907171f21SGeorge Rimar   std::vector<SectionPattern> Ret;
1270601e9898SGeorge Rimar   while (!Error && peek() != ")") {
1271f91282e1SRui Ueyama     StringMatcher ExcludeFilePat;
127283043f23SRui Ueyama     if (consume("EXCLUDE_FILE")) {
1273395281cfSGeorge Rimar       expect("(");
1274f91282e1SRui Ueyama       ExcludeFilePat = readFilePatterns();
1275395281cfSGeorge Rimar     }
1276395281cfSGeorge Rimar 
1277601e9898SGeorge Rimar     std::vector<StringRef> V;
1278601e9898SGeorge Rimar     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1279395281cfSGeorge Rimar       V.push_back(next());
1280601e9898SGeorge Rimar 
1281601e9898SGeorge Rimar     if (!V.empty())
1282f91282e1SRui Ueyama       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
1283601e9898SGeorge Rimar     else
1284601e9898SGeorge Rimar       setError("section pattern is expected");
1285395281cfSGeorge Rimar   }
128607171f21SGeorge Rimar   return Ret;
1287395281cfSGeorge Rimar }
1288395281cfSGeorge Rimar 
128907171f21SGeorge Rimar // Section pattern grammar can have complex expressions, for example:
129007171f21SGeorge Rimar // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
129107171f21SGeorge Rimar // Generally is a sequence of globs and excludes that may be wrapped in a SORT()
129207171f21SGeorge Rimar // commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
129307171f21SGeorge Rimar // This methods handles wrapping sequences of excluded files and section globs
129407171f21SGeorge Rimar // into SORT() if that needed and reads them all.
1295a2496cbeSGeorge Rimar InputSectionDescription *
1296a2496cbeSGeorge Rimar ScriptParser::readInputSectionRules(StringRef FilePattern) {
1297c91930a1SGeorge Rimar   auto *Cmd = new InputSectionDescription(FilePattern);
12980ed42b0cSDavide Italiano   expect("(");
129983043f23SRui Ueyama   while (!HasError && !consume(")")) {
130007171f21SGeorge Rimar     SortSectionPolicy Outer = readSortKind();
130107171f21SGeorge Rimar     SortSectionPolicy Inner = SortSectionPolicy::Default;
130207171f21SGeorge Rimar     std::vector<SectionPattern> V;
130307171f21SGeorge Rimar     if (Outer != SortSectionPolicy::Default) {
13040702c4e8SGeorge Rimar       expect("(");
130507171f21SGeorge Rimar       Inner = readSortKind();
130607171f21SGeorge Rimar       if (Inner != SortSectionPolicy::Default) {
1307350ece4eSGeorge Rimar         expect("(");
130807171f21SGeorge Rimar         V = readInputSectionsList();
13090702c4e8SGeorge Rimar         expect(")");
1310350ece4eSGeorge Rimar       } else {
131107171f21SGeorge Rimar         V = readInputSectionsList();
1312350ece4eSGeorge Rimar       }
1313350ece4eSGeorge Rimar       expect(")");
131407171f21SGeorge Rimar     } else {
131507171f21SGeorge Rimar       V = readInputSectionsList();
13160659800eSGeorge Rimar     }
13170702c4e8SGeorge Rimar 
131807171f21SGeorge Rimar     for (SectionPattern &Pat : V) {
131907171f21SGeorge Rimar       Pat.SortInner = Inner;
132007171f21SGeorge Rimar       Pat.SortOuter = Outer;
132107171f21SGeorge Rimar     }
132207171f21SGeorge Rimar 
132307171f21SGeorge Rimar     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
132407171f21SGeorge Rimar   }
132510416564SRui Ueyama   return Cmd;
13260659800eSGeorge Rimar }
13270659800eSGeorge Rimar 
1328a2496cbeSGeorge Rimar InputSectionDescription *
1329a2496cbeSGeorge Rimar ScriptParser::readInputSectionDescription(StringRef Tok) {
13300659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
13310659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1332a2496cbeSGeorge Rimar   if (Tok == "KEEP") {
1333e7282797SDavide Italiano     expect("(");
1334a2496cbeSGeorge Rimar     StringRef FilePattern = next();
1335a2496cbeSGeorge Rimar     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
13360ed42b0cSDavide Italiano     expect(")");
1337cf43f179SEugene Leviant     Opt.KeptSections.push_back(Cmd);
133810416564SRui Ueyama     return Cmd;
133910416564SRui Ueyama   }
1340a2496cbeSGeorge Rimar   return readInputSectionRules(Tok);
13410659800eSGeorge Rimar }
13420659800eSGeorge Rimar 
134303fc010eSGeorge Rimar void ScriptParser::readSort() {
134403fc010eSGeorge Rimar   expect("(");
134503fc010eSGeorge Rimar   expect("CONSTRUCTORS");
134603fc010eSGeorge Rimar   expect(")");
134703fc010eSGeorge Rimar }
134803fc010eSGeorge Rimar 
1349eefa758eSGeorge Rimar Expr ScriptParser::readAssert() {
1350eefa758eSGeorge Rimar   expect("(");
1351eefa758eSGeorge Rimar   Expr E = readExpr();
1352eefa758eSGeorge Rimar   expect(",");
1353cd574a5eSGeorge Rimar   StringRef Msg = unquote(next());
1354eefa758eSGeorge Rimar   expect(")");
1355eefa758eSGeorge Rimar   return [=](uint64_t Dot) {
1356eefa758eSGeorge Rimar     uint64_t V = E(Dot);
1357eefa758eSGeorge Rimar     if (!V)
1358eefa758eSGeorge Rimar       error(Msg);
1359eefa758eSGeorge Rimar     return V;
1360eefa758eSGeorge Rimar   };
1361eefa758eSGeorge Rimar }
1362eefa758eSGeorge Rimar 
136325150e8bSRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
136425150e8bSRui Ueyama // alias for =fillexp section attribute, which is different from
136525150e8bSRui Ueyama // what GNU linkers do.
136625150e8bSRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1367ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readFill() {
1368ff1f29e0SGeorge Rimar   expect("(");
1369ff1f29e0SGeorge Rimar   std::vector<uint8_t> V = readOutputSectionFiller(next());
1370ff1f29e0SGeorge Rimar   expect(")");
1371ff1f29e0SGeorge Rimar   expect(";");
1372ff1f29e0SGeorge Rimar   return V;
1373ff1f29e0SGeorge Rimar }
1374ff1f29e0SGeorge Rimar 
137510416564SRui Ueyama OutputSectionCommand *
137610416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1377076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
137858e5c4dcSGeorge Rimar 
137958e5c4dcSGeorge Rimar   // Read an address expression.
138058e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
138158e5c4dcSGeorge Rimar   if (peek() != ":")
138258e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
138358e5c4dcSGeorge Rimar 
13848e3b38abSDenis Protivensky   expect(":");
1385246f681eSDavide Italiano 
138683043f23SRui Ueyama   if (consume("AT"))
1387b71d6f7aSEugene Leviant     Cmd->LMAExpr = readParenExpr();
138883043f23SRui Ueyama   if (consume("ALIGN"))
13896ad7dfccSRui Ueyama     Cmd->AlignExpr = readParenExpr();
139083043f23SRui Ueyama   if (consume("SUBALIGN"))
1391db24d9c3SGeorge Rimar     Cmd->SubalignExpr = readParenExpr();
1392630c6179SGeorge Rimar 
1393246f681eSDavide Italiano   // Parse constraints.
139483043f23SRui Ueyama   if (consume("ONLY_IF_RO"))
1395efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
139683043f23SRui Ueyama   if (consume("ONLY_IF_RW"))
1397efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
13988e3b38abSDenis Protivensky   expect("{");
13998ec77e64SRui Ueyama 
140083043f23SRui Ueyama   while (!Error && !consume("}")) {
1401ceabe80eSEugene Leviant     StringRef Tok = next();
1402c96da110SRafael Espindola     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1403ceabe80eSEugene Leviant       Cmd->Commands.emplace_back(Assignment);
1404e38cbab5SGeorge Rimar     else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1405e38cbab5SGeorge Rimar       Cmd->Commands.emplace_back(Data);
1406ff1f29e0SGeorge Rimar     else if (Tok == "FILL")
1407ff1f29e0SGeorge Rimar       Cmd->Filler = readFill();
1408ceabe80eSEugene Leviant     else if (Tok == "SORT")
140903fc010eSGeorge Rimar       readSort();
1410a2496cbeSGeorge Rimar     else if (peek() == "(")
1411a2496cbeSGeorge Rimar       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1412ceabe80eSEugene Leviant     else
1413ceabe80eSEugene Leviant       setError("unknown command " + Tok);
14148e3b38abSDenis Protivensky   }
1415076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
14164ebc5620SGeorge Rimar 
141783043f23SRui Ueyama   if (consume("="))
14184ebc5620SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next());
14194ebc5620SGeorge Rimar   else if (peek().startswith("="))
1420ff1f29e0SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next().drop_front());
14214ebc5620SGeorge Rimar 
142210416564SRui Ueyama   return Cmd;
1423f71caa2bSRui Ueyama }
14248ec77e64SRui Ueyama 
14252c8f1f04SRui Ueyama // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
14262c8f1f04SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
14272c8f1f04SRui Ueyama //
14282c8f1f04SRui Ueyama // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
14292c8f1f04SRui Ueyama // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
14302c8f1f04SRui Ueyama // as 32-bit big-endian values. We will do the same as ld.gold does
14312c8f1f04SRui Ueyama // because it's simpler than what ld.bfd does.
1432ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1433965827d6SRui Ueyama   uint32_t V;
1434ff1f29e0SGeorge Rimar   if (Tok.getAsInteger(0, V)) {
1435965827d6SRui Ueyama     setError("invalid filler expression: " + Tok);
1436f71caa2bSRui Ueyama     return {};
1437e2ee72b5SGeorge Rimar   }
1438965827d6SRui Ueyama   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
14398e3b38abSDenis Protivensky }
14408e3b38abSDenis Protivensky 
1441a35e39caSPetr Hosek SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1442a31c91b1SEugene Leviant   expect("(");
1443174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
1444a35e39caSPetr Hosek   Cmd->Provide = Provide;
1445174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
1446a31c91b1SEugene Leviant   expect(")");
1447a31c91b1SEugene Leviant   expect(";");
144810416564SRui Ueyama   return Cmd;
1449eda81a1bSEugene Leviant }
1450eda81a1bSEugene Leviant 
1451c96da110SRafael Espindola SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1452ceabe80eSEugene Leviant   SymbolAssignment *Cmd = nullptr;
1453ceabe80eSEugene Leviant   if (peek() == "=" || peek() == "+=") {
1454ceabe80eSEugene Leviant     Cmd = readAssignment(Tok);
1455ceabe80eSEugene Leviant     expect(";");
1456ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE") {
1457a35e39caSPetr Hosek     Cmd = readProvideHidden(true, false);
1458a35e39caSPetr Hosek   } else if (Tok == "HIDDEN") {
1459a35e39caSPetr Hosek     Cmd = readProvideHidden(false, true);
1460ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE_HIDDEN") {
1461a35e39caSPetr Hosek     Cmd = readProvideHidden(true, true);
1462ceabe80eSEugene Leviant   }
1463ceabe80eSEugene Leviant   return Cmd;
1464ceabe80eSEugene Leviant }
1465ceabe80eSEugene Leviant 
146630835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
146730835ea4SGeorge Rimar   if (S == ".")
146830835ea4SGeorge Rimar     return Dot;
1469884e786dSGeorge Rimar   return ScriptBase->getSymbolValue(S);
1470e32a3598SGeorge Rimar }
1471e32a3598SGeorge Rimar 
14722f831dcaSRafael Espindola static bool isAbsolute(StringRef S) {
14732f831dcaSRafael Espindola   if (S == ".")
14742f831dcaSRafael Espindola     return false;
14752f831dcaSRafael Espindola   return ScriptBase->isAbsolute(S);
14762f831dcaSRafael Espindola }
14772f831dcaSRafael Espindola 
147830835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
147930835ea4SGeorge Rimar   StringRef Op = next();
1480db741e72SEugene Leviant   Expr E;
148130835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
148283043f23SRui Ueyama   if (consume("ABSOLUTE")) {
14837c1381a0SRui Ueyama     // The RHS may be something like "ABSOLUTE(.) & 0xff".
14847c1381a0SRui Ueyama     // Call readExpr1 to read the whole expression.
14857c1381a0SRui Ueyama     E = readExpr1(readParenExpr(), 0);
14862f831dcaSRafael Espindola     E.IsAbsolute = []() { return true; };
1487db741e72SEugene Leviant   } else {
1488db741e72SEugene Leviant     E = readExpr();
1489db741e72SEugene Leviant   }
149030835ea4SGeorge Rimar   if (Op == "+=")
149130835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1492f661393aSRafael Espindola   return new SymbolAssignment(Name, E);
149330835ea4SGeorge Rimar }
149430835ea4SGeorge Rimar 
149530835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
149630835ea4SGeorge Rimar // script expression.
149730835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
149830835ea4SGeorge Rimar 
149936c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
150036c1cd23SRui Ueyama   if (Op == "*")
150136c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
150236c1cd23SRui Ueyama   if (Op == "/") {
150336c1cd23SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
150436c1cd23SRui Ueyama       uint64_t RHS = R(Dot);
150536c1cd23SRui Ueyama       if (RHS == 0) {
150636c1cd23SRui Ueyama         error("division by zero");
150736c1cd23SRui Ueyama         return 0;
150836c1cd23SRui Ueyama       }
150936c1cd23SRui Ueyama       return L(Dot) / RHS;
151036c1cd23SRui Ueyama     };
151136c1cd23SRui Ueyama   }
151236c1cd23SRui Ueyama   if (Op == "+")
15132f831dcaSRafael Espindola     return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
15142f831dcaSRafael Espindola             [=]() { return L.IsAbsolute() && R.IsAbsolute(); }};
151536c1cd23SRui Ueyama   if (Op == "-")
151636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1517c8ccd1f1SGeorge Rimar   if (Op == "<<")
1518c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1519c8ccd1f1SGeorge Rimar   if (Op == ">>")
1520c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
152136c1cd23SRui Ueyama   if (Op == "<")
152236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
152336c1cd23SRui Ueyama   if (Op == ">")
152436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
152536c1cd23SRui Ueyama   if (Op == ">=")
152636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
152736c1cd23SRui Ueyama   if (Op == "<=")
152836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
152936c1cd23SRui Ueyama   if (Op == "==")
153036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
153136c1cd23SRui Ueyama   if (Op == "!=")
153236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
153336c1cd23SRui Ueyama   if (Op == "&")
153436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1535cc3dd629SRafael Espindola   if (Op == "|")
1536cc3dd629SRafael Espindola     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
153736c1cd23SRui Ueyama   llvm_unreachable("invalid operator");
153836c1cd23SRui Ueyama }
153936c1cd23SRui Ueyama 
1540708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
1541708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
1542708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1543708019c4SRui Ueyama   while (!atEOF() && !Error) {
1544708019c4SRui Ueyama     // Read an operator and an expression.
1545708019c4SRui Ueyama     StringRef Op1 = peek();
1546708019c4SRui Ueyama     if (Op1 == "?")
1547708019c4SRui Ueyama       return readTernary(Lhs);
1548708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
1549a31c91b1SEugene Leviant       break;
15505424e7c7SJustin Bogner     skip();
1551708019c4SRui Ueyama     Expr Rhs = readPrimary();
1552708019c4SRui Ueyama 
1553708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
1554708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
1555708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
1556708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
1557708019c4SRui Ueyama     while (!atEOF()) {
1558708019c4SRui Ueyama       StringRef Op2 = peek();
1559708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
1560eda81a1bSEugene Leviant         break;
1561708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
1562eda81a1bSEugene Leviant     }
1563708019c4SRui Ueyama 
1564708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
1565708019c4SRui Ueyama   }
1566708019c4SRui Ueyama   return Lhs;
1567708019c4SRui Ueyama }
1568708019c4SRui Ueyama 
1569708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
1570e2cc07bcSMichael J. Spencer   if (S == "COMMONPAGESIZE")
1571708019c4SRui Ueyama     return Target->PageSize;
1572e2cc07bcSMichael J. Spencer   if (S == "MAXPAGESIZE")
1573997f8838SPetr Hosek     return Config->MaxPageSize;
1574708019c4SRui Ueyama   error("unknown constant: " + S);
1575708019c4SRui Ueyama   return 0;
1576708019c4SRui Ueyama }
1577708019c4SRui Ueyama 
1578626e0b08SRui Ueyama // Parses Tok as an integer. Returns true if successful.
1579626e0b08SRui Ueyama // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1580626e0b08SRui Ueyama // and decimal numbers. Decimal numbers may have "K" (kilo) or
1581626e0b08SRui Ueyama // "M" (mega) prefixes.
15829f2f7ad9SGeorge Rimar static bool readInteger(StringRef Tok, uint64_t &Result) {
1583eaeafb2bSSimon Atanasyan   if (Tok.startswith("-")) {
1584eaeafb2bSSimon Atanasyan     if (!readInteger(Tok.substr(1), Result))
1585eaeafb2bSSimon Atanasyan       return false;
1586eaeafb2bSSimon Atanasyan     Result = -Result;
1587eaeafb2bSSimon Atanasyan     return true;
1588eaeafb2bSSimon Atanasyan   }
15899f2f7ad9SGeorge Rimar   if (Tok.startswith_lower("0x"))
15909f2f7ad9SGeorge Rimar     return !Tok.substr(2).getAsInteger(16, Result);
15919f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("H"))
15929f2f7ad9SGeorge Rimar     return !Tok.drop_back().getAsInteger(16, Result);
15939f2f7ad9SGeorge Rimar 
15949f2f7ad9SGeorge Rimar   int Suffix = 1;
15959f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("K")) {
15969f2f7ad9SGeorge Rimar     Suffix = 1024;
15979f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
15989f2f7ad9SGeorge Rimar   } else if (Tok.endswith_lower("M")) {
15999f2f7ad9SGeorge Rimar     Suffix = 1024 * 1024;
16009f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
16019f2f7ad9SGeorge Rimar   }
16029f2f7ad9SGeorge Rimar   if (Tok.getAsInteger(10, Result))
16039f2f7ad9SGeorge Rimar     return false;
16049f2f7ad9SGeorge Rimar   Result *= Suffix;
16059f2f7ad9SGeorge Rimar   return true;
16069f2f7ad9SGeorge Rimar }
16079f2f7ad9SGeorge Rimar 
1608e38cbab5SGeorge Rimar BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1609e38cbab5SGeorge Rimar   int Size = StringSwitch<unsigned>(Tok)
1610e38cbab5SGeorge Rimar                  .Case("BYTE", 1)
1611e38cbab5SGeorge Rimar                  .Case("SHORT", 2)
1612e38cbab5SGeorge Rimar                  .Case("LONG", 4)
1613e38cbab5SGeorge Rimar                  .Case("QUAD", 8)
1614e38cbab5SGeorge Rimar                  .Default(-1);
1615e38cbab5SGeorge Rimar   if (Size == -1)
1616e38cbab5SGeorge Rimar     return nullptr;
1617e38cbab5SGeorge Rimar 
1618e38cbab5SGeorge Rimar   expect("(");
1619e38cbab5SGeorge Rimar   uint64_t Val = 0;
1620e38cbab5SGeorge Rimar   StringRef S = next();
1621e38cbab5SGeorge Rimar   if (!readInteger(S, Val))
1622e38cbab5SGeorge Rimar     setError("unexpected value: " + S);
1623e38cbab5SGeorge Rimar   expect(")");
1624e38cbab5SGeorge Rimar   return new BytesDataCommand(Val, Size);
1625e38cbab5SGeorge Rimar }
1626e38cbab5SGeorge Rimar 
1627b71d6f7aSEugene Leviant StringRef ScriptParser::readParenLiteral() {
1628b71d6f7aSEugene Leviant   expect("(");
1629b71d6f7aSEugene Leviant   StringRef Tok = next();
1630b71d6f7aSEugene Leviant   expect(")");
1631b71d6f7aSEugene Leviant   return Tok;
1632b71d6f7aSEugene Leviant }
1633b71d6f7aSEugene Leviant 
1634708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
16356ad7dfccSRui Ueyama   if (peek() == "(")
16366ad7dfccSRui Ueyama     return readParenExpr();
1637708019c4SRui Ueyama 
16386ad7dfccSRui Ueyama   StringRef Tok = next();
1639708019c4SRui Ueyama 
1640eaeafb2bSSimon Atanasyan   if (Tok == "~") {
1641eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1642eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return ~E(Dot); };
1643eaeafb2bSSimon Atanasyan   }
1644eaeafb2bSSimon Atanasyan   if (Tok == "-") {
1645eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1646eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return -E(Dot); };
1647eaeafb2bSSimon Atanasyan   }
1648eaeafb2bSSimon Atanasyan 
1649708019c4SRui Ueyama   // Built-in functions are parsed here.
1650708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
165196659df0SGeorge Rimar   if (Tok == "ADDR") {
1652b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1653884e786dSGeorge Rimar     return
1654884e786dSGeorge Rimar         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
165596659df0SGeorge Rimar   }
1656b71d6f7aSEugene Leviant   if (Tok == "LOADADDR") {
1657b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1658b71d6f7aSEugene Leviant     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1659b71d6f7aSEugene Leviant   }
1660eefa758eSGeorge Rimar   if (Tok == "ASSERT")
1661eefa758eSGeorge Rimar     return readAssert();
1662708019c4SRui Ueyama   if (Tok == "ALIGN") {
16636ad7dfccSRui Ueyama     Expr E = readParenExpr();
1664708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1665708019c4SRui Ueyama   }
1666708019c4SRui Ueyama   if (Tok == "CONSTANT") {
1667b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1668b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return getConstant(Name); };
1669708019c4SRui Ueyama   }
1670f34f45fdSGeorge Rimar   if (Tok == "DEFINED") {
1671f34f45fdSGeorge Rimar     expect("(");
1672f34f45fdSGeorge Rimar     StringRef Tok = next();
1673f34f45fdSGeorge Rimar     expect(")");
1674f2821028SGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
1675f34f45fdSGeorge Rimar   }
167654c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
167754c145ceSRafael Espindola     expect("(");
16785424e7c7SJustin Bogner     skip();
167954c145ceSRafael Espindola     expect(",");
16808c658bf8SGeorge Rimar     Expr E = readExpr();
168154c145ceSRafael Espindola     expect(")");
16828c658bf8SGeorge Rimar     return [=](uint64_t Dot) { return E(Dot); };
168354c145ceSRafael Espindola   }
1684708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
1685708019c4SRui Ueyama     expect("(");
1686708019c4SRui Ueyama     Expr E = readExpr();
1687708019c4SRui Ueyama     expect(",");
1688708019c4SRui Ueyama     readExpr();
1689708019c4SRui Ueyama     expect(")");
1690f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1691708019c4SRui Ueyama   }
1692708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
1693708019c4SRui Ueyama     expect("(");
1694708019c4SRui Ueyama     expect(".");
1695708019c4SRui Ueyama     expect(")");
1696708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
1697708019c4SRui Ueyama   }
1698276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
1699276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1700276b4e64SGeorge Rimar   // the next page boundary for simplicity.
1701276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
1702276b4e64SGeorge Rimar     expect("(");
170397bdc722SRafael Espindola     readExpr();
1704276b4e64SGeorge Rimar     expect(",");
1705276b4e64SGeorge Rimar     readExpr();
1706276b4e64SGeorge Rimar     expect(")");
1707276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1708276b4e64SGeorge Rimar   }
17099e69450eSGeorge Rimar   if (Tok == "SIZEOF") {
1710b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1711b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
17129e69450eSGeorge Rimar   }
171336fac7f0SEugene Leviant   if (Tok == "ALIGNOF") {
1714b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1715b0de56b5SRafael Espindola     return
1716b0de56b5SRafael Espindola         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
171736fac7f0SEugene Leviant   }
1718e32a3598SGeorge Rimar   if (Tok == "SIZEOF_HEADERS")
1719b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1720708019c4SRui Ueyama 
17219f2f7ad9SGeorge Rimar   // Tok is a literal number.
17229f2f7ad9SGeorge Rimar   uint64_t V;
17239f2f7ad9SGeorge Rimar   if (readInteger(Tok, V))
1724b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return V; };
17259f2f7ad9SGeorge Rimar 
17269f2f7ad9SGeorge Rimar   // Tok is a symbol name.
172730835ea4SGeorge Rimar   if (Tok != "." && !isValidCIdentifier(Tok))
1728708019c4SRui Ueyama     setError("malformed number: " + Tok);
17292f831dcaSRafael Espindola   return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
17302f831dcaSRafael Espindola           [=]() { return isAbsolute(Tok); }};
1731a9c5a528SGeorge Rimar }
1732708019c4SRui Ueyama 
1733708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
17345424e7c7SJustin Bogner   skip();
1735708019c4SRui Ueyama   Expr L = readExpr();
1736708019c4SRui Ueyama   expect(":");
1737708019c4SRui Ueyama   Expr R = readExpr();
1738708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1739708019c4SRui Ueyama }
1740708019c4SRui Ueyama 
17416ad7dfccSRui Ueyama Expr ScriptParser::readParenExpr() {
17426ad7dfccSRui Ueyama   expect("(");
17436ad7dfccSRui Ueyama   Expr E = readExpr();
17446ad7dfccSRui Ueyama   expect(")");
17456ad7dfccSRui Ueyama   return E;
17466ad7dfccSRui Ueyama }
17476ad7dfccSRui Ueyama 
1748bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1749bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
1750bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
1751bbe38602SEugene Leviant     StringRef Tok = next();
1752da841c16SGeorge Rimar     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1753bbe38602SEugene Leviant   }
1754bbe38602SEugene Leviant   return Phdrs;
1755bbe38602SEugene Leviant }
1756bbe38602SEugene Leviant 
175795dd718cSGeorge Rimar // Read a program header type name. The next token must be a
175895dd718cSGeorge Rimar // name of a program header type or a constant (e.g. "0x3").
1759bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
1760bbe38602SEugene Leviant   StringRef Tok = next();
176195dd718cSGeorge Rimar   uint64_t Val;
176295dd718cSGeorge Rimar   if (readInteger(Tok, Val))
176395dd718cSGeorge Rimar     return Val;
176495dd718cSGeorge Rimar 
1765b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
1766b0f6c590SRui Ueyama                      .Case("PT_NULL", PT_NULL)
1767b0f6c590SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
1768b0f6c590SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1769b0f6c590SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
1770b0f6c590SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
1771b0f6c590SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
1772b0f6c590SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
1773b0f6c590SRui Ueyama                      .Case("PT_TLS", PT_TLS)
1774b0f6c590SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1775b0f6c590SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1776b0f6c590SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1777270173f2SGeorge Rimar                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1778cc6e567cSGeorge Rimar                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1779b0f6c590SRui Ueyama                      .Default(-1);
1780bbe38602SEugene Leviant 
1781b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1782b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1783b0f6c590SRui Ueyama     return PT_NULL;
1784b0f6c590SRui Ueyama   }
1785b0f6c590SRui Ueyama   return Ret;
1786bbe38602SEugene Leviant }
1787bbe38602SEugene Leviant 
178895769b4aSRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
178920b6598cSGeorge Rimar   // Identifiers start at 2 because 0 and 1 are reserved
179020b6598cSGeorge Rimar   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
179120b6598cSGeorge Rimar   size_t VersionId = Config->VersionDefinitions.size() + 2;
179220b6598cSGeorge Rimar   Config->VersionDefinitions.push_back({VerStr, VersionId});
179320b6598cSGeorge Rimar 
179483043f23SRui Ueyama   if (consume("global:") || peek() != "local:")
179520b6598cSGeorge Rimar     readGlobal(VerStr);
179683043f23SRui Ueyama   if (consume("local:"))
1797bb6c01e7SGeorge Rimar     readLocal(VerStr);
179820b6598cSGeorge Rimar   expect("}");
179920b6598cSGeorge Rimar 
180020b6598cSGeorge Rimar   // Each version may have a parent version. For example, "Ver2" defined as
180120b6598cSGeorge Rimar   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
180220b6598cSGeorge Rimar   // version hierarchy is, probably against your instinct, purely for human; the
180320b6598cSGeorge Rimar   // runtime doesn't care about them at all. In LLD, we simply skip the token.
180420b6598cSGeorge Rimar   if (!VerStr.empty() && peek() != ";")
18055424e7c7SJustin Bogner     skip();
180620b6598cSGeorge Rimar   expect(";");
180720b6598cSGeorge Rimar }
180820b6598cSGeorge Rimar 
1809bb6c01e7SGeorge Rimar void ScriptParser::readLocal(StringRef VerStr) {
1810bb6c01e7SGeorge Rimar   if (consume("*")) {
181120b6598cSGeorge Rimar     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
181220b6598cSGeorge Rimar     expect(";");
1813bb6c01e7SGeorge Rimar     return;
1814bb6c01e7SGeorge Rimar   }
1815bb6c01e7SGeorge Rimar 
1816bb6c01e7SGeorge Rimar   if (VerStr.empty())
1817bb6c01e7SGeorge Rimar     setError("locals list for anonymous version is not supported");
1818bb6c01e7SGeorge Rimar 
1819bb6c01e7SGeorge Rimar   std::vector<SymbolVersion> &Locals = Config->VersionDefinitions.back().Locals;
1820bb6c01e7SGeorge Rimar   while (!Error && peek() != "}") {
1821bb6c01e7SGeorge Rimar     StringRef Tok = next();
1822bb6c01e7SGeorge Rimar     Locals.push_back({unquote(Tok), false, hasWildcard(Tok)});
1823bb6c01e7SGeorge Rimar     expect(";");
1824bb6c01e7SGeorge Rimar   }
182520b6598cSGeorge Rimar }
182620b6598cSGeorge Rimar 
1827*2a00b846SRui Ueyama void ScriptParser::readVersionExtern(std::vector<SymbolVersion> *Globals) {
1828cd574a5eSGeorge Rimar   expect("\"C++\"");
182920b6598cSGeorge Rimar   expect("{");
183020b6598cSGeorge Rimar 
183120b6598cSGeorge Rimar   for (;;) {
183220b6598cSGeorge Rimar     if (peek() == "}" || Error)
183320b6598cSGeorge Rimar       break;
1834cd574a5eSGeorge Rimar     bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1835cd574a5eSGeorge Rimar     Globals->push_back({unquote(next()), true, HasWildcard});
183620b6598cSGeorge Rimar     expect(";");
183720b6598cSGeorge Rimar   }
183820b6598cSGeorge Rimar 
183920b6598cSGeorge Rimar   expect("}");
184020b6598cSGeorge Rimar   expect(";");
184120b6598cSGeorge Rimar }
184220b6598cSGeorge Rimar 
184320b6598cSGeorge Rimar void ScriptParser::readGlobal(StringRef VerStr) {
184420b6598cSGeorge Rimar   std::vector<SymbolVersion> *Globals;
184520b6598cSGeorge Rimar   if (VerStr.empty())
184620b6598cSGeorge Rimar     Globals = &Config->VersionScriptGlobals;
184720b6598cSGeorge Rimar   else
184820b6598cSGeorge Rimar     Globals = &Config->VersionDefinitions.back().Globals;
184920b6598cSGeorge Rimar 
185020b6598cSGeorge Rimar   for (;;) {
185183043f23SRui Ueyama     if (consume("extern"))
1852*2a00b846SRui Ueyama       readVersionExtern(Globals);
185320b6598cSGeorge Rimar 
185420b6598cSGeorge Rimar     StringRef Cur = peek();
185520b6598cSGeorge Rimar     if (Cur == "}" || Cur == "local:" || Error)
185620b6598cSGeorge Rimar       return;
18575424e7c7SJustin Bogner     skip();
1858cd574a5eSGeorge Rimar     Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
185920b6598cSGeorge Rimar     expect(";");
186020b6598cSGeorge Rimar   }
186120b6598cSGeorge Rimar }
186220b6598cSGeorge Rimar 
186316b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
186416b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
186516b0cc9eSSimon Atanasyan     return false;
186616b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
186716b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
186816b0cc9eSSimon Atanasyan       return true;
186916b0cc9eSSimon Atanasyan   return false;
187016b0cc9eSSimon Atanasyan }
187116b0cc9eSSimon Atanasyan 
187207320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
187316b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
187420b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
187520b6598cSGeorge Rimar }
187620b6598cSGeorge Rimar 
187720b6598cSGeorge Rimar void elf::readVersionScript(MemoryBufferRef MB) {
187820b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), false).readVersionScript();
1879f7c5fbb1SRui Ueyama }
18801ebc8ed7SRui Ueyama 
188107320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
188207320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
188307320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
188407320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1885