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;
67*1bdaf3e3SRui Ueyama   Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
68*1bdaf3e3SRui Ueyama                                             0, 0, STB_GLOBAL, 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 
5169546fffbSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
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;
529e08e78dfSRafael Espindola         std::vector<OutputSectionBase *> Secs =
530e08e78dfSRafael Espindola             findSections<ELFT>(Cmd->Name, *OutputSections);
5316d38e4dbSRafael Espindola         if (!Secs.empty())
5326d38e4dbSRafael Espindola           return false;
5336d38e4dbSRafael Espindola         for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
5346d38e4dbSRafael Espindola           if (!isa<InputSectionDescription>(I.get()))
5356d38e4dbSRafael Espindola             return false;
5366d38e4dbSRafael Espindola         return true;
5376d38e4dbSRafael Espindola       });
5386d38e4dbSRafael Espindola   Opt.Commands.erase(Pos, Opt.Commands.end());
5396d38e4dbSRafael Espindola 
5409546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
5419546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
5429546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
5439546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
5449546fffbSRafael Espindola   uintX_t Flags = SHF_ALLOC;
5459546fffbSRafael Espindola   uint32_t Type = 0;
5469546fffbSRafael Espindola   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
5479546fffbSRafael Espindola     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
5489546fffbSRafael Espindola     if (!Cmd)
5499546fffbSRafael Espindola       continue;
550e08e78dfSRafael Espindola     std::vector<OutputSectionBase *> Secs =
551e08e78dfSRafael Espindola         findSections<ELFT>(Cmd->Name, *OutputSections);
5529546fffbSRafael Espindola     if (!Secs.empty()) {
55304a2e348SRafael Espindola       Flags = Secs[0]->Flags;
55404a2e348SRafael Espindola       Type = Secs[0]->Type;
5559546fffbSRafael Espindola       continue;
5569546fffbSRafael Espindola     }
5579546fffbSRafael Espindola 
55895642b95SRui Ueyama     auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
5599546fffbSRafael Espindola     OutputSections->push_back(OutSec);
5609546fffbSRafael Espindola   }
5619546fffbSRafael Espindola }
5629546fffbSRafael Espindola 
56315c57951SRafael Espindola // When placing orphan sections, we want to place them after symbol assignments
56415c57951SRafael Espindola // so that an orphan after
56515c57951SRafael Espindola //   begin_foo = .;
56615c57951SRafael Espindola //   foo : { *(foo) }
56715c57951SRafael Espindola //   end_foo = .;
56815c57951SRafael Espindola // doesn't break the intended meaning of the begin/end symbols.
56915c57951SRafael Espindola // We don't want to go over sections since Writer<ELFT>::sortSections is the
57015c57951SRafael Espindola // one in charge of deciding the order of the sections.
57115c57951SRafael Espindola // We don't want to go over alignments, since doing so in
57215c57951SRafael Espindola //  rx_sec : { *(rx_sec) }
57315c57951SRafael Espindola //  . = ALIGN(0x1000);
57415c57951SRafael Espindola //  /* The RW PT_LOAD starts here*/
57515c57951SRafael Espindola //  rw_sec : { *(rw_sec) }
57615c57951SRafael Espindola // would mean that the RW PT_LOAD would become unaligned.
57715c57951SRafael Espindola static bool shouldSkip(const BaseCommand &Cmd) {
57815c57951SRafael Espindola   if (isa<OutputSectionCommand>(Cmd))
57915c57951SRafael Espindola     return false;
58015c57951SRafael Espindola   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
58115c57951SRafael Espindola   if (!Assign)
58215c57951SRafael Espindola     return true;
58315c57951SRafael Espindola   return Assign->Name != ".";
58415c57951SRafael Espindola }
58515c57951SRafael Espindola 
5866d91fce5SRafael Espindola template <class ELFT>
5876d91fce5SRafael Espindola void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
588652852c5SGeorge Rimar   // Orphan sections are sections present in the input files which
5897c18c28cSRui Ueyama   // are not explicitly placed into the output file by the linker script.
5907c18c28cSRui Ueyama   // We place orphan sections at end of file.
5917c18c28cSRui Ueyama   // Other linkers places them using some heuristics as described in
592652852c5SGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
593aab6d5c5SRafael Espindola 
594aab6d5c5SRafael Espindola   // The OutputSections are already in the correct order.
595aab6d5c5SRafael Espindola   // This loops creates or moves commands as needed so that they are in the
596aab6d5c5SRafael Espindola   // correct order.
597aab6d5c5SRafael Espindola   int CmdIndex = 0;
598e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
599652852c5SGeorge Rimar     StringRef Name = Sec->getName();
600aab6d5c5SRafael Espindola 
601aab6d5c5SRafael Espindola     // Find the last spot where we can insert a command and still get the
60215c57951SRafael Espindola     // correct result.
603aab6d5c5SRafael Espindola     auto CmdIter = Opt.Commands.begin() + CmdIndex;
604aab6d5c5SRafael Espindola     auto E = Opt.Commands.end();
60515c57951SRafael Espindola     while (CmdIter != E && shouldSkip(**CmdIter)) {
606aab6d5c5SRafael Espindola       ++CmdIter;
607aab6d5c5SRafael Espindola       ++CmdIndex;
608aab6d5c5SRafael Espindola     }
609aab6d5c5SRafael Espindola 
610aab6d5c5SRafael Espindola     auto Pos =
611aab6d5c5SRafael Espindola         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
612aab6d5c5SRafael Espindola           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
613aab6d5c5SRafael Espindola           return Cmd && Cmd->Name == Name;
614aab6d5c5SRafael Espindola         });
615aab6d5c5SRafael Espindola     if (Pos == E) {
616aab6d5c5SRafael Espindola       Opt.Commands.insert(CmdIter,
617aab6d5c5SRafael Espindola                           llvm::make_unique<OutputSectionCommand>(Name));
618aab6d5c5SRafael Espindola       ++CmdIndex;
61915c57951SRafael Espindola       continue;
62015c57951SRafael Espindola     }
62115c57951SRafael Espindola 
62215c57951SRafael Espindola     // Continue from where we found it.
62315c57951SRafael Espindola     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
624652852c5SGeorge Rimar   }
625652852c5SGeorge Rimar 
6267c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
627be607334SRafael Espindola   Dot = 0;
628652852c5SGeorge Rimar 
629076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
630076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
6318d083e6aSRui Ueyama       if (Cmd->Name == ".") {
6328d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
6338d083e6aSRui Ueyama       } else if (Cmd->Sym) {
634e08e78dfSRafael Espindola         assignSectionSymbol<ELFT>(
635e08e78dfSRafael Espindola             Cmd, CurOutSec ? CurOutSec : (*OutputSections)[0], Dot);
6368d083e6aSRui Ueyama       }
63705ef4cffSRui Ueyama       continue;
638652852c5SGeorge Rimar     }
639652852c5SGeorge Rimar 
640eefa758eSGeorge Rimar     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
641eefa758eSGeorge Rimar       Cmd->Expression(Dot);
642eefa758eSGeorge Rimar       continue;
643eefa758eSGeorge Rimar     }
644eefa758eSGeorge Rimar 
645076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
646652852c5SGeorge Rimar 
64758e5c4dcSGeorge Rimar     if (Cmd->AddrExpr)
64858e5c4dcSGeorge Rimar       Dot = Cmd->AddrExpr(Dot);
64958e5c4dcSGeorge Rimar 
650d3190795SRafael Espindola     assignOffsets(Cmd);
651a14b13d8SGeorge Rimar   }
652467c4d55SEugene Leviant 
653aab6d5c5SRafael Espindola   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
654e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
65504a2e348SRafael Espindola     if (Sec->Flags & SHF_ALLOC)
656e08e78dfSRafael Espindola       MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
657aab6d5c5SRafael Espindola     else
65804a2e348SRafael Espindola       Sec->Addr = 0;
659aab6d5c5SRafael Espindola   }
660aab6d5c5SRafael Espindola 
6610d4b6d5cSRafael Espindola   uintX_t HeaderSize = getHeaderSize();
6626d91fce5SRafael Espindola   auto FirstPTLoad =
6636d91fce5SRafael Espindola       std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
6646d91fce5SRafael Espindola         return E.H.p_type == PT_LOAD;
6656d91fce5SRafael Espindola       });
666db35fdf7SEugene Leviant 
6676d91fce5SRafael Espindola   if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
668db35fdf7SEugene Leviant     // If linker script specifies program headers and first PT_LOAD doesn't
669db35fdf7SEugene Leviant     // have both PHDRS and FILEHDR attributes then do nothing
670db35fdf7SEugene Leviant     if (!Opt.PhdrsCommands.empty()) {
671db35fdf7SEugene Leviant       size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
672db35fdf7SEugene Leviant       if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
673db35fdf7SEugene Leviant           !Opt.PhdrsCommands[SegNum].HasFilehdr)
674db35fdf7SEugene Leviant         return;
675db35fdf7SEugene Leviant     }
67664c32d6fSRafael Espindola     // ELF and Program headers need to be right before the first section in
677b91e7118SGeorge Rimar     // memory. Set their addresses accordingly.
6784ec013acSRafael Espindola     MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
67904a2e348SRafael Espindola     Out<ELFT>::ElfHeader->Addr = MinVA;
68004a2e348SRafael Espindola     Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
6816d91fce5SRafael Espindola     FirstPTLoad->First = Out<ELFT>::ElfHeader;
6826d91fce5SRafael Espindola     if (!FirstPTLoad->Last)
6836d91fce5SRafael Espindola       FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
684cd8eaf89SEugene Leviant   } else if (!FirstPTLoad->First) {
685cd8eaf89SEugene Leviant     // Sometimes the very first PT_LOAD segment can be empty.
686cd8eaf89SEugene Leviant     // This happens if (all conditions met):
687cd8eaf89SEugene Leviant     //  - Linker script is used
688cd8eaf89SEugene Leviant     //  - First section in ELF image is not RO
689cd8eaf89SEugene Leviant     //  - Not enough space for program headers.
690cd8eaf89SEugene Leviant     // The code below removes empty PT_LOAD segment and updates
691cd8eaf89SEugene Leviant     // program headers size.
692cd8eaf89SEugene Leviant     Phdrs.erase(FirstPTLoad);
69304a2e348SRafael Espindola     Out<ELFT>::ProgramHeaders->Size =
69404a2e348SRafael Espindola         sizeof(typename ELFT::Phdr) * Phdrs.size();
6956d91fce5SRafael Espindola   }
696fb8978fcSDima Stepanov }
697652852c5SGeorge Rimar 
698464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
69907320e40SRui Ueyama template <class ELFT>
700a4b41dcaSRafael Espindola std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
701edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
702bbe38602SEugene Leviant 
703464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
704464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
705ce30b1c7SEugene Leviant   std::vector<size_t> DefPhdrIds;
706bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
707edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
708edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
709bbe38602SEugene Leviant 
710bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
711adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
712bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
713adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
71456b21c86SEugene Leviant 
71556b21c86SEugene Leviant     if (Cmd.LMAExpr) {
71656b21c86SEugene Leviant       Phdr.H.p_paddr = Cmd.LMAExpr(0);
71756b21c86SEugene Leviant       Phdr.HasLMA = true;
71856b21c86SEugene Leviant     }
719ce30b1c7SEugene Leviant 
720ce30b1c7SEugene Leviant     // If output section command doesn't specify any segments,
721ce30b1c7SEugene Leviant     // and we haven't previously assigned any section to segment,
722ce30b1c7SEugene Leviant     // then we simply assign section to the very first load segment.
723ce30b1c7SEugene Leviant     // Below is an example of such linker script:
724ce30b1c7SEugene Leviant     // PHDRS { seg PT_LOAD; }
725ce30b1c7SEugene Leviant     // SECTIONS { .aaa : { *(.aaa) } }
726ce30b1c7SEugene Leviant     if (DefPhdrIds.empty() && Phdr.H.p_type == PT_LOAD)
727ce30b1c7SEugene Leviant       DefPhdrIds.push_back(Ret.size() - 1);
728bbe38602SEugene Leviant   }
729bbe38602SEugene Leviant 
730464daadcSRui Ueyama   // Add output sections to program headers.
731e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections) {
73204a2e348SRafael Espindola     if (!(Sec->Flags & SHF_ALLOC))
733bbe38602SEugene Leviant       break;
734bbe38602SEugene Leviant 
735edebbdf1SRui Ueyama     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
736ce30b1c7SEugene Leviant     if (PhdrIds.empty())
737ce30b1c7SEugene Leviant       PhdrIds = std::move(DefPhdrIds);
738ce30b1c7SEugene Leviant 
739bbe38602SEugene Leviant     // Assign headers specified by linker script
740bbe38602SEugene Leviant     for (size_t Id : PhdrIds) {
741edebbdf1SRui Ueyama       Ret[Id].add(Sec);
742865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
7430b113671SRafael Espindola         Ret[Id].H.p_flags |= Sec->getPhdrFlags();
744bbe38602SEugene Leviant     }
745ce30b1c7SEugene Leviant     DefPhdrIds = std::move(PhdrIds);
746bbe38602SEugene Leviant   }
747edebbdf1SRui Ueyama   return Ret;
748bbe38602SEugene Leviant }
749bbe38602SEugene Leviant 
750f9bc3bd2SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
751f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
752f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
753f9bc3bd2SEugene Leviant   return !Opt.PhdrsCommands.empty() &&
754f9bc3bd2SEugene Leviant          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
755f9bc3bd2SEugene Leviant            return Cmd.Type == PT_INTERP;
756f9bc3bd2SEugene Leviant          }) == Opt.PhdrsCommands.end();
757f9bc3bd2SEugene Leviant }
758f9bc3bd2SEugene Leviant 
759bbe38602SEugene Leviant template <class ELFT>
76007320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
761f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
762f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
763f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
764f6c3ccefSGeorge Rimar         return Cmd->Filler;
765e2ee72b5SGeorge Rimar   return {};
766e2ee72b5SGeorge Rimar }
767e2ee72b5SGeorge Rimar 
768e38cbab5SGeorge Rimar template <class ELFT>
769e38cbab5SGeorge Rimar static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
770e38cbab5SGeorge Rimar   const endianness E = ELFT::TargetEndianness;
771e38cbab5SGeorge Rimar 
772e38cbab5SGeorge Rimar   switch (Size) {
773e38cbab5SGeorge Rimar   case 1:
774e38cbab5SGeorge Rimar     *Buf = (uint8_t)Data;
775e38cbab5SGeorge Rimar     break;
776e38cbab5SGeorge Rimar   case 2:
777e38cbab5SGeorge Rimar     write16<E>(Buf, Data);
778e38cbab5SGeorge Rimar     break;
779e38cbab5SGeorge Rimar   case 4:
780e38cbab5SGeorge Rimar     write32<E>(Buf, Data);
781e38cbab5SGeorge Rimar     break;
782e38cbab5SGeorge Rimar   case 8:
783e38cbab5SGeorge Rimar     write64<E>(Buf, Data);
784e38cbab5SGeorge Rimar     break;
785e38cbab5SGeorge Rimar   default:
786e38cbab5SGeorge Rimar     llvm_unreachable("unsupported Size argument");
787e38cbab5SGeorge Rimar   }
788e38cbab5SGeorge Rimar }
789e38cbab5SGeorge Rimar 
790e38cbab5SGeorge Rimar template <class ELFT>
791e38cbab5SGeorge Rimar void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
792e38cbab5SGeorge Rimar   int I = getSectionIndex(Name);
793e38cbab5SGeorge Rimar   if (I == INT_MAX)
794e38cbab5SGeorge Rimar     return;
795e38cbab5SGeorge Rimar 
796e38cbab5SGeorge Rimar   OutputSectionCommand *Cmd =
797e38cbab5SGeorge Rimar       dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
798e38cbab5SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
799e38cbab5SGeorge Rimar     if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
800e38cbab5SGeorge Rimar       writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
801e38cbab5SGeorge Rimar }
802e38cbab5SGeorge Rimar 
803b71d6f7aSEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
8048ceadb38SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
8058ceadb38SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
806b71d6f7aSEugene Leviant       if (Cmd->LMAExpr && Cmd->Name == Name)
807b71d6f7aSEugene Leviant         return true;
808b71d6f7aSEugene Leviant   return false;
8098ceadb38SGeorge Rimar }
8108ceadb38SGeorge Rimar 
811c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
812c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
813c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
814c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
815076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
816f510fa6bSRui Ueyama   int I = 0;
817f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
818076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
819076fe157SGeorge Rimar       if (Cmd->Name == Name)
820f510fa6bSRui Ueyama         return I;
821f510fa6bSRui Ueyama     ++I;
822f510fa6bSRui Ueyama   }
823f510fa6bSRui Ueyama   return INT_MAX;
82471b26e94SGeorge Rimar }
82571b26e94SGeorge Rimar 
826bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
827bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
828bbe38602SEugene Leviant }
829bbe38602SEugene Leviant 
8309e69450eSGeorge Rimar template <class ELFT>
831884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
832e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections)
83396659df0SGeorge Rimar     if (Sec->getName() == Name)
83404a2e348SRafael Espindola       return Sec->Addr;
83596659df0SGeorge Rimar   error("undefined section " + Name);
83696659df0SGeorge Rimar   return 0;
83796659df0SGeorge Rimar }
83896659df0SGeorge Rimar 
83996659df0SGeorge Rimar template <class ELFT>
840b71d6f7aSEugene Leviant uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
841e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections)
842b71d6f7aSEugene Leviant     if (Sec->getName() == Name)
843b71d6f7aSEugene Leviant       return Sec->getLMA();
844b71d6f7aSEugene Leviant   error("undefined section " + Name);
845b71d6f7aSEugene Leviant   return 0;
846b71d6f7aSEugene Leviant }
847b71d6f7aSEugene Leviant 
848b71d6f7aSEugene Leviant template <class ELFT>
849884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
850e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections)
8519e69450eSGeorge Rimar     if (Sec->getName() == Name)
85204a2e348SRafael Espindola       return Sec->Size;
8539e69450eSGeorge Rimar   error("undefined section " + Name);
8549e69450eSGeorge Rimar   return 0;
8559e69450eSGeorge Rimar }
8569e69450eSGeorge Rimar 
85736fac7f0SEugene Leviant template <class ELFT>
85836fac7f0SEugene Leviant uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
859e08e78dfSRafael Espindola   for (OutputSectionBase *Sec : *OutputSections)
86036fac7f0SEugene Leviant     if (Sec->getName() == Name)
86104a2e348SRafael Espindola       return Sec->Addralign;
86236fac7f0SEugene Leviant   error("undefined section " + Name);
86336fac7f0SEugene Leviant   return 0;
86436fac7f0SEugene Leviant }
86536fac7f0SEugene Leviant 
866884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
8670d4b6d5cSRafael Espindola   return elf::getHeaderSize<ELFT>();
868e32a3598SGeorge Rimar }
869e32a3598SGeorge Rimar 
870884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
871884e786dSGeorge Rimar   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
872884e786dSGeorge Rimar     return B->getVA<ELFT>();
873884e786dSGeorge Rimar   error("symbol not found: " + S);
874884e786dSGeorge Rimar   return 0;
875884e786dSGeorge Rimar }
876884e786dSGeorge Rimar 
877f34f45fdSGeorge Rimar template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
878f34f45fdSGeorge Rimar   return Symtab<ELFT>::X->find(S) != nullptr;
879f34f45fdSGeorge Rimar }
880f34f45fdSGeorge Rimar 
8812f831dcaSRafael Espindola template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
8822f831dcaSRafael Espindola   SymbolBody *Sym = Symtab<ELFT>::X->find(S);
8832f831dcaSRafael Espindola   auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
8842f831dcaSRafael Espindola   return DR && !DR->Section;
8852f831dcaSRafael Espindola }
8862f831dcaSRafael Espindola 
887bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
888bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
889bbe38602SEugene Leviant // PHDRS {} script block.
890bbe38602SEugene Leviant template <class ELFT>
891edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
892076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
893076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
894edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
89531d842f5SGeorge Rimar       continue;
89631d842f5SGeorge Rimar 
89729c5a2a9SRui Ueyama     std::vector<size_t> Ret;
89829c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
89929c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
90029c5a2a9SRui Ueyama     return Ret;
901bbe38602SEugene Leviant   }
90231d842f5SGeorge Rimar   return {};
90331d842f5SGeorge Rimar }
904bbe38602SEugene Leviant 
90529c5a2a9SRui Ueyama template <class ELFT>
90629c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
90729c5a2a9SRui Ueyama   size_t I = 0;
90829c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
90929c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
91029c5a2a9SRui Ueyama       return I;
91129c5a2a9SRui Ueyama     ++I;
91229c5a2a9SRui Ueyama   }
91329c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
91429c5a2a9SRui Ueyama   return 0;
91529c5a2a9SRui Ueyama }
91629c5a2a9SRui Ueyama 
91707320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
918c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
919c3794e58SGeorge Rimar 
920f7c5fbb1SRui Ueyama public:
92107320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
922f23b2320SGeorge Rimar 
92320b6598cSGeorge Rimar   void readLinkerScript();
92420b6598cSGeorge Rimar   void readVersionScript();
925f7c5fbb1SRui Ueyama 
926f7c5fbb1SRui Ueyama private:
92752a1509eSRui Ueyama   void addFile(StringRef Path);
92852a1509eSRui Ueyama 
929f7c5fbb1SRui Ueyama   void readAsNeeded();
93090c5099eSDenis Protivensky   void readEntry();
93183f406cfSGeorge Rimar   void readExtern();
932f7c5fbb1SRui Ueyama   void readGroup();
93331aa1f83SRui Ueyama   void readInclude();
934ee59282bSRui Ueyama   void readOutput();
9359159ce93SDavide Italiano   void readOutputArch();
936f7c5fbb1SRui Ueyama   void readOutputFormat();
937bbe38602SEugene Leviant   void readPhdrs();
93868a39a65SDavide Italiano   void readSearchDir();
9398e3b38abSDenis Protivensky   void readSections();
94095769b4aSRui Ueyama   void readVersion();
94195769b4aSRui Ueyama   void readVersionScriptCommand();
9428e3b38abSDenis Protivensky 
943113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
944e38cbab5SGeorge Rimar   BytesDataCommand *readBytesDataCommand(StringRef Tok);
945ff1f29e0SGeorge Rimar   std::vector<uint8_t> readFill();
94610416564SRui Ueyama   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
947ff1f29e0SGeorge Rimar   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
948bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
949a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionDescription(StringRef Tok);
950db688454SEugene Leviant   StringMatcher readFilePatterns();
95107171f21SGeorge Rimar   std::vector<SectionPattern> readInputSectionsList();
952a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
953bbe38602SEugene Leviant   unsigned readPhdrType();
954be394db3SGeorge Rimar   SortSectionPolicy readSortKind();
955a35e39caSPetr Hosek   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
956c96da110SRafael Espindola   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
95703fc010eSGeorge Rimar   void readSort();
958eefa758eSGeorge Rimar   Expr readAssert();
959708019c4SRui Ueyama 
960708019c4SRui Ueyama   Expr readExpr();
961708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
962b71d6f7aSEugene Leviant   StringRef readParenLiteral();
963708019c4SRui Ueyama   Expr readPrimary();
964708019c4SRui Ueyama   Expr readTernary(Expr Cond);
9656ad7dfccSRui Ueyama   Expr readParenExpr();
966f7c5fbb1SRui Ueyama 
96720b6598cSGeorge Rimar   // For parsing version script.
96820b6598cSGeorge Rimar   void readExtern(std::vector<SymbolVersion> *Globals);
96995769b4aSRui Ueyama   void readVersionDeclaration(StringRef VerStr);
97020b6598cSGeorge Rimar   void readGlobal(StringRef VerStr);
97120b6598cSGeorge Rimar   void readLocal();
97220b6598cSGeorge Rimar 
97307320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
97416b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
975f7c5fbb1SRui Ueyama };
976f7c5fbb1SRui Ueyama 
97720b6598cSGeorge Rimar void ScriptParser::readVersionScript() {
97895769b4aSRui Ueyama   readVersionScriptCommand();
97920b6598cSGeorge Rimar   if (!atEOF())
98095769b4aSRui Ueyama     setError("EOF expected, but got " + next());
98195769b4aSRui Ueyama }
98295769b4aSRui Ueyama 
98395769b4aSRui Ueyama void ScriptParser::readVersionScriptCommand() {
98483043f23SRui Ueyama   if (consume("{")) {
98595769b4aSRui Ueyama     readVersionDeclaration("");
98620b6598cSGeorge Rimar     return;
98720b6598cSGeorge Rimar   }
98820b6598cSGeorge Rimar 
98995769b4aSRui Ueyama   while (!atEOF() && !Error && peek() != "}") {
99020b6598cSGeorge Rimar     StringRef VerStr = next();
99120b6598cSGeorge Rimar     if (VerStr == "{") {
99295769b4aSRui Ueyama       setError("anonymous version definition is used in "
99395769b4aSRui Ueyama                "combination with other version definitions");
99420b6598cSGeorge Rimar       return;
99520b6598cSGeorge Rimar     }
99620b6598cSGeorge Rimar     expect("{");
99795769b4aSRui Ueyama     readVersionDeclaration(VerStr);
99820b6598cSGeorge Rimar   }
99920b6598cSGeorge Rimar }
100020b6598cSGeorge Rimar 
100195769b4aSRui Ueyama void ScriptParser::readVersion() {
100295769b4aSRui Ueyama   expect("{");
100395769b4aSRui Ueyama   readVersionScriptCommand();
100495769b4aSRui Ueyama   expect("}");
100595769b4aSRui Ueyama }
100695769b4aSRui Ueyama 
100720b6598cSGeorge Rimar void ScriptParser::readLinkerScript() {
1008f7c5fbb1SRui Ueyama   while (!atEOF()) {
1009f7c5fbb1SRui Ueyama     StringRef Tok = next();
1010a27eeccaSRui Ueyama     if (Tok == ";")
1011a27eeccaSRui Ueyama       continue;
1012a27eeccaSRui Ueyama 
101320d03194SEugene Leviant     if (Tok == "ASSERT") {
101420d03194SEugene Leviant       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
101520d03194SEugene Leviant     } else if (Tok == "ENTRY") {
1016a27eeccaSRui Ueyama       readEntry();
1017a27eeccaSRui Ueyama     } else if (Tok == "EXTERN") {
1018a27eeccaSRui Ueyama       readExtern();
1019a27eeccaSRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
1020a27eeccaSRui Ueyama       readGroup();
1021a27eeccaSRui Ueyama     } else if (Tok == "INCLUDE") {
1022a27eeccaSRui Ueyama       readInclude();
1023a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT") {
1024a27eeccaSRui Ueyama       readOutput();
1025a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
1026a27eeccaSRui Ueyama       readOutputArch();
1027a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
1028a27eeccaSRui Ueyama       readOutputFormat();
1029a27eeccaSRui Ueyama     } else if (Tok == "PHDRS") {
1030a27eeccaSRui Ueyama       readPhdrs();
1031a27eeccaSRui Ueyama     } else if (Tok == "SEARCH_DIR") {
1032a27eeccaSRui Ueyama       readSearchDir();
1033a27eeccaSRui Ueyama     } else if (Tok == "SECTIONS") {
1034a27eeccaSRui Ueyama       readSections();
1035a27eeccaSRui Ueyama     } else if (Tok == "VERSION") {
1036a27eeccaSRui Ueyama       readVersion();
1037c96da110SRafael Espindola     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
10380df80befSPetr Hosek       Opt.Commands.emplace_back(Cmd);
1039e5d3ca50SPetr Hosek     } else {
10405761042dSGeorge Rimar       setError("unknown directive: " + Tok);
1041f7c5fbb1SRui Ueyama     }
1042f7c5fbb1SRui Ueyama   }
1043e5d3ca50SPetr Hosek }
1044f7c5fbb1SRui Ueyama 
1045717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
104616b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
10475af1687fSJustin Bogner     SmallString<128> PathData;
10485af1687fSJustin Bogner     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
104916b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
10505af1687fSJustin Bogner       Driver->addFile(Saver.save(Path));
105116b0cc9eSSimon Atanasyan       return;
105216b0cc9eSSimon Atanasyan     }
105316b0cc9eSSimon Atanasyan   }
105416b0cc9eSSimon Atanasyan 
1055f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
105652a1509eSRui Ueyama     Driver->addFile(S);
105752a1509eSRui Ueyama   } else if (S.startswith("=")) {
105852a1509eSRui Ueyama     if (Config->Sysroot.empty())
105952a1509eSRui Ueyama       Driver->addFile(S.substr(1));
106052a1509eSRui Ueyama     else
106152a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
106252a1509eSRui Ueyama   } else if (S.startswith("-l")) {
106321eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
1064a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
1065a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
106652a1509eSRui Ueyama   } else {
106752a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
106852a1509eSRui Ueyama     if (Path.empty())
1069777f9630SGeorge Rimar       setError("unable to find " + S);
1070025d59b1SRui Ueyama     else
107152a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
107252a1509eSRui Ueyama   }
107352a1509eSRui Ueyama }
107452a1509eSRui Ueyama 
1075717677afSRui Ueyama void ScriptParser::readAsNeeded() {
1076f7c5fbb1SRui Ueyama   expect("(");
107735da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
107835da9b6eSRui Ueyama   Config->AsNeeded = true;
107983043f23SRui Ueyama   while (!Error && !consume(")"))
1080cd574a5eSGeorge Rimar     addFile(unquote(next()));
108135da9b6eSRui Ueyama   Config->AsNeeded = Orig;
1082f7c5fbb1SRui Ueyama }
1083f7c5fbb1SRui Ueyama 
1084717677afSRui Ueyama void ScriptParser::readEntry() {
108590c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
108690c5099eSDenis Protivensky   expect("(");
108790c5099eSDenis Protivensky   StringRef Tok = next();
108890c5099eSDenis Protivensky   if (Config->Entry.empty())
108990c5099eSDenis Protivensky     Config->Entry = Tok;
109090c5099eSDenis Protivensky   expect(")");
109190c5099eSDenis Protivensky }
109290c5099eSDenis Protivensky 
1093717677afSRui Ueyama void ScriptParser::readExtern() {
109483f406cfSGeorge Rimar   expect("(");
109583043f23SRui Ueyama   while (!Error && !consume(")"))
1096a2acc931SRui Ueyama     Config->Undefined.push_back(next());
109783f406cfSGeorge Rimar }
109883f406cfSGeorge Rimar 
1099717677afSRui Ueyama void ScriptParser::readGroup() {
1100f7c5fbb1SRui Ueyama   expect("(");
110183043f23SRui Ueyama   while (!Error && !consume(")")) {
1102f7c5fbb1SRui Ueyama     StringRef Tok = next();
1103a2acc931SRui Ueyama     if (Tok == "AS_NEEDED")
1104f7c5fbb1SRui Ueyama       readAsNeeded();
1105a2acc931SRui Ueyama     else
1106cd574a5eSGeorge Rimar       addFile(unquote(Tok));
1107f7c5fbb1SRui Ueyama   }
1108f7c5fbb1SRui Ueyama }
1109f7c5fbb1SRui Ueyama 
1110717677afSRui Ueyama void ScriptParser::readInclude() {
111131aa1f83SRui Ueyama   StringRef Tok = next();
1112cd574a5eSGeorge Rimar   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
1113025d59b1SRui Ueyama   if (!MBOrErr) {
11145761042dSGeorge Rimar     setError("cannot open " + Tok);
1115025d59b1SRui Ueyama     return;
1116025d59b1SRui Ueyama   }
111731aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
1118a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1119a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
112031aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
112131aa1f83SRui Ueyama }
112231aa1f83SRui Ueyama 
1123717677afSRui Ueyama void ScriptParser::readOutput() {
1124ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
1125ee59282bSRui Ueyama   expect("(");
1126ee59282bSRui Ueyama   StringRef Tok = next();
1127ee59282bSRui Ueyama   if (Config->OutputFile.empty())
1128cd574a5eSGeorge Rimar     Config->OutputFile = unquote(Tok);
1129ee59282bSRui Ueyama   expect(")");
1130ee59282bSRui Ueyama }
1131ee59282bSRui Ueyama 
1132717677afSRui Ueyama void ScriptParser::readOutputArch() {
11339159ce93SDavide Italiano   // Error checking only for now.
11349159ce93SDavide Italiano   expect("(");
11355424e7c7SJustin Bogner   skip();
11369159ce93SDavide Italiano   expect(")");
11379159ce93SDavide Italiano }
11389159ce93SDavide Italiano 
1139717677afSRui Ueyama void ScriptParser::readOutputFormat() {
1140f7c5fbb1SRui Ueyama   // Error checking only for now.
1141f7c5fbb1SRui Ueyama   expect("(");
11425424e7c7SJustin Bogner   skip();
11436836c618SDavide Italiano   StringRef Tok = next();
11446836c618SDavide Italiano   if (Tok == ")")
11456836c618SDavide Italiano     return;
1146025d59b1SRui Ueyama   if (Tok != ",") {
11475761042dSGeorge Rimar     setError("unexpected token: " + Tok);
1148025d59b1SRui Ueyama     return;
1149025d59b1SRui Ueyama   }
11505424e7c7SJustin Bogner   skip();
11516836c618SDavide Italiano   expect(",");
11525424e7c7SJustin Bogner   skip();
1153f7c5fbb1SRui Ueyama   expect(")");
1154f7c5fbb1SRui Ueyama }
1155f7c5fbb1SRui Ueyama 
1156bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
1157bbe38602SEugene Leviant   expect("{");
115883043f23SRui Ueyama   while (!Error && !consume("}")) {
1159bbe38602SEugene Leviant     StringRef Tok = next();
116056b21c86SEugene Leviant     Opt.PhdrsCommands.push_back(
116156b21c86SEugene Leviant         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1162bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1163bbe38602SEugene Leviant 
1164bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
1165bbe38602SEugene Leviant     do {
1166bbe38602SEugene Leviant       Tok = next();
1167bbe38602SEugene Leviant       if (Tok == ";")
1168bbe38602SEugene Leviant         break;
1169bbe38602SEugene Leviant       if (Tok == "FILEHDR")
1170bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
1171bbe38602SEugene Leviant       else if (Tok == "PHDRS")
1172bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
117356b21c86SEugene Leviant       else if (Tok == "AT")
117456b21c86SEugene Leviant         PhdrCmd.LMAExpr = readParenExpr();
1175865bf863SEugene Leviant       else if (Tok == "FLAGS") {
1176865bf863SEugene Leviant         expect("(");
1177eb685cd7SRafael Espindola         // Passing 0 for the value of dot is a bit of a hack. It means that
1178eb685cd7SRafael Espindola         // we accept expressions like ".|1".
1179eb685cd7SRafael Espindola         PhdrCmd.Flags = readExpr()(0);
1180865bf863SEugene Leviant         expect(")");
1181865bf863SEugene Leviant       } else
1182bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
1183bbe38602SEugene Leviant     } while (!Error);
1184bbe38602SEugene Leviant   }
1185bbe38602SEugene Leviant }
1186bbe38602SEugene Leviant 
1187717677afSRui Ueyama void ScriptParser::readSearchDir() {
118868a39a65SDavide Italiano   expect("(");
118986c5fb82SRui Ueyama   StringRef Tok = next();
11906c7ad13fSRui Ueyama   if (!Config->Nostdlib)
1191cd574a5eSGeorge Rimar     Config->SearchPaths.push_back(unquote(Tok));
119268a39a65SDavide Italiano   expect(")");
119368a39a65SDavide Italiano }
119468a39a65SDavide Italiano 
1195717677afSRui Ueyama void ScriptParser::readSections() {
1196e05336ffSEugene Leviant   Opt.HasSections = true;
11978e3b38abSDenis Protivensky   expect("{");
119883043f23SRui Ueyama   while (!Error && !consume("}")) {
1199113cdec9SRui Ueyama     StringRef Tok = next();
1200c96da110SRafael Espindola     BaseCommand *Cmd = readProvideOrAssignment(Tok);
1201ceabe80eSEugene Leviant     if (!Cmd) {
1202ceabe80eSEugene Leviant       if (Tok == "ASSERT")
1203eefa758eSGeorge Rimar         Cmd = new AssertCommand(readAssert());
1204ceabe80eSEugene Leviant       else
120510416564SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
12068e3b38abSDenis Protivensky     }
120710416564SRui Ueyama     Opt.Commands.emplace_back(Cmd);
1208652852c5SGeorge Rimar   }
1209708019c4SRui Ueyama }
12108e3b38abSDenis Protivensky 
1211708019c4SRui Ueyama static int precedence(StringRef Op) {
1212708019c4SRui Ueyama   return StringSwitch<int>(Op)
12130120e3f2SRui Ueyama       .Cases("*", "/", 5)
12140120e3f2SRui Ueyama       .Cases("+", "-", 4)
12150120e3f2SRui Ueyama       .Cases("<<", ">>", 3)
12169c4ac5f2SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
12170120e3f2SRui Ueyama       .Cases("&", "|", 1)
1218708019c4SRui Ueyama       .Default(-1);
1219708019c4SRui Ueyama }
1220708019c4SRui Ueyama 
1221db688454SEugene Leviant StringMatcher ScriptParser::readFilePatterns() {
122210416564SRui Ueyama   std::vector<StringRef> V;
122383043f23SRui Ueyama   while (!Error && !consume(")"))
122410416564SRui Ueyama     V.push_back(next());
1225f91282e1SRui Ueyama   return StringMatcher(V);
12260702c4e8SGeorge Rimar }
12270702c4e8SGeorge Rimar 
1228be394db3SGeorge Rimar SortSectionPolicy ScriptParser::readSortKind() {
122983043f23SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
1230be394db3SGeorge Rimar     return SortSectionPolicy::Name;
123183043f23SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
1232be394db3SGeorge Rimar     return SortSectionPolicy::Alignment;
123383043f23SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
1234be394db3SGeorge Rimar     return SortSectionPolicy::Priority;
123583043f23SRui Ueyama   if (consume("SORT_NONE"))
1236be394db3SGeorge Rimar     return SortSectionPolicy::None;
1237b2a0abdfSRui Ueyama   return SortSectionPolicy::Default;
1238be394db3SGeorge Rimar }
1239be394db3SGeorge Rimar 
1240395281cfSGeorge Rimar // Method reads a list of sequence of excluded files and section globs given in
1241395281cfSGeorge Rimar // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1242395281cfSGeorge Rimar // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1243af03be19SGeorge Rimar // The semantics of that is next:
1244af03be19SGeorge Rimar // * Include .foo.1 from every file.
1245af03be19SGeorge Rimar // * Include .foo.2 from every file but a.o
1246af03be19SGeorge Rimar // * Include .foo.3 from every file but b.o
124707171f21SGeorge Rimar std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
124807171f21SGeorge Rimar   std::vector<SectionPattern> Ret;
1249601e9898SGeorge Rimar   while (!Error && peek() != ")") {
1250f91282e1SRui Ueyama     StringMatcher ExcludeFilePat;
125183043f23SRui Ueyama     if (consume("EXCLUDE_FILE")) {
1252395281cfSGeorge Rimar       expect("(");
1253f91282e1SRui Ueyama       ExcludeFilePat = readFilePatterns();
1254395281cfSGeorge Rimar     }
1255395281cfSGeorge Rimar 
1256601e9898SGeorge Rimar     std::vector<StringRef> V;
1257601e9898SGeorge Rimar     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1258395281cfSGeorge Rimar       V.push_back(next());
1259601e9898SGeorge Rimar 
1260601e9898SGeorge Rimar     if (!V.empty())
1261f91282e1SRui Ueyama       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
1262601e9898SGeorge Rimar     else
1263601e9898SGeorge Rimar       setError("section pattern is expected");
1264395281cfSGeorge Rimar   }
126507171f21SGeorge Rimar   return Ret;
1266395281cfSGeorge Rimar }
1267395281cfSGeorge Rimar 
126807171f21SGeorge Rimar // Section pattern grammar can have complex expressions, for example:
126907171f21SGeorge Rimar // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
127007171f21SGeorge Rimar // Generally is a sequence of globs and excludes that may be wrapped in a SORT()
127107171f21SGeorge Rimar // commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
127207171f21SGeorge Rimar // This methods handles wrapping sequences of excluded files and section globs
127307171f21SGeorge Rimar // into SORT() if that needed and reads them all.
1274a2496cbeSGeorge Rimar InputSectionDescription *
1275a2496cbeSGeorge Rimar ScriptParser::readInputSectionRules(StringRef FilePattern) {
1276c91930a1SGeorge Rimar   auto *Cmd = new InputSectionDescription(FilePattern);
12770ed42b0cSDavide Italiano   expect("(");
127883043f23SRui Ueyama   while (!HasError && !consume(")")) {
127907171f21SGeorge Rimar     SortSectionPolicy Outer = readSortKind();
128007171f21SGeorge Rimar     SortSectionPolicy Inner = SortSectionPolicy::Default;
128107171f21SGeorge Rimar     std::vector<SectionPattern> V;
128207171f21SGeorge Rimar     if (Outer != SortSectionPolicy::Default) {
12830702c4e8SGeorge Rimar       expect("(");
128407171f21SGeorge Rimar       Inner = readSortKind();
128507171f21SGeorge Rimar       if (Inner != SortSectionPolicy::Default) {
1286350ece4eSGeorge Rimar         expect("(");
128707171f21SGeorge Rimar         V = readInputSectionsList();
12880702c4e8SGeorge Rimar         expect(")");
1289350ece4eSGeorge Rimar       } else {
129007171f21SGeorge Rimar         V = readInputSectionsList();
1291350ece4eSGeorge Rimar       }
1292350ece4eSGeorge Rimar       expect(")");
129307171f21SGeorge Rimar     } else {
129407171f21SGeorge Rimar       V = readInputSectionsList();
12950659800eSGeorge Rimar     }
12960702c4e8SGeorge Rimar 
129707171f21SGeorge Rimar     for (SectionPattern &Pat : V) {
129807171f21SGeorge Rimar       Pat.SortInner = Inner;
129907171f21SGeorge Rimar       Pat.SortOuter = Outer;
130007171f21SGeorge Rimar     }
130107171f21SGeorge Rimar 
130207171f21SGeorge Rimar     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
130307171f21SGeorge Rimar   }
130410416564SRui Ueyama   return Cmd;
13050659800eSGeorge Rimar }
13060659800eSGeorge Rimar 
1307a2496cbeSGeorge Rimar InputSectionDescription *
1308a2496cbeSGeorge Rimar ScriptParser::readInputSectionDescription(StringRef Tok) {
13090659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
13100659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1311a2496cbeSGeorge Rimar   if (Tok == "KEEP") {
1312e7282797SDavide Italiano     expect("(");
1313a2496cbeSGeorge Rimar     StringRef FilePattern = next();
1314a2496cbeSGeorge Rimar     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
13150ed42b0cSDavide Italiano     expect(")");
1316cf43f179SEugene Leviant     Opt.KeptSections.push_back(Cmd);
131710416564SRui Ueyama     return Cmd;
131810416564SRui Ueyama   }
1319a2496cbeSGeorge Rimar   return readInputSectionRules(Tok);
13200659800eSGeorge Rimar }
13210659800eSGeorge Rimar 
132203fc010eSGeorge Rimar void ScriptParser::readSort() {
132303fc010eSGeorge Rimar   expect("(");
132403fc010eSGeorge Rimar   expect("CONSTRUCTORS");
132503fc010eSGeorge Rimar   expect(")");
132603fc010eSGeorge Rimar }
132703fc010eSGeorge Rimar 
1328eefa758eSGeorge Rimar Expr ScriptParser::readAssert() {
1329eefa758eSGeorge Rimar   expect("(");
1330eefa758eSGeorge Rimar   Expr E = readExpr();
1331eefa758eSGeorge Rimar   expect(",");
1332cd574a5eSGeorge Rimar   StringRef Msg = unquote(next());
1333eefa758eSGeorge Rimar   expect(")");
1334eefa758eSGeorge Rimar   return [=](uint64_t Dot) {
1335eefa758eSGeorge Rimar     uint64_t V = E(Dot);
1336eefa758eSGeorge Rimar     if (!V)
1337eefa758eSGeorge Rimar       error(Msg);
1338eefa758eSGeorge Rimar     return V;
1339eefa758eSGeorge Rimar   };
1340eefa758eSGeorge Rimar }
1341eefa758eSGeorge Rimar 
134225150e8bSRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
134325150e8bSRui Ueyama // alias for =fillexp section attribute, which is different from
134425150e8bSRui Ueyama // what GNU linkers do.
134525150e8bSRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1346ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readFill() {
1347ff1f29e0SGeorge Rimar   expect("(");
1348ff1f29e0SGeorge Rimar   std::vector<uint8_t> V = readOutputSectionFiller(next());
1349ff1f29e0SGeorge Rimar   expect(")");
1350ff1f29e0SGeorge Rimar   expect(";");
1351ff1f29e0SGeorge Rimar   return V;
1352ff1f29e0SGeorge Rimar }
1353ff1f29e0SGeorge Rimar 
135410416564SRui Ueyama OutputSectionCommand *
135510416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1356076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
135758e5c4dcSGeorge Rimar 
135858e5c4dcSGeorge Rimar   // Read an address expression.
135958e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
136058e5c4dcSGeorge Rimar   if (peek() != ":")
136158e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
136258e5c4dcSGeorge Rimar 
13638e3b38abSDenis Protivensky   expect(":");
1364246f681eSDavide Italiano 
136583043f23SRui Ueyama   if (consume("AT"))
1366b71d6f7aSEugene Leviant     Cmd->LMAExpr = readParenExpr();
136783043f23SRui Ueyama   if (consume("ALIGN"))
13686ad7dfccSRui Ueyama     Cmd->AlignExpr = readParenExpr();
136983043f23SRui Ueyama   if (consume("SUBALIGN"))
1370db24d9c3SGeorge Rimar     Cmd->SubalignExpr = readParenExpr();
1371630c6179SGeorge Rimar 
1372246f681eSDavide Italiano   // Parse constraints.
137383043f23SRui Ueyama   if (consume("ONLY_IF_RO"))
1374efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
137583043f23SRui Ueyama   if (consume("ONLY_IF_RW"))
1376efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
13778e3b38abSDenis Protivensky   expect("{");
13788ec77e64SRui Ueyama 
137983043f23SRui Ueyama   while (!Error && !consume("}")) {
1380ceabe80eSEugene Leviant     StringRef Tok = next();
1381c96da110SRafael Espindola     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1382ceabe80eSEugene Leviant       Cmd->Commands.emplace_back(Assignment);
1383e38cbab5SGeorge Rimar     else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1384e38cbab5SGeorge Rimar       Cmd->Commands.emplace_back(Data);
1385ff1f29e0SGeorge Rimar     else if (Tok == "FILL")
1386ff1f29e0SGeorge Rimar       Cmd->Filler = readFill();
1387ceabe80eSEugene Leviant     else if (Tok == "SORT")
138803fc010eSGeorge Rimar       readSort();
1389a2496cbeSGeorge Rimar     else if (peek() == "(")
1390a2496cbeSGeorge Rimar       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1391ceabe80eSEugene Leviant     else
1392ceabe80eSEugene Leviant       setError("unknown command " + Tok);
13938e3b38abSDenis Protivensky   }
1394076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
13954ebc5620SGeorge Rimar 
139683043f23SRui Ueyama   if (consume("="))
13974ebc5620SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next());
13984ebc5620SGeorge Rimar   else if (peek().startswith("="))
1399ff1f29e0SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next().drop_front());
14004ebc5620SGeorge Rimar 
140110416564SRui Ueyama   return Cmd;
1402f71caa2bSRui Ueyama }
14038ec77e64SRui Ueyama 
14042c8f1f04SRui Ueyama // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
14052c8f1f04SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
14062c8f1f04SRui Ueyama //
14072c8f1f04SRui Ueyama // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
14082c8f1f04SRui Ueyama // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
14092c8f1f04SRui Ueyama // as 32-bit big-endian values. We will do the same as ld.gold does
14102c8f1f04SRui Ueyama // because it's simpler than what ld.bfd does.
1411ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1412965827d6SRui Ueyama   uint32_t V;
1413ff1f29e0SGeorge Rimar   if (Tok.getAsInteger(0, V)) {
1414965827d6SRui Ueyama     setError("invalid filler expression: " + Tok);
1415f71caa2bSRui Ueyama     return {};
1416e2ee72b5SGeorge Rimar   }
1417965827d6SRui Ueyama   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
14188e3b38abSDenis Protivensky }
14198e3b38abSDenis Protivensky 
1420a35e39caSPetr Hosek SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1421a31c91b1SEugene Leviant   expect("(");
1422174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
1423a35e39caSPetr Hosek   Cmd->Provide = Provide;
1424174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
1425a31c91b1SEugene Leviant   expect(")");
1426a31c91b1SEugene Leviant   expect(";");
142710416564SRui Ueyama   return Cmd;
1428eda81a1bSEugene Leviant }
1429eda81a1bSEugene Leviant 
1430c96da110SRafael Espindola SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1431ceabe80eSEugene Leviant   SymbolAssignment *Cmd = nullptr;
1432ceabe80eSEugene Leviant   if (peek() == "=" || peek() == "+=") {
1433ceabe80eSEugene Leviant     Cmd = readAssignment(Tok);
1434ceabe80eSEugene Leviant     expect(";");
1435ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE") {
1436a35e39caSPetr Hosek     Cmd = readProvideHidden(true, false);
1437a35e39caSPetr Hosek   } else if (Tok == "HIDDEN") {
1438a35e39caSPetr Hosek     Cmd = readProvideHidden(false, true);
1439ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE_HIDDEN") {
1440a35e39caSPetr Hosek     Cmd = readProvideHidden(true, true);
1441ceabe80eSEugene Leviant   }
1442ceabe80eSEugene Leviant   return Cmd;
1443ceabe80eSEugene Leviant }
1444ceabe80eSEugene Leviant 
144530835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
144630835ea4SGeorge Rimar   if (S == ".")
144730835ea4SGeorge Rimar     return Dot;
1448884e786dSGeorge Rimar   return ScriptBase->getSymbolValue(S);
1449e32a3598SGeorge Rimar }
1450e32a3598SGeorge Rimar 
14512f831dcaSRafael Espindola static bool isAbsolute(StringRef S) {
14522f831dcaSRafael Espindola   if (S == ".")
14532f831dcaSRafael Espindola     return false;
14542f831dcaSRafael Espindola   return ScriptBase->isAbsolute(S);
14552f831dcaSRafael Espindola }
14562f831dcaSRafael Espindola 
145730835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
145830835ea4SGeorge Rimar   StringRef Op = next();
1459db741e72SEugene Leviant   Expr E;
146030835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
146183043f23SRui Ueyama   if (consume("ABSOLUTE")) {
14627c1381a0SRui Ueyama     // The RHS may be something like "ABSOLUTE(.) & 0xff".
14637c1381a0SRui Ueyama     // Call readExpr1 to read the whole expression.
14647c1381a0SRui Ueyama     E = readExpr1(readParenExpr(), 0);
14652f831dcaSRafael Espindola     E.IsAbsolute = []() { return true; };
1466db741e72SEugene Leviant   } else {
1467db741e72SEugene Leviant     E = readExpr();
1468db741e72SEugene Leviant   }
146930835ea4SGeorge Rimar   if (Op == "+=")
147030835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1471f661393aSRafael Espindola   return new SymbolAssignment(Name, E);
147230835ea4SGeorge Rimar }
147330835ea4SGeorge Rimar 
147430835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
147530835ea4SGeorge Rimar // script expression.
147630835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
147730835ea4SGeorge Rimar 
147836c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
147936c1cd23SRui Ueyama   if (Op == "*")
148036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
148136c1cd23SRui Ueyama   if (Op == "/") {
148236c1cd23SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
148336c1cd23SRui Ueyama       uint64_t RHS = R(Dot);
148436c1cd23SRui Ueyama       if (RHS == 0) {
148536c1cd23SRui Ueyama         error("division by zero");
148636c1cd23SRui Ueyama         return 0;
148736c1cd23SRui Ueyama       }
148836c1cd23SRui Ueyama       return L(Dot) / RHS;
148936c1cd23SRui Ueyama     };
149036c1cd23SRui Ueyama   }
149136c1cd23SRui Ueyama   if (Op == "+")
14922f831dcaSRafael Espindola     return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
14932f831dcaSRafael Espindola             [=]() { return L.IsAbsolute() && R.IsAbsolute(); }};
149436c1cd23SRui Ueyama   if (Op == "-")
149536c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1496c8ccd1f1SGeorge Rimar   if (Op == "<<")
1497c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1498c8ccd1f1SGeorge Rimar   if (Op == ">>")
1499c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
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) { return L(Dot) > R(Dot); };
150436c1cd23SRui Ueyama   if (Op == ">=")
150536c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
150636c1cd23SRui Ueyama   if (Op == "<=")
150736c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
150836c1cd23SRui Ueyama   if (Op == "==")
150936c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
151036c1cd23SRui Ueyama   if (Op == "!=")
151136c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
151236c1cd23SRui Ueyama   if (Op == "&")
151336c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1514cc3dd629SRafael Espindola   if (Op == "|")
1515cc3dd629SRafael Espindola     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
151636c1cd23SRui Ueyama   llvm_unreachable("invalid operator");
151736c1cd23SRui Ueyama }
151836c1cd23SRui Ueyama 
1519708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
1520708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
1521708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1522708019c4SRui Ueyama   while (!atEOF() && !Error) {
1523708019c4SRui Ueyama     // Read an operator and an expression.
1524708019c4SRui Ueyama     StringRef Op1 = peek();
1525708019c4SRui Ueyama     if (Op1 == "?")
1526708019c4SRui Ueyama       return readTernary(Lhs);
1527708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
1528a31c91b1SEugene Leviant       break;
15295424e7c7SJustin Bogner     skip();
1530708019c4SRui Ueyama     Expr Rhs = readPrimary();
1531708019c4SRui Ueyama 
1532708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
1533708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
1534708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
1535708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
1536708019c4SRui Ueyama     while (!atEOF()) {
1537708019c4SRui Ueyama       StringRef Op2 = peek();
1538708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
1539eda81a1bSEugene Leviant         break;
1540708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
1541eda81a1bSEugene Leviant     }
1542708019c4SRui Ueyama 
1543708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
1544708019c4SRui Ueyama   }
1545708019c4SRui Ueyama   return Lhs;
1546708019c4SRui Ueyama }
1547708019c4SRui Ueyama 
1548708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
1549e2cc07bcSMichael J. Spencer   if (S == "COMMONPAGESIZE")
1550708019c4SRui Ueyama     return Target->PageSize;
1551e2cc07bcSMichael J. Spencer   if (S == "MAXPAGESIZE")
1552997f8838SPetr Hosek     return Config->MaxPageSize;
1553708019c4SRui Ueyama   error("unknown constant: " + S);
1554708019c4SRui Ueyama   return 0;
1555708019c4SRui Ueyama }
1556708019c4SRui Ueyama 
1557626e0b08SRui Ueyama // Parses Tok as an integer. Returns true if successful.
1558626e0b08SRui Ueyama // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1559626e0b08SRui Ueyama // and decimal numbers. Decimal numbers may have "K" (kilo) or
1560626e0b08SRui Ueyama // "M" (mega) prefixes.
15619f2f7ad9SGeorge Rimar static bool readInteger(StringRef Tok, uint64_t &Result) {
1562eaeafb2bSSimon Atanasyan   if (Tok.startswith("-")) {
1563eaeafb2bSSimon Atanasyan     if (!readInteger(Tok.substr(1), Result))
1564eaeafb2bSSimon Atanasyan       return false;
1565eaeafb2bSSimon Atanasyan     Result = -Result;
1566eaeafb2bSSimon Atanasyan     return true;
1567eaeafb2bSSimon Atanasyan   }
15689f2f7ad9SGeorge Rimar   if (Tok.startswith_lower("0x"))
15699f2f7ad9SGeorge Rimar     return !Tok.substr(2).getAsInteger(16, Result);
15709f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("H"))
15719f2f7ad9SGeorge Rimar     return !Tok.drop_back().getAsInteger(16, Result);
15729f2f7ad9SGeorge Rimar 
15739f2f7ad9SGeorge Rimar   int Suffix = 1;
15749f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("K")) {
15759f2f7ad9SGeorge Rimar     Suffix = 1024;
15769f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
15779f2f7ad9SGeorge Rimar   } else if (Tok.endswith_lower("M")) {
15789f2f7ad9SGeorge Rimar     Suffix = 1024 * 1024;
15799f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
15809f2f7ad9SGeorge Rimar   }
15819f2f7ad9SGeorge Rimar   if (Tok.getAsInteger(10, Result))
15829f2f7ad9SGeorge Rimar     return false;
15839f2f7ad9SGeorge Rimar   Result *= Suffix;
15849f2f7ad9SGeorge Rimar   return true;
15859f2f7ad9SGeorge Rimar }
15869f2f7ad9SGeorge Rimar 
1587e38cbab5SGeorge Rimar BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1588e38cbab5SGeorge Rimar   int Size = StringSwitch<unsigned>(Tok)
1589e38cbab5SGeorge Rimar                  .Case("BYTE", 1)
1590e38cbab5SGeorge Rimar                  .Case("SHORT", 2)
1591e38cbab5SGeorge Rimar                  .Case("LONG", 4)
1592e38cbab5SGeorge Rimar                  .Case("QUAD", 8)
1593e38cbab5SGeorge Rimar                  .Default(-1);
1594e38cbab5SGeorge Rimar   if (Size == -1)
1595e38cbab5SGeorge Rimar     return nullptr;
1596e38cbab5SGeorge Rimar 
1597e38cbab5SGeorge Rimar   expect("(");
1598e38cbab5SGeorge Rimar   uint64_t Val = 0;
1599e38cbab5SGeorge Rimar   StringRef S = next();
1600e38cbab5SGeorge Rimar   if (!readInteger(S, Val))
1601e38cbab5SGeorge Rimar     setError("unexpected value: " + S);
1602e38cbab5SGeorge Rimar   expect(")");
1603e38cbab5SGeorge Rimar   return new BytesDataCommand(Val, Size);
1604e38cbab5SGeorge Rimar }
1605e38cbab5SGeorge Rimar 
1606b71d6f7aSEugene Leviant StringRef ScriptParser::readParenLiteral() {
1607b71d6f7aSEugene Leviant   expect("(");
1608b71d6f7aSEugene Leviant   StringRef Tok = next();
1609b71d6f7aSEugene Leviant   expect(")");
1610b71d6f7aSEugene Leviant   return Tok;
1611b71d6f7aSEugene Leviant }
1612b71d6f7aSEugene Leviant 
1613708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
16146ad7dfccSRui Ueyama   if (peek() == "(")
16156ad7dfccSRui Ueyama     return readParenExpr();
1616708019c4SRui Ueyama 
16176ad7dfccSRui Ueyama   StringRef Tok = next();
1618708019c4SRui Ueyama 
1619eaeafb2bSSimon Atanasyan   if (Tok == "~") {
1620eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1621eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return ~E(Dot); };
1622eaeafb2bSSimon Atanasyan   }
1623eaeafb2bSSimon Atanasyan   if (Tok == "-") {
1624eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1625eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return -E(Dot); };
1626eaeafb2bSSimon Atanasyan   }
1627eaeafb2bSSimon Atanasyan 
1628708019c4SRui Ueyama   // Built-in functions are parsed here.
1629708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
163096659df0SGeorge Rimar   if (Tok == "ADDR") {
1631b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1632884e786dSGeorge Rimar     return
1633884e786dSGeorge Rimar         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
163496659df0SGeorge Rimar   }
1635b71d6f7aSEugene Leviant   if (Tok == "LOADADDR") {
1636b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1637b71d6f7aSEugene Leviant     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1638b71d6f7aSEugene Leviant   }
1639eefa758eSGeorge Rimar   if (Tok == "ASSERT")
1640eefa758eSGeorge Rimar     return readAssert();
1641708019c4SRui Ueyama   if (Tok == "ALIGN") {
16426ad7dfccSRui Ueyama     Expr E = readParenExpr();
1643708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1644708019c4SRui Ueyama   }
1645708019c4SRui Ueyama   if (Tok == "CONSTANT") {
1646b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1647b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return getConstant(Name); };
1648708019c4SRui Ueyama   }
1649f34f45fdSGeorge Rimar   if (Tok == "DEFINED") {
1650f34f45fdSGeorge Rimar     expect("(");
1651f34f45fdSGeorge Rimar     StringRef Tok = next();
1652f34f45fdSGeorge Rimar     expect(")");
1653f2821028SGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
1654f34f45fdSGeorge Rimar   }
165554c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
165654c145ceSRafael Espindola     expect("(");
16575424e7c7SJustin Bogner     skip();
165854c145ceSRafael Espindola     expect(",");
16598c658bf8SGeorge Rimar     Expr E = readExpr();
166054c145ceSRafael Espindola     expect(")");
16618c658bf8SGeorge Rimar     return [=](uint64_t Dot) { return E(Dot); };
166254c145ceSRafael Espindola   }
1663708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
1664708019c4SRui Ueyama     expect("(");
1665708019c4SRui Ueyama     Expr E = readExpr();
1666708019c4SRui Ueyama     expect(",");
1667708019c4SRui Ueyama     readExpr();
1668708019c4SRui Ueyama     expect(")");
1669f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1670708019c4SRui Ueyama   }
1671708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
1672708019c4SRui Ueyama     expect("(");
1673708019c4SRui Ueyama     expect(".");
1674708019c4SRui Ueyama     expect(")");
1675708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
1676708019c4SRui Ueyama   }
1677276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
1678276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1679276b4e64SGeorge Rimar   // the next page boundary for simplicity.
1680276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
1681276b4e64SGeorge Rimar     expect("(");
168297bdc722SRafael Espindola     readExpr();
1683276b4e64SGeorge Rimar     expect(",");
1684276b4e64SGeorge Rimar     readExpr();
1685276b4e64SGeorge Rimar     expect(")");
1686276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1687276b4e64SGeorge Rimar   }
16889e69450eSGeorge Rimar   if (Tok == "SIZEOF") {
1689b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1690b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
16919e69450eSGeorge Rimar   }
169236fac7f0SEugene Leviant   if (Tok == "ALIGNOF") {
1693b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1694b0de56b5SRafael Espindola     return
1695b0de56b5SRafael Espindola         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
169636fac7f0SEugene Leviant   }
1697e32a3598SGeorge Rimar   if (Tok == "SIZEOF_HEADERS")
1698b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1699708019c4SRui Ueyama 
17009f2f7ad9SGeorge Rimar   // Tok is a literal number.
17019f2f7ad9SGeorge Rimar   uint64_t V;
17029f2f7ad9SGeorge Rimar   if (readInteger(Tok, V))
1703b0de56b5SRafael Espindola     return [=](uint64_t Dot) { return V; };
17049f2f7ad9SGeorge Rimar 
17059f2f7ad9SGeorge Rimar   // Tok is a symbol name.
170630835ea4SGeorge Rimar   if (Tok != "." && !isValidCIdentifier(Tok))
1707708019c4SRui Ueyama     setError("malformed number: " + Tok);
17082f831dcaSRafael Espindola   return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
17092f831dcaSRafael Espindola           [=]() { return isAbsolute(Tok); }};
1710a9c5a528SGeorge Rimar }
1711708019c4SRui Ueyama 
1712708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
17135424e7c7SJustin Bogner   skip();
1714708019c4SRui Ueyama   Expr L = readExpr();
1715708019c4SRui Ueyama   expect(":");
1716708019c4SRui Ueyama   Expr R = readExpr();
1717708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1718708019c4SRui Ueyama }
1719708019c4SRui Ueyama 
17206ad7dfccSRui Ueyama Expr ScriptParser::readParenExpr() {
17216ad7dfccSRui Ueyama   expect("(");
17226ad7dfccSRui Ueyama   Expr E = readExpr();
17236ad7dfccSRui Ueyama   expect(")");
17246ad7dfccSRui Ueyama   return E;
17256ad7dfccSRui Ueyama }
17266ad7dfccSRui Ueyama 
1727bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1728bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
1729bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
1730bbe38602SEugene Leviant     StringRef Tok = next();
1731bbe38602SEugene Leviant     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1732bbe38602SEugene Leviant     if (Tok.empty()) {
1733bbe38602SEugene Leviant       setError("section header name is empty");
1734bbe38602SEugene Leviant       break;
1735bbe38602SEugene Leviant     }
1736bbe38602SEugene Leviant     Phdrs.push_back(Tok);
1737bbe38602SEugene Leviant   }
1738bbe38602SEugene Leviant   return Phdrs;
1739bbe38602SEugene Leviant }
1740bbe38602SEugene Leviant 
174195dd718cSGeorge Rimar // Read a program header type name. The next token must be a
174295dd718cSGeorge Rimar // name of a program header type or a constant (e.g. "0x3").
1743bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
1744bbe38602SEugene Leviant   StringRef Tok = next();
174595dd718cSGeorge Rimar   uint64_t Val;
174695dd718cSGeorge Rimar   if (readInteger(Tok, Val))
174795dd718cSGeorge Rimar     return Val;
174895dd718cSGeorge Rimar 
1749b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
1750b0f6c590SRui Ueyama                      .Case("PT_NULL", PT_NULL)
1751b0f6c590SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
1752b0f6c590SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1753b0f6c590SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
1754b0f6c590SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
1755b0f6c590SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
1756b0f6c590SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
1757b0f6c590SRui Ueyama                      .Case("PT_TLS", PT_TLS)
1758b0f6c590SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1759b0f6c590SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1760b0f6c590SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1761270173f2SGeorge Rimar                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1762cc6e567cSGeorge Rimar                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1763b0f6c590SRui Ueyama                      .Default(-1);
1764bbe38602SEugene Leviant 
1765b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1766b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1767b0f6c590SRui Ueyama     return PT_NULL;
1768b0f6c590SRui Ueyama   }
1769b0f6c590SRui Ueyama   return Ret;
1770bbe38602SEugene Leviant }
1771bbe38602SEugene Leviant 
177295769b4aSRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
177320b6598cSGeorge Rimar   // Identifiers start at 2 because 0 and 1 are reserved
177420b6598cSGeorge Rimar   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
177520b6598cSGeorge Rimar   size_t VersionId = Config->VersionDefinitions.size() + 2;
177620b6598cSGeorge Rimar   Config->VersionDefinitions.push_back({VerStr, VersionId});
177720b6598cSGeorge Rimar 
177883043f23SRui Ueyama   if (consume("global:") || peek() != "local:")
177920b6598cSGeorge Rimar     readGlobal(VerStr);
178083043f23SRui Ueyama   if (consume("local:"))
178120b6598cSGeorge Rimar     readLocal();
178220b6598cSGeorge Rimar   expect("}");
178320b6598cSGeorge Rimar 
178420b6598cSGeorge Rimar   // Each version may have a parent version. For example, "Ver2" defined as
178520b6598cSGeorge Rimar   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
178620b6598cSGeorge Rimar   // version hierarchy is, probably against your instinct, purely for human; the
178720b6598cSGeorge Rimar   // runtime doesn't care about them at all. In LLD, we simply skip the token.
178820b6598cSGeorge Rimar   if (!VerStr.empty() && peek() != ";")
17895424e7c7SJustin Bogner     skip();
179020b6598cSGeorge Rimar   expect(";");
179120b6598cSGeorge Rimar }
179220b6598cSGeorge Rimar 
179320b6598cSGeorge Rimar void ScriptParser::readLocal() {
179420b6598cSGeorge Rimar   Config->DefaultSymbolVersion = VER_NDX_LOCAL;
179520b6598cSGeorge Rimar   expect("*");
179620b6598cSGeorge Rimar   expect(";");
179720b6598cSGeorge Rimar }
179820b6598cSGeorge Rimar 
179920b6598cSGeorge Rimar void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1800cd574a5eSGeorge Rimar   expect("\"C++\"");
180120b6598cSGeorge Rimar   expect("{");
180220b6598cSGeorge Rimar 
180320b6598cSGeorge Rimar   for (;;) {
180420b6598cSGeorge Rimar     if (peek() == "}" || Error)
180520b6598cSGeorge Rimar       break;
1806cd574a5eSGeorge Rimar     bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1807cd574a5eSGeorge Rimar     Globals->push_back({unquote(next()), true, HasWildcard});
180820b6598cSGeorge Rimar     expect(";");
180920b6598cSGeorge Rimar   }
181020b6598cSGeorge Rimar 
181120b6598cSGeorge Rimar   expect("}");
181220b6598cSGeorge Rimar   expect(";");
181320b6598cSGeorge Rimar }
181420b6598cSGeorge Rimar 
181520b6598cSGeorge Rimar void ScriptParser::readGlobal(StringRef VerStr) {
181620b6598cSGeorge Rimar   std::vector<SymbolVersion> *Globals;
181720b6598cSGeorge Rimar   if (VerStr.empty())
181820b6598cSGeorge Rimar     Globals = &Config->VersionScriptGlobals;
181920b6598cSGeorge Rimar   else
182020b6598cSGeorge Rimar     Globals = &Config->VersionDefinitions.back().Globals;
182120b6598cSGeorge Rimar 
182220b6598cSGeorge Rimar   for (;;) {
182383043f23SRui Ueyama     if (consume("extern"))
182420b6598cSGeorge Rimar       readExtern(Globals);
182520b6598cSGeorge Rimar 
182620b6598cSGeorge Rimar     StringRef Cur = peek();
182720b6598cSGeorge Rimar     if (Cur == "}" || Cur == "local:" || Error)
182820b6598cSGeorge Rimar       return;
18295424e7c7SJustin Bogner     skip();
1830cd574a5eSGeorge Rimar     Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
183120b6598cSGeorge Rimar     expect(";");
183220b6598cSGeorge Rimar   }
183320b6598cSGeorge Rimar }
183420b6598cSGeorge Rimar 
183516b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
183616b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
183716b0cc9eSSimon Atanasyan     return false;
183816b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
183916b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
184016b0cc9eSSimon Atanasyan       return true;
184116b0cc9eSSimon Atanasyan   return false;
184216b0cc9eSSimon Atanasyan }
184316b0cc9eSSimon Atanasyan 
184407320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
184516b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
184620b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
184720b6598cSGeorge Rimar }
184820b6598cSGeorge Rimar 
184920b6598cSGeorge Rimar void elf::readVersionScript(MemoryBufferRef MB) {
185020b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), false).readVersionScript();
1851f7c5fbb1SRui Ueyama }
18521ebc8ed7SRui Ueyama 
185307320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
185407320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
185507320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
185607320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1857