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"
24652852c5SGeorge Rimar #include "OutputSections.h"
25e77b5bf6SAdhemerval Zanella #include "ScriptParser.h"
2693c9af42SRui Ueyama #include "Strings.h"
27eda81a1bSEugene Leviant #include "Symbols.h"
28f7c5fbb1SRui Ueyama #include "SymbolTable.h"
29467c4d55SEugene Leviant #include "Target.h"
30bbe38602SEugene Leviant #include "Writer.h"
31960504b9SRui Ueyama #include "llvm/ADT/StringSwitch.h"
32652852c5SGeorge Rimar #include "llvm/Support/ELF.h"
33f7c5fbb1SRui Ueyama #include "llvm/Support/FileSystem.h"
34f7c5fbb1SRui Ueyama #include "llvm/Support/MemoryBuffer.h"
35f03f3cc1SRui Ueyama #include "llvm/Support/Path.h"
36a47ee68dSRui Ueyama #include "llvm/Support/StringSaver.h"
37f7c5fbb1SRui Ueyama 
38f7c5fbb1SRui Ueyama using namespace llvm;
39652852c5SGeorge Rimar using namespace llvm::ELF;
401ebc8ed7SRui Ueyama using namespace llvm::object;
41e38cbab5SGeorge Rimar using namespace llvm::support::endian;
42f7c5fbb1SRui Ueyama using namespace lld;
43e0df00b9SRafael Espindola using namespace lld::elf;
44f7c5fbb1SRui Ueyama 
45884e786dSGeorge Rimar LinkerScriptBase *elf::ScriptBase;
4607320e40SRui Ueyama ScriptConfiguration *elf::ScriptConfig;
47717677afSRui Ueyama 
486c55f0e3SGeorge Rimar template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
491602421cSRui Ueyama   Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
501602421cSRui Ueyama   Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
511602421cSRui Ueyama   Cmd->Sym = Sym->body();
5220d03194SEugene Leviant 
5320d03194SEugene Leviant   // If we have no SECTIONS then we don't have '.' and don't call
5420d03194SEugene Leviant   // assignAddresses(). We calculate symbol value immediately in this case.
5520d03194SEugene Leviant   if (!ScriptConfig->HasSections)
5620d03194SEugene Leviant     cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
57ceabe80eSEugene Leviant }
58ceabe80eSEugene Leviant 
590c70d3ccSRui Ueyama template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
60e1937bb5SGeorge Rimar   Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
61e1937bb5SGeorge Rimar       Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
621602421cSRui Ueyama   Cmd->Sym = Sym->body();
63ceabe80eSEugene Leviant }
64ceabe80eSEugene Leviant 
65db741e72SEugene Leviant template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
66db741e72SEugene Leviant   if (Cmd->IsAbsolute)
67db741e72SEugene Leviant     addRegular<ELFT>(Cmd);
68db741e72SEugene Leviant   else
69db741e72SEugene Leviant     addSynthetic<ELFT>(Cmd);
70db741e72SEugene Leviant }
711602421cSRui Ueyama // If a symbol was in PROVIDE(), we need to define it only when
721602421cSRui Ueyama // it is an undefined symbol.
731602421cSRui Ueyama template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
741602421cSRui Ueyama   if (Cmd->Name == ".")
75ceabe80eSEugene Leviant     return false;
761602421cSRui Ueyama   if (!Cmd->Provide)
77ceabe80eSEugene Leviant     return true;
781602421cSRui Ueyama   SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
791602421cSRui Ueyama   return B && B->isUndefined();
80ceabe80eSEugene Leviant }
81ceabe80eSEugene Leviant 
82076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
83076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
84076fe157SGeorge Rimar }
85076fe157SGeorge Rimar 
86076fe157SGeorge Rimar bool OutputSectionCommand::classof(const BaseCommand *C) {
87076fe157SGeorge Rimar   return C->Kind == OutputSectionKind;
88076fe157SGeorge Rimar }
89076fe157SGeorge Rimar 
90eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
91eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
92eea3114fSGeorge Rimar }
93eea3114fSGeorge Rimar 
94eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
95eefa758eSGeorge Rimar   return C->Kind == AssertKind;
96eefa758eSGeorge Rimar }
97eefa758eSGeorge Rimar 
98e38cbab5SGeorge Rimar bool BytesDataCommand::classof(const BaseCommand *C) {
99e38cbab5SGeorge Rimar   return C->Kind == BytesDataKind;
100e38cbab5SGeorge Rimar }
101e38cbab5SGeorge Rimar 
10236a153cdSRui Ueyama template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
103eea3114fSGeorge Rimar   return !S || !S->Live;
104717677afSRui Ueyama }
105717677afSRui Ueyama 
106f34d0e08SRui Ueyama template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
107f34d0e08SRui Ueyama template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
108f34d0e08SRui Ueyama 
10907320e40SRui Ueyama template <class ELFT>
11007320e40SRui Ueyama bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
111cf43f179SEugene Leviant   for (InputSectionDescription *ID : Opt.KeptSections) {
112cf43f179SEugene Leviant     StringRef Filename = S->getFile()->getName();
113cf43f179SEugene Leviant     if (!ID->FileRe.match(sys::path::filename(Filename)))
114cf43f179SEugene Leviant       continue;
115cf43f179SEugene Leviant 
116cf43f179SEugene Leviant     for (SectionPattern &P : ID->SectionPatterns)
117cf43f179SEugene Leviant       if (P.SectionRe.match(S->Name))
118eea3114fSGeorge Rimar         return true;
119cf43f179SEugene Leviant   }
120eea3114fSGeorge Rimar   return false;
121eea3114fSGeorge Rimar }
122eea3114fSGeorge Rimar 
123575208caSGeorge Rimar static bool comparePriority(InputSectionData *A, InputSectionData *B) {
124575208caSGeorge Rimar   return getPriority(A->Name) < getPriority(B->Name);
125575208caSGeorge Rimar }
126575208caSGeorge Rimar 
127c0028d3dSRafael Espindola static bool compareName(InputSectionData *A, InputSectionData *B) {
128042a3f20SRafael Espindola   return A->Name < B->Name;
1290702c4e8SGeorge Rimar }
130742c3836SRui Ueyama 
131c0028d3dSRafael Espindola static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
132742c3836SRui Ueyama   // ">" is not a mistake. Larger alignments are placed before smaller
133742c3836SRui Ueyama   // alignments in order to reduce the amount of padding necessary.
134742c3836SRui Ueyama   // This is compatible with GNU.
135742c3836SRui Ueyama   return A->Alignment > B->Alignment;
136742c3836SRui Ueyama }
137742c3836SRui Ueyama 
138c0028d3dSRafael Espindola static std::function<bool(InputSectionData *, InputSectionData *)>
139be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
140be394db3SGeorge Rimar   switch (K) {
141be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
142c0028d3dSRafael Espindola     return compareAlignment;
143be394db3SGeorge Rimar   case SortSectionPolicy::Name:
144be394db3SGeorge Rimar     return compareName;
145be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
146be394db3SGeorge Rimar     return comparePriority;
147be394db3SGeorge Rimar   default:
148be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
149be394db3SGeorge Rimar   }
150742c3836SRui Ueyama }
1510702c4e8SGeorge Rimar 
15248c3f1ceSRui Ueyama template <class ELFT>
153e71a3f8aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
15406ae6836SGeorge Rimar                              ConstraintKind Kind) {
1558f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
1568f66df92SGeorge Rimar     return true;
157e746e52cSRafael Espindola   bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
158d3190795SRafael Espindola     auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
159e746e52cSRafael Espindola     return Sec->getSectionHdr()->sh_flags & SHF_WRITE;
16006ae6836SGeorge Rimar   });
161e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
162e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
16306ae6836SGeorge Rimar }
16406ae6836SGeorge Rimar 
16507171f21SGeorge Rimar static void sortSections(InputSectionData **Begin, InputSectionData **End,
166ee924709SRui Ueyama                          SortSectionPolicy K) {
167ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
16807171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
169ee924709SRui Ueyama }
170ee924709SRui Ueyama 
171d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
172be94e1b6SRafael Espindola template <class ELFT>
173e71a3f8aSRafael Espindola void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
1744dc07becSRui Ueyama   // Collects all sections that satisfy constraints of I
1754dc07becSRui Ueyama   // and attach them to I.
1764dc07becSRui Ueyama   for (SectionPattern &Pat : I->SectionPatterns) {
17707171f21SGeorge Rimar     size_t SizeBefore = I->Sections.size();
178395281cfSGeorge Rimar     for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
1793ff27f49SRui Ueyama       StringRef Filename = sys::path::filename(F->getName());
180f135f0ecSRafael Espindola       if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
1813ff27f49SRui Ueyama         continue;
1824dc07becSRui Ueyama 
183be94e1b6SRafael Espindola       for (InputSectionBase<ELFT> *S : F->getSections())
184f135f0ecSRafael Espindola         if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
185d3190795SRafael Espindola           I->Sections.push_back(S);
186f135f0ecSRafael Espindola       if (Pat.SectionRe.match("COMMON"))
187d3190795SRafael Espindola         I->Sections.push_back(CommonInputSection<ELFT>::X);
188395281cfSGeorge Rimar     }
189d3190795SRafael Espindola 
190ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
191ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
192ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
193ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
194ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
195ee924709SRui Ueyama     //
196ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
197ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
198ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
199ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
200ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
20107171f21SGeorge Rimar     InputSectionData **Begin = I->Sections.data() + SizeBefore;
20207171f21SGeorge Rimar     InputSectionData **End = I->Sections.data() + I->Sections.size();
20307171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
20407171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
20507171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
206ee924709SRui Ueyama       else
20707171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
20807171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
20907171f21SGeorge Rimar     }
210ee924709SRui Ueyama   }
211d3190795SRafael Espindola 
212d3190795SRafael Espindola   // We do not add duplicate input sections, so mark them with a dummy output
213d3190795SRafael Espindola   // section for now.
214d3190795SRafael Espindola   for (InputSectionData *S : I->Sections) {
215d3190795SRafael Espindola     auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
216d3190795SRafael Espindola     S2->OutSec = (OutputSectionBase<ELFT> *)-1;
217d3190795SRafael Espindola   }
218be94e1b6SRafael Espindola }
219be94e1b6SRafael Espindola 
220be94e1b6SRafael Espindola template <class ELFT>
221be94e1b6SRafael Espindola void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
222be94e1b6SRafael Espindola   for (InputSectionBase<ELFT> *S : V) {
223be94e1b6SRafael Espindola     S->Live = false;
224be94e1b6SRafael Espindola     reportDiscarded(S);
225be94e1b6SRafael Espindola   }
226be94e1b6SRafael Espindola }
227be94e1b6SRafael Espindola 
22806ae6836SGeorge Rimar template <class ELFT>
2290b9ce6a4SRui Ueyama std::vector<InputSectionBase<ELFT> *>
23006ae6836SGeorge Rimar LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
2310b9ce6a4SRui Ueyama   std::vector<InputSectionBase<ELFT> *> Ret;
232e7f912cdSRui Ueyama 
23306ae6836SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
2347c3ff2ebSRafael Espindola     auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
2357c3ff2ebSRafael Espindola     if (!Cmd)
2360b9ce6a4SRui Ueyama       continue;
237e71a3f8aSRafael Espindola     computeInputSections(Cmd);
238d3190795SRafael Espindola     for (InputSectionData *S : Cmd->Sections)
239d3190795SRafael Espindola       Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
2400b9ce6a4SRui Ueyama   }
241e71a3f8aSRafael Espindola 
242cc1ba8c7SEugene Leviant   // After we created final list we should now set OutSec pointer to null,
243cc1ba8c7SEugene Leviant   // instead of -1. Otherwise we may get a crash when writing relocs, in
244cc1ba8c7SEugene Leviant   // case section is discarded by linker script
245cc1ba8c7SEugene Leviant   for (InputSectionBase<ELFT> *S : Ret)
246cc1ba8c7SEugene Leviant     S->OutSec = nullptr;
247cc1ba8c7SEugene Leviant 
2480b9ce6a4SRui Ueyama   return Ret;
2490b9ce6a4SRui Ueyama }
2500b9ce6a4SRui Ueyama 
251e5d3ca50SPetr Hosek template <class ELFT>
25210897f18SRafael Espindola static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
25310897f18SRafael Espindola                                             StringRef OutsecName) {
25410897f18SRafael Espindola   // When using linker script the merge rules are different.
25510897f18SRafael Espindola   // Unfortunately, linker scripts are name based. This means that expressions
25610897f18SRafael Espindola   // like *(.foo*) can refer to multiple input sections that would normally be
25710897f18SRafael Espindola   // placed in different output sections. We cannot put them in different
25810897f18SRafael Espindola   // output sections or we would produce wrong results for
25910897f18SRafael Espindola   // start = .; *(.foo.*) end = .; *(.bar)
26010897f18SRafael Espindola   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
26110897f18SRafael Espindola   // another. The problem is that there is no way to layout those output
26210897f18SRafael Espindola   // sections such that the .foo sections are the only thing between the
26310897f18SRafael Espindola   // start and end symbols.
26410897f18SRafael Espindola 
26510897f18SRafael Espindola   // An extra annoyance is that we cannot simply disable merging of the contents
26610897f18SRafael Espindola   // of SHF_MERGE sections, but our implementation requires one output section
26710897f18SRafael Espindola   // per "kind" (string or not, which size/aligment).
26810897f18SRafael Espindola   // Fortunately, creating symbols in the middle of a merge section is not
26910897f18SRafael Espindola   // supported by bfd or gold, so we can just create multiple section in that
27010897f18SRafael Espindola   // case.
27110897f18SRafael Espindola   const typename ELFT::Shdr *H = C->getSectionHdr();
27210897f18SRafael Espindola   typedef typename ELFT::uint uintX_t;
27310897f18SRafael Espindola   uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
27410897f18SRafael Espindola 
27510897f18SRafael Espindola   uintX_t Alignment = 0;
27610897f18SRafael Espindola   if (isa<MergeInputSection<ELFT>>(C))
27710897f18SRafael Espindola     Alignment = std::max(H->sh_addralign, H->sh_entsize);
27810897f18SRafael Espindola 
27910897f18SRafael Espindola   return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
28010897f18SRafael Espindola }
28110897f18SRafael Espindola 
28210897f18SRafael Espindola template <class ELFT>
28320d03194SEugene Leviant void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
28420d03194SEugene Leviant                                     InputSectionBase<ELFT> *Sec,
28520d03194SEugene Leviant                                     StringRef Name) {
28628c1597aSRafael Espindola   OutputSectionBase<ELFT> *OutSec;
28728c1597aSRafael Espindola   bool IsNew;
28810897f18SRafael Espindola   std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
28928c1597aSRafael Espindola   if (IsNew)
29028c1597aSRafael Espindola     OutputSections->push_back(OutSec);
29120d03194SEugene Leviant   OutSec->addSection(Sec);
29220d03194SEugene Leviant }
29320d03194SEugene Leviant 
29420d03194SEugene Leviant template <class ELFT>
29520d03194SEugene Leviant void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
29628c1597aSRafael Espindola 
2977c3ff2ebSRafael Espindola   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
2987c3ff2ebSRafael Espindola     auto Iter = Opt.Commands.begin() + I;
2997c3ff2ebSRafael Espindola     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
3002ab5f73dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
3012ab5f73dSRui Ueyama       if (shouldDefine<ELFT>(Cmd))
3022ab5f73dSRui Ueyama         addRegular<ELFT>(Cmd);
3032ab5f73dSRui Ueyama       continue;
3042ab5f73dSRui Ueyama     }
30520d03194SEugene Leviant     if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
30620d03194SEugene Leviant       // If we don't have SECTIONS then output sections have already been
307194470cdSGeorge Rimar       // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
30820d03194SEugene Leviant       // will not be called, so ASSERT should be evaluated now.
30920d03194SEugene Leviant       if (!Opt.HasSections)
31020d03194SEugene Leviant         Cmd->Expression(0);
31120d03194SEugene Leviant       continue;
31220d03194SEugene Leviant     }
3132ab5f73dSRui Ueyama 
314ceabe80eSEugene Leviant     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
3157bd37870SRafael Espindola       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
3167bd37870SRafael Espindola 
31748c3f1ceSRui Ueyama       if (Cmd->Name == "/DISCARD/") {
3187bd37870SRafael Espindola         discard(V);
31948c3f1ceSRui Ueyama         continue;
32048c3f1ceSRui Ueyama       }
3210b9ce6a4SRui Ueyama 
3227c3ff2ebSRafael Espindola       if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
3237c3ff2ebSRafael Espindola         for (InputSectionBase<ELFT> *S : V)
3247c3ff2ebSRafael Espindola           S->OutSec = nullptr;
3257c3ff2ebSRafael Espindola         Opt.Commands.erase(Iter);
326dfbbbc86SGeorge Rimar         --I;
3277c3ff2ebSRafael Espindola         continue;
3287c3ff2ebSRafael Espindola       }
3297c3ff2ebSRafael Espindola 
3307c3ff2ebSRafael Espindola       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
3317c3ff2ebSRafael Espindola         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
3327c3ff2ebSRafael Espindola           if (shouldDefine<ELFT>(OutCmd))
3337c3ff2ebSRafael Espindola             addSymbol<ELFT>(OutCmd);
3347c3ff2ebSRafael Espindola 
33597403d15SEugene Leviant       if (V.empty())
3360b9ce6a4SRui Ueyama         continue;
3370b9ce6a4SRui Ueyama 
338a14b13d8SGeorge Rimar       for (InputSectionBase<ELFT> *Sec : V) {
33920d03194SEugene Leviant         addSection(Factory, Sec, Cmd->Name);
34020d03194SEugene Leviant         if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
341db24d9c3SGeorge Rimar           Sec->Alignment = Subalign;
34220d03194SEugene Leviant       }
343eea3114fSGeorge Rimar     }
34448c3f1ceSRui Ueyama   }
345db24d9c3SGeorge Rimar }
346e63d81bdSEugene Leviant 
34720d03194SEugene Leviant template <class ELFT>
34820d03194SEugene Leviant void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
34920d03194SEugene Leviant   processCommands(Factory);
3500b9ce6a4SRui Ueyama   // Add orphan sections.
35120d03194SEugene Leviant   for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
35220d03194SEugene Leviant     for (InputSectionBase<ELFT> *S : F->getSections())
35320d03194SEugene Leviant       if (!isDiscarded(S) && !S->OutSec)
35405384080SRui Ueyama         addSection(Factory, S, getOutputSectionName(S->Name, Opt.Alloc));
355e63d81bdSEugene Leviant }
356e63d81bdSEugene Leviant 
357db741e72SEugene Leviant // Sets value of a section-defined symbol. Two kinds of
358db741e72SEugene Leviant // symbols are processed: synthetic symbols, whose value
359db741e72SEugene Leviant // is an offset from beginning of section and regular
360db741e72SEugene Leviant // symbols whose value is absolute.
361db741e72SEugene Leviant template <class ELFT>
362db741e72SEugene Leviant static void assignSectionSymbol(SymbolAssignment *Cmd,
363db741e72SEugene Leviant                                 OutputSectionBase<ELFT> *Sec,
364db741e72SEugene Leviant                                 typename ELFT::uint Off) {
365db741e72SEugene Leviant   if (!Cmd->Sym)
366db741e72SEugene Leviant     return;
367db741e72SEugene Leviant 
368db741e72SEugene Leviant   if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
369db741e72SEugene Leviant     Body->Section = Sec;
370db741e72SEugene Leviant     Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
371db741e72SEugene Leviant     return;
372db741e72SEugene Leviant   }
373db741e72SEugene Leviant   auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
374db741e72SEugene Leviant   Body->Value = Cmd->Expression(Sec->getVA() + Off);
375db741e72SEugene Leviant }
376db741e72SEugene Leviant 
377a940e539SRafael Espindola template <class ELFT> static bool isTbss(OutputSectionBase<ELFT> *Sec) {
378a940e539SRafael Espindola   return (Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS;
379a940e539SRafael Espindola }
380a940e539SRafael Espindola 
381d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
382d3190795SRafael Espindola   if (!AlreadyOutputIS.insert(S).second)
383ceabe80eSEugene Leviant     return;
384a940e539SRafael Espindola   bool IsTbss = isTbss(CurOutSec);
385d3190795SRafael Espindola 
386d3190795SRafael Espindola   uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
387d3190795SRafael Espindola   Pos = alignTo(Pos, S->Alignment);
388d3190795SRafael Espindola   S->OutSecOff = Pos - CurOutSec->getVA();
389d3190795SRafael Espindola   Pos += S->getSize();
390d3190795SRafael Espindola 
391d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
392d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
393d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
394d3190795SRafael Espindola   CurOutSec->setSize(Pos - CurOutSec->getVA());
395d3190795SRafael Espindola 
3967252ae52SRafael Espindola   if (IsTbss)
3977252ae52SRafael Espindola     ThreadBssOffset = Pos - Dot;
3987252ae52SRafael Espindola   else
399d3190795SRafael Espindola     Dot = Pos;
4002de509c3SRui Ueyama }
401ceabe80eSEugene Leviant 
402d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::flush() {
40365499b90SRafael Espindola   if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
40465499b90SRafael Espindola     return;
40565499b90SRafael Espindola   if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
406d3190795SRafael Espindola     for (InputSection<ELFT> *I : OutSec->Sections)
407d3190795SRafael Espindola       output(I);
40865499b90SRafael Espindola   } else {
40965499b90SRafael Espindola     Dot += CurOutSec->getSize();
410d3190795SRafael Espindola   }
411d3190795SRafael Espindola }
41297403d15SEugene Leviant 
413d3190795SRafael Espindola template <class ELFT>
414d3190795SRafael Espindola void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
415d3190795SRafael Espindola   if (CurOutSec == Sec)
416d3190795SRafael Espindola     return;
417d3190795SRafael Espindola   if (AlreadyOutputOS.count(Sec))
418d3190795SRafael Espindola     return;
419d3190795SRafael Espindola 
420d3190795SRafael Espindola   flush();
421d3190795SRafael Espindola   CurOutSec = Sec;
422d3190795SRafael Espindola 
423d3190795SRafael Espindola   Dot = alignTo(Dot, CurOutSec->getAlignment());
424a940e539SRafael Espindola   CurOutSec->setVA(isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot);
425b71d6f7aSEugene Leviant 
426b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
427b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
428b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
429b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
430b71d6f7aSEugene Leviant   CurOutSec->setLMAOffset(LMAOffset);
431d3190795SRafael Espindola }
432d3190795SRafael Espindola 
433d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
434e38cbab5SGeorge Rimar   // This handles the assignments to symbol or to a location counter (.)
435d3190795SRafael Espindola   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
43697403d15SEugene Leviant     if (AssignCmd->Name == ".") {
43797403d15SEugene Leviant       // Update to location counter means update to section size.
438d3190795SRafael Espindola       Dot = AssignCmd->Expression(Dot);
439d3190795SRafael Espindola       CurOutSec->setSize(Dot - CurOutSec->getVA());
440d3190795SRafael Espindola       return;
44197403d15SEugene Leviant     }
442d3190795SRafael Espindola     assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
443d3190795SRafael Espindola     return;
44497403d15SEugene Leviant   }
445e38cbab5SGeorge Rimar 
446e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
447e38cbab5SGeorge Rimar   if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
448e38cbab5SGeorge Rimar     DataCmd->Offset = Dot - CurOutSec->getVA();
449e38cbab5SGeorge Rimar     Dot += DataCmd->Size;
450e38cbab5SGeorge Rimar     CurOutSec->setSize(Dot - CurOutSec->getVA());
451e38cbab5SGeorge Rimar     return;
452e38cbab5SGeorge Rimar   }
453e38cbab5SGeorge Rimar 
454e38cbab5SGeorge Rimar   // It handles single input section description command,
455e38cbab5SGeorge Rimar   // calculates and assigns the offsets for each section and also
456e38cbab5SGeorge Rimar   // updates the output section size.
457d3190795SRafael Espindola   auto &ICmd = cast<InputSectionDescription>(Base);
458d3190795SRafael Espindola   for (InputSectionData *ID : ICmd.Sections) {
459d3190795SRafael Espindola     auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
460d3190795SRafael Espindola     switchTo(IB->OutSec);
461d3190795SRafael Espindola     if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
462d3190795SRafael Espindola       output(I);
46365499b90SRafael Espindola     else
46465499b90SRafael Espindola       flush();
465ceabe80eSEugene Leviant   }
466ceabe80eSEugene Leviant }
467ceabe80eSEugene Leviant 
4688f66df92SGeorge Rimar template <class ELFT>
469a14b13d8SGeorge Rimar static std::vector<OutputSectionBase<ELFT> *>
4709257764dSEugene Leviant findSections(StringRef Name,
471d3190795SRafael Espindola              const std::vector<OutputSectionBase<ELFT> *> &Sections) {
472a14b13d8SGeorge Rimar   std::vector<OutputSectionBase<ELFT> *> Ret;
473a14b13d8SGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : Sections)
4749257764dSEugene Leviant     if (Sec->getName() == Name)
475a14b13d8SGeorge Rimar       Ret.push_back(Sec);
476a14b13d8SGeorge Rimar   return Ret;
4778f66df92SGeorge Rimar }
4788f66df92SGeorge Rimar 
479d3190795SRafael Espindola template <class ELFT>
480d3190795SRafael Espindola void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
481b71d6f7aSEugene Leviant   if (Cmd->LMAExpr)
482b71d6f7aSEugene Leviant     LMAOffset = Cmd->LMAExpr(Dot) - Dot;
483d3190795SRafael Espindola   std::vector<OutputSectionBase<ELFT> *> Sections =
4849257764dSEugene Leviant       findSections(Cmd->Name, *OutputSections);
485d3190795SRafael Espindola   if (Sections.empty())
486d3190795SRafael Espindola     return;
487d3190795SRafael Espindola   switchTo(Sections[0]);
488d3190795SRafael Espindola   // Find the last section output location. We will output orphan sections
489d3190795SRafael Espindola   // there so that end symbols point to the correct location.
490d3190795SRafael Espindola   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
491d3190795SRafael Espindola                         [](const std::unique_ptr<BaseCommand> &Cmd) {
492d3190795SRafael Espindola                           return !isa<SymbolAssignment>(*Cmd);
493d3190795SRafael Espindola                         })
494d3190795SRafael Espindola                .base();
495d3190795SRafael Espindola   for (auto I = Cmd->Commands.begin(); I != E; ++I)
496d3190795SRafael Espindola     process(**I);
49765499b90SRafael Espindola   for (OutputSectionBase<ELFT> *Base : Sections)
498d3190795SRafael Espindola     switchTo(Base);
4992506cb4dSEugene Leviant   flush();
500b31dd370SGeorge Rimar   std::for_each(E, Cmd->Commands.end(),
501b31dd370SGeorge Rimar                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
502d3190795SRafael Espindola }
503d3190795SRafael Espindola 
5049546fffbSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
5056d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
5066d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
5076d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
5086d38e4dbSRafael Espindola   // clutter the output.
5096d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
5106d38e4dbSRafael Espindola   // more aggressive at removing them.
5116d38e4dbSRafael Espindola   auto Pos = std::remove_if(
5126d38e4dbSRafael Espindola       Opt.Commands.begin(), Opt.Commands.end(),
5136d38e4dbSRafael Espindola       [&](const std::unique_ptr<BaseCommand> &Base) {
5146d38e4dbSRafael Espindola         auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
5156d38e4dbSRafael Espindola         if (!Cmd)
5166d38e4dbSRafael Espindola           return false;
5176d38e4dbSRafael Espindola         std::vector<OutputSectionBase<ELFT> *> Secs =
5189257764dSEugene Leviant             findSections(Cmd->Name, *OutputSections);
5196d38e4dbSRafael Espindola         if (!Secs.empty())
5206d38e4dbSRafael Espindola           return false;
5216d38e4dbSRafael Espindola         for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
5226d38e4dbSRafael Espindola           if (!isa<InputSectionDescription>(I.get()))
5236d38e4dbSRafael Espindola             return false;
5246d38e4dbSRafael Espindola         return true;
5256d38e4dbSRafael Espindola       });
5266d38e4dbSRafael Espindola   Opt.Commands.erase(Pos, Opt.Commands.end());
5276d38e4dbSRafael Espindola 
5289546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
5299546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
5309546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
5319546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
5329546fffbSRafael Espindola   uintX_t Flags = SHF_ALLOC;
5339546fffbSRafael Espindola   uint32_t Type = 0;
5349546fffbSRafael Espindola   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
5359546fffbSRafael Espindola     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
5369546fffbSRafael Espindola     if (!Cmd)
5379546fffbSRafael Espindola       continue;
5389546fffbSRafael Espindola     std::vector<OutputSectionBase<ELFT> *> Secs =
5399257764dSEugene Leviant         findSections(Cmd->Name, *OutputSections);
5409546fffbSRafael Espindola     if (!Secs.empty()) {
5419546fffbSRafael Espindola       Flags = Secs[0]->getFlags();
5429546fffbSRafael Espindola       Type = Secs[0]->getType();
5439546fffbSRafael Espindola       continue;
5449546fffbSRafael Espindola     }
5459546fffbSRafael Espindola 
5469546fffbSRafael Espindola     auto *OutSec = new OutputSection<ELFT>(Cmd->Name, Type, Flags);
5479546fffbSRafael Espindola     Out<ELFT>::Pool.emplace_back(OutSec);
5489546fffbSRafael Espindola     OutputSections->push_back(OutSec);
5499546fffbSRafael Espindola   }
5509546fffbSRafael Espindola }
5519546fffbSRafael Espindola 
55215c57951SRafael Espindola // When placing orphan sections, we want to place them after symbol assignments
55315c57951SRafael Espindola // so that an orphan after
55415c57951SRafael Espindola //   begin_foo = .;
55515c57951SRafael Espindola //   foo : { *(foo) }
55615c57951SRafael Espindola //   end_foo = .;
55715c57951SRafael Espindola // doesn't break the intended meaning of the begin/end symbols.
55815c57951SRafael Espindola // We don't want to go over sections since Writer<ELFT>::sortSections is the
55915c57951SRafael Espindola // one in charge of deciding the order of the sections.
56015c57951SRafael Espindola // We don't want to go over alignments, since doing so in
56115c57951SRafael Espindola //  rx_sec : { *(rx_sec) }
56215c57951SRafael Espindola //  . = ALIGN(0x1000);
56315c57951SRafael Espindola //  /* The RW PT_LOAD starts here*/
56415c57951SRafael Espindola //  rw_sec : { *(rw_sec) }
56515c57951SRafael Espindola // would mean that the RW PT_LOAD would become unaligned.
56615c57951SRafael Espindola static bool shouldSkip(const BaseCommand &Cmd) {
56715c57951SRafael Espindola   if (isa<OutputSectionCommand>(Cmd))
56815c57951SRafael Espindola     return false;
56915c57951SRafael Espindola   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
57015c57951SRafael Espindola   if (!Assign)
57115c57951SRafael Espindola     return true;
57215c57951SRafael Espindola   return Assign->Name != ".";
57315c57951SRafael Espindola }
57415c57951SRafael Espindola 
5756d91fce5SRafael Espindola template <class ELFT>
5766d91fce5SRafael Espindola void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
577652852c5SGeorge Rimar   // Orphan sections are sections present in the input files which
5787c18c28cSRui Ueyama   // are not explicitly placed into the output file by the linker script.
5797c18c28cSRui Ueyama   // We place orphan sections at end of file.
5807c18c28cSRui Ueyama   // Other linkers places them using some heuristics as described in
581652852c5SGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
582aab6d5c5SRafael Espindola 
583aab6d5c5SRafael Espindola   // The OutputSections are already in the correct order.
584aab6d5c5SRafael Espindola   // This loops creates or moves commands as needed so that they are in the
585aab6d5c5SRafael Espindola   // correct order.
586aab6d5c5SRafael Espindola   int CmdIndex = 0;
587e5cc668eSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
588652852c5SGeorge Rimar     StringRef Name = Sec->getName();
589aab6d5c5SRafael Espindola 
590aab6d5c5SRafael Espindola     // Find the last spot where we can insert a command and still get the
59115c57951SRafael Espindola     // correct result.
592aab6d5c5SRafael Espindola     auto CmdIter = Opt.Commands.begin() + CmdIndex;
593aab6d5c5SRafael Espindola     auto E = Opt.Commands.end();
59415c57951SRafael Espindola     while (CmdIter != E && shouldSkip(**CmdIter)) {
595aab6d5c5SRafael Espindola       ++CmdIter;
596aab6d5c5SRafael Espindola       ++CmdIndex;
597aab6d5c5SRafael Espindola     }
598aab6d5c5SRafael Espindola 
599aab6d5c5SRafael Espindola     auto Pos =
600aab6d5c5SRafael Espindola         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
601aab6d5c5SRafael Espindola           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
602aab6d5c5SRafael Espindola           return Cmd && Cmd->Name == Name;
603aab6d5c5SRafael Espindola         });
604aab6d5c5SRafael Espindola     if (Pos == E) {
605aab6d5c5SRafael Espindola       Opt.Commands.insert(CmdIter,
606aab6d5c5SRafael Espindola                           llvm::make_unique<OutputSectionCommand>(Name));
607aab6d5c5SRafael Espindola       ++CmdIndex;
60815c57951SRafael Espindola       continue;
60915c57951SRafael Espindola     }
61015c57951SRafael Espindola 
61115c57951SRafael Espindola     // Continue from where we found it.
61215c57951SRafael Espindola     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
61315c57951SRafael Espindola     continue;
614652852c5SGeorge Rimar   }
615652852c5SGeorge Rimar 
6167c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
617be607334SRafael Espindola   Dot = 0;
618652852c5SGeorge Rimar 
619076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
620076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
6218d083e6aSRui Ueyama       if (Cmd->Name == ".") {
6228d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
6238d083e6aSRui Ueyama       } else if (Cmd->Sym) {
6248d083e6aSRui Ueyama         cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
6258d083e6aSRui Ueyama       }
62605ef4cffSRui Ueyama       continue;
627652852c5SGeorge Rimar     }
628652852c5SGeorge Rimar 
629eefa758eSGeorge Rimar     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
630eefa758eSGeorge Rimar       Cmd->Expression(Dot);
631eefa758eSGeorge Rimar       continue;
632eefa758eSGeorge Rimar     }
633eefa758eSGeorge Rimar 
634076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
635652852c5SGeorge Rimar 
63658e5c4dcSGeorge Rimar     if (Cmd->AddrExpr)
63758e5c4dcSGeorge Rimar       Dot = Cmd->AddrExpr(Dot);
63858e5c4dcSGeorge Rimar 
639d3190795SRafael Espindola     assignOffsets(Cmd);
640a14b13d8SGeorge Rimar   }
641467c4d55SEugene Leviant 
642aab6d5c5SRafael Espindola   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
643aab6d5c5SRafael Espindola   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
644aab6d5c5SRafael Espindola     if (Sec->getFlags() & SHF_ALLOC)
645aab6d5c5SRafael Espindola       MinVA = std::min(MinVA, Sec->getVA());
646aab6d5c5SRafael Espindola     else
647d3190795SRafael Espindola       Sec->setVA(0);
648aab6d5c5SRafael Espindola   }
649aab6d5c5SRafael Espindola 
6500d4b6d5cSRafael Espindola   uintX_t HeaderSize = getHeaderSize();
6516d91fce5SRafael Espindola   auto FirstPTLoad =
6526d91fce5SRafael Espindola       std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
6536d91fce5SRafael Espindola         return E.H.p_type == PT_LOAD;
6546d91fce5SRafael Espindola       });
655*db35fdf7SEugene Leviant 
6566d91fce5SRafael Espindola   if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
657*db35fdf7SEugene Leviant     // If linker script specifies program headers and first PT_LOAD doesn't
658*db35fdf7SEugene Leviant     // have both PHDRS and FILEHDR attributes then do nothing
659*db35fdf7SEugene Leviant     if (!Opt.PhdrsCommands.empty()) {
660*db35fdf7SEugene Leviant       size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
661*db35fdf7SEugene Leviant       if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
662*db35fdf7SEugene Leviant           !Opt.PhdrsCommands[SegNum].HasFilehdr)
663*db35fdf7SEugene Leviant         return;
664*db35fdf7SEugene Leviant     }
66564c32d6fSRafael Espindola     // ELF and Program headers need to be right before the first section in
666b91e7118SGeorge Rimar     // memory. Set their addresses accordingly.
6674ec013acSRafael Espindola     MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
668467c4d55SEugene Leviant     Out<ELFT>::ElfHeader->setVA(MinVA);
669467c4d55SEugene Leviant     Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
6706d91fce5SRafael Espindola     FirstPTLoad->First = Out<ELFT>::ElfHeader;
6716d91fce5SRafael Espindola     if (!FirstPTLoad->Last)
6726d91fce5SRafael Espindola       FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
673cd8eaf89SEugene Leviant   } else if (!FirstPTLoad->First) {
674cd8eaf89SEugene Leviant     // Sometimes the very first PT_LOAD segment can be empty.
675cd8eaf89SEugene Leviant     // This happens if (all conditions met):
676cd8eaf89SEugene Leviant     //  - Linker script is used
677cd8eaf89SEugene Leviant     //  - First section in ELF image is not RO
678cd8eaf89SEugene Leviant     //  - Not enough space for program headers.
679cd8eaf89SEugene Leviant     // The code below removes empty PT_LOAD segment and updates
680cd8eaf89SEugene Leviant     // program headers size.
681cd8eaf89SEugene Leviant     Phdrs.erase(FirstPTLoad);
682cd8eaf89SEugene Leviant     Out<ELFT>::ProgramHeaders->setSize(sizeof(typename ELFT::Phdr) *
683cd8eaf89SEugene Leviant                                        Phdrs.size());
6846d91fce5SRafael Espindola   }
685fb8978fcSDima Stepanov }
686652852c5SGeorge Rimar 
687464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
68807320e40SRui Ueyama template <class ELFT>
689a4b41dcaSRafael Espindola std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
690edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
691bbe38602SEugene Leviant 
692464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
693464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
694ce30b1c7SEugene Leviant   std::vector<size_t> DefPhdrIds;
695bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
696edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
697edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
698bbe38602SEugene Leviant 
699bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
700adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
701bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
702adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
70356b21c86SEugene Leviant 
70456b21c86SEugene Leviant     if (Cmd.LMAExpr) {
70556b21c86SEugene Leviant       Phdr.H.p_paddr = Cmd.LMAExpr(0);
70656b21c86SEugene Leviant       Phdr.HasLMA = true;
70756b21c86SEugene Leviant     }
708ce30b1c7SEugene Leviant 
709ce30b1c7SEugene Leviant     // If output section command doesn't specify any segments,
710ce30b1c7SEugene Leviant     // and we haven't previously assigned any section to segment,
711ce30b1c7SEugene Leviant     // then we simply assign section to the very first load segment.
712ce30b1c7SEugene Leviant     // Below is an example of such linker script:
713ce30b1c7SEugene Leviant     // PHDRS { seg PT_LOAD; }
714ce30b1c7SEugene Leviant     // SECTIONS { .aaa : { *(.aaa) } }
715ce30b1c7SEugene Leviant     if (DefPhdrIds.empty() && Phdr.H.p_type == PT_LOAD)
716ce30b1c7SEugene Leviant       DefPhdrIds.push_back(Ret.size() - 1);
717bbe38602SEugene Leviant   }
718bbe38602SEugene Leviant 
719464daadcSRui Ueyama   // Add output sections to program headers.
720464daadcSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
721bbe38602SEugene Leviant     if (!(Sec->getFlags() & SHF_ALLOC))
722bbe38602SEugene Leviant       break;
723bbe38602SEugene Leviant 
724edebbdf1SRui Ueyama     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
725ce30b1c7SEugene Leviant     if (PhdrIds.empty())
726ce30b1c7SEugene Leviant       PhdrIds = std::move(DefPhdrIds);
727ce30b1c7SEugene Leviant 
728bbe38602SEugene Leviant     // Assign headers specified by linker script
729bbe38602SEugene Leviant     for (size_t Id : PhdrIds) {
730edebbdf1SRui Ueyama       Ret[Id].add(Sec);
731865bf863SEugene Leviant       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
7320b113671SRafael Espindola         Ret[Id].H.p_flags |= Sec->getPhdrFlags();
733bbe38602SEugene Leviant     }
734ce30b1c7SEugene Leviant     DefPhdrIds = std::move(PhdrIds);
735bbe38602SEugene Leviant   }
736edebbdf1SRui Ueyama   return Ret;
737bbe38602SEugene Leviant }
738bbe38602SEugene Leviant 
739f9bc3bd2SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
740f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
741f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
742f9bc3bd2SEugene Leviant   return !Opt.PhdrsCommands.empty() &&
743f9bc3bd2SEugene Leviant          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
744f9bc3bd2SEugene Leviant            return Cmd.Type == PT_INTERP;
745f9bc3bd2SEugene Leviant          }) == Opt.PhdrsCommands.end();
746f9bc3bd2SEugene Leviant }
747f9bc3bd2SEugene Leviant 
748bbe38602SEugene Leviant template <class ELFT>
74907320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
750f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
751f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
752f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
753f6c3ccefSGeorge Rimar         return Cmd->Filler;
754e2ee72b5SGeorge Rimar   return {};
755e2ee72b5SGeorge Rimar }
756e2ee72b5SGeorge Rimar 
757e38cbab5SGeorge Rimar template <class ELFT>
758e38cbab5SGeorge Rimar static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
759e38cbab5SGeorge Rimar   const endianness E = ELFT::TargetEndianness;
760e38cbab5SGeorge Rimar 
761e38cbab5SGeorge Rimar   switch (Size) {
762e38cbab5SGeorge Rimar   case 1:
763e38cbab5SGeorge Rimar     *Buf = (uint8_t)Data;
764e38cbab5SGeorge Rimar     break;
765e38cbab5SGeorge Rimar   case 2:
766e38cbab5SGeorge Rimar     write16<E>(Buf, Data);
767e38cbab5SGeorge Rimar     break;
768e38cbab5SGeorge Rimar   case 4:
769e38cbab5SGeorge Rimar     write32<E>(Buf, Data);
770e38cbab5SGeorge Rimar     break;
771e38cbab5SGeorge Rimar   case 8:
772e38cbab5SGeorge Rimar     write64<E>(Buf, Data);
773e38cbab5SGeorge Rimar     break;
774e38cbab5SGeorge Rimar   default:
775e38cbab5SGeorge Rimar     llvm_unreachable("unsupported Size argument");
776e38cbab5SGeorge Rimar   }
777e38cbab5SGeorge Rimar }
778e38cbab5SGeorge Rimar 
779e38cbab5SGeorge Rimar template <class ELFT>
780e38cbab5SGeorge Rimar void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
781e38cbab5SGeorge Rimar   int I = getSectionIndex(Name);
782e38cbab5SGeorge Rimar   if (I == INT_MAX)
783e38cbab5SGeorge Rimar     return;
784e38cbab5SGeorge Rimar 
785e38cbab5SGeorge Rimar   OutputSectionCommand *Cmd =
786e38cbab5SGeorge Rimar       dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
787e38cbab5SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
788e38cbab5SGeorge Rimar     if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
789e38cbab5SGeorge Rimar       writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
790e38cbab5SGeorge Rimar }
791e38cbab5SGeorge Rimar 
792b71d6f7aSEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
7938ceadb38SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
7948ceadb38SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
795b71d6f7aSEugene Leviant       if (Cmd->LMAExpr && Cmd->Name == Name)
796b71d6f7aSEugene Leviant         return true;
797b71d6f7aSEugene Leviant   return false;
7988ceadb38SGeorge Rimar }
7998ceadb38SGeorge Rimar 
800c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
801c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
802c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
803c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
804076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
805f510fa6bSRui Ueyama   int I = 0;
806f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
807076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
808076fe157SGeorge Rimar       if (Cmd->Name == Name)
809f510fa6bSRui Ueyama         return I;
810f510fa6bSRui Ueyama     ++I;
811f510fa6bSRui Ueyama   }
812f510fa6bSRui Ueyama   return INT_MAX;
81371b26e94SGeorge Rimar }
81471b26e94SGeorge Rimar 
815bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
816bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
817bbe38602SEugene Leviant }
818bbe38602SEugene Leviant 
8199e69450eSGeorge Rimar template <class ELFT>
820884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
82196659df0SGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
82296659df0SGeorge Rimar     if (Sec->getName() == Name)
82396659df0SGeorge Rimar       return Sec->getVA();
82496659df0SGeorge Rimar   error("undefined section " + Name);
82596659df0SGeorge Rimar   return 0;
82696659df0SGeorge Rimar }
82796659df0SGeorge Rimar 
82896659df0SGeorge Rimar template <class ELFT>
829b71d6f7aSEugene Leviant uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
830b71d6f7aSEugene Leviant   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
831b71d6f7aSEugene Leviant     if (Sec->getName() == Name)
832b71d6f7aSEugene Leviant       return Sec->getLMA();
833b71d6f7aSEugene Leviant   error("undefined section " + Name);
834b71d6f7aSEugene Leviant   return 0;
835b71d6f7aSEugene Leviant }
836b71d6f7aSEugene Leviant 
837b71d6f7aSEugene Leviant template <class ELFT>
838884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
8399e69450eSGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
8409e69450eSGeorge Rimar     if (Sec->getName() == Name)
8419e69450eSGeorge Rimar       return Sec->getSize();
8429e69450eSGeorge Rimar   error("undefined section " + Name);
8439e69450eSGeorge Rimar   return 0;
8449e69450eSGeorge Rimar }
8459e69450eSGeorge Rimar 
84636fac7f0SEugene Leviant template <class ELFT>
84736fac7f0SEugene Leviant uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
84836fac7f0SEugene Leviant   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
84936fac7f0SEugene Leviant     if (Sec->getName() == Name)
85036fac7f0SEugene Leviant       return Sec->getAlignment();
85136fac7f0SEugene Leviant   error("undefined section " + Name);
85236fac7f0SEugene Leviant   return 0;
85336fac7f0SEugene Leviant }
85436fac7f0SEugene Leviant 
855884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
8560d4b6d5cSRafael Espindola   return elf::getHeaderSize<ELFT>();
857e32a3598SGeorge Rimar }
858e32a3598SGeorge Rimar 
859884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
860884e786dSGeorge Rimar   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
861884e786dSGeorge Rimar     return B->getVA<ELFT>();
862884e786dSGeorge Rimar   error("symbol not found: " + S);
863884e786dSGeorge Rimar   return 0;
864884e786dSGeorge Rimar }
865884e786dSGeorge Rimar 
866f34f45fdSGeorge Rimar template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
867f34f45fdSGeorge Rimar   return Symtab<ELFT>::X->find(S) != nullptr;
868f34f45fdSGeorge Rimar }
869f34f45fdSGeorge Rimar 
870bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
871bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
872bbe38602SEugene Leviant // PHDRS {} script block.
873bbe38602SEugene Leviant template <class ELFT>
874edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
875076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
876076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
877edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
87831d842f5SGeorge Rimar       continue;
87931d842f5SGeorge Rimar 
88029c5a2a9SRui Ueyama     std::vector<size_t> Ret;
88129c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
88229c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
88329c5a2a9SRui Ueyama     return Ret;
884bbe38602SEugene Leviant   }
88531d842f5SGeorge Rimar   return {};
88631d842f5SGeorge Rimar }
887bbe38602SEugene Leviant 
88829c5a2a9SRui Ueyama template <class ELFT>
88929c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
89029c5a2a9SRui Ueyama   size_t I = 0;
89129c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
89229c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
89329c5a2a9SRui Ueyama       return I;
89429c5a2a9SRui Ueyama     ++I;
89529c5a2a9SRui Ueyama   }
89629c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
89729c5a2a9SRui Ueyama   return 0;
89829c5a2a9SRui Ueyama }
89929c5a2a9SRui Ueyama 
90007320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
901c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
902c3794e58SGeorge Rimar 
903f7c5fbb1SRui Ueyama public:
90407320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
905f23b2320SGeorge Rimar 
90620b6598cSGeorge Rimar   void readLinkerScript();
90720b6598cSGeorge Rimar   void readVersionScript();
908f7c5fbb1SRui Ueyama 
909f7c5fbb1SRui Ueyama private:
91052a1509eSRui Ueyama   void addFile(StringRef Path);
91152a1509eSRui Ueyama 
912f7c5fbb1SRui Ueyama   void readAsNeeded();
91390c5099eSDenis Protivensky   void readEntry();
91483f406cfSGeorge Rimar   void readExtern();
915f7c5fbb1SRui Ueyama   void readGroup();
91631aa1f83SRui Ueyama   void readInclude();
917ee59282bSRui Ueyama   void readOutput();
9189159ce93SDavide Italiano   void readOutputArch();
919f7c5fbb1SRui Ueyama   void readOutputFormat();
920bbe38602SEugene Leviant   void readPhdrs();
92168a39a65SDavide Italiano   void readSearchDir();
9228e3b38abSDenis Protivensky   void readSections();
92395769b4aSRui Ueyama   void readVersion();
92495769b4aSRui Ueyama   void readVersionScriptCommand();
9258e3b38abSDenis Protivensky 
926113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
927e38cbab5SGeorge Rimar   BytesDataCommand *readBytesDataCommand(StringRef Tok);
928ff1f29e0SGeorge Rimar   std::vector<uint8_t> readFill();
92910416564SRui Ueyama   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
930ff1f29e0SGeorge Rimar   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
931bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
932a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionDescription(StringRef Tok);
933c91930a1SGeorge Rimar   Regex readFilePatterns();
93407171f21SGeorge Rimar   std::vector<SectionPattern> readInputSectionsList();
935a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
936bbe38602SEugene Leviant   unsigned readPhdrType();
937be394db3SGeorge Rimar   SortSectionPolicy readSortKind();
938a35e39caSPetr Hosek   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
939db741e72SEugene Leviant   SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
94003fc010eSGeorge Rimar   void readSort();
941eefa758eSGeorge Rimar   Expr readAssert();
942708019c4SRui Ueyama 
943708019c4SRui Ueyama   Expr readExpr();
944708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
945b71d6f7aSEugene Leviant   StringRef readParenLiteral();
946708019c4SRui Ueyama   Expr readPrimary();
947708019c4SRui Ueyama   Expr readTernary(Expr Cond);
9486ad7dfccSRui Ueyama   Expr readParenExpr();
949f7c5fbb1SRui Ueyama 
95020b6598cSGeorge Rimar   // For parsing version script.
95120b6598cSGeorge Rimar   void readExtern(std::vector<SymbolVersion> *Globals);
95295769b4aSRui Ueyama   void readVersionDeclaration(StringRef VerStr);
95320b6598cSGeorge Rimar   void readGlobal(StringRef VerStr);
95420b6598cSGeorge Rimar   void readLocal();
95520b6598cSGeorge Rimar 
95607320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
95707320e40SRui Ueyama   StringSaver Saver = {ScriptConfig->Alloc};
95816b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
959f7c5fbb1SRui Ueyama };
960f7c5fbb1SRui Ueyama 
96120b6598cSGeorge Rimar void ScriptParser::readVersionScript() {
96295769b4aSRui Ueyama   readVersionScriptCommand();
96320b6598cSGeorge Rimar   if (!atEOF())
96495769b4aSRui Ueyama     setError("EOF expected, but got " + next());
96595769b4aSRui Ueyama }
96695769b4aSRui Ueyama 
96795769b4aSRui Ueyama void ScriptParser::readVersionScriptCommand() {
96883043f23SRui Ueyama   if (consume("{")) {
96995769b4aSRui Ueyama     readVersionDeclaration("");
97020b6598cSGeorge Rimar     return;
97120b6598cSGeorge Rimar   }
97220b6598cSGeorge Rimar 
97395769b4aSRui Ueyama   while (!atEOF() && !Error && peek() != "}") {
97420b6598cSGeorge Rimar     StringRef VerStr = next();
97520b6598cSGeorge Rimar     if (VerStr == "{") {
97695769b4aSRui Ueyama       setError("anonymous version definition is used in "
97795769b4aSRui Ueyama                "combination with other version definitions");
97820b6598cSGeorge Rimar       return;
97920b6598cSGeorge Rimar     }
98020b6598cSGeorge Rimar     expect("{");
98195769b4aSRui Ueyama     readVersionDeclaration(VerStr);
98220b6598cSGeorge Rimar   }
98320b6598cSGeorge Rimar }
98420b6598cSGeorge Rimar 
98595769b4aSRui Ueyama void ScriptParser::readVersion() {
98695769b4aSRui Ueyama   expect("{");
98795769b4aSRui Ueyama   readVersionScriptCommand();
98895769b4aSRui Ueyama   expect("}");
98995769b4aSRui Ueyama }
99095769b4aSRui Ueyama 
99120b6598cSGeorge Rimar void ScriptParser::readLinkerScript() {
992f7c5fbb1SRui Ueyama   while (!atEOF()) {
993f7c5fbb1SRui Ueyama     StringRef Tok = next();
994a27eeccaSRui Ueyama     if (Tok == ";")
995a27eeccaSRui Ueyama       continue;
996a27eeccaSRui Ueyama 
99720d03194SEugene Leviant     if (Tok == "ASSERT") {
99820d03194SEugene Leviant       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
99920d03194SEugene Leviant     } else if (Tok == "ENTRY") {
1000a27eeccaSRui Ueyama       readEntry();
1001a27eeccaSRui Ueyama     } else if (Tok == "EXTERN") {
1002a27eeccaSRui Ueyama       readExtern();
1003a27eeccaSRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
1004a27eeccaSRui Ueyama       readGroup();
1005a27eeccaSRui Ueyama     } else if (Tok == "INCLUDE") {
1006a27eeccaSRui Ueyama       readInclude();
1007a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT") {
1008a27eeccaSRui Ueyama       readOutput();
1009a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
1010a27eeccaSRui Ueyama       readOutputArch();
1011a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
1012a27eeccaSRui Ueyama       readOutputFormat();
1013a27eeccaSRui Ueyama     } else if (Tok == "PHDRS") {
1014a27eeccaSRui Ueyama       readPhdrs();
1015a27eeccaSRui Ueyama     } else if (Tok == "SEARCH_DIR") {
1016a27eeccaSRui Ueyama       readSearchDir();
1017a27eeccaSRui Ueyama     } else if (Tok == "SECTIONS") {
1018a27eeccaSRui Ueyama       readSections();
1019a27eeccaSRui Ueyama     } else if (Tok == "VERSION") {
1020a27eeccaSRui Ueyama       readVersion();
1021db741e72SEugene Leviant     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
10220df80befSPetr Hosek       Opt.Commands.emplace_back(Cmd);
1023e5d3ca50SPetr Hosek     } else {
10245761042dSGeorge Rimar       setError("unknown directive: " + Tok);
1025f7c5fbb1SRui Ueyama     }
1026f7c5fbb1SRui Ueyama   }
1027e5d3ca50SPetr Hosek }
1028f7c5fbb1SRui Ueyama 
1029717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
103016b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
10315af1687fSJustin Bogner     SmallString<128> PathData;
10325af1687fSJustin Bogner     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
103316b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
10345af1687fSJustin Bogner       Driver->addFile(Saver.save(Path));
103516b0cc9eSSimon Atanasyan       return;
103616b0cc9eSSimon Atanasyan     }
103716b0cc9eSSimon Atanasyan   }
103816b0cc9eSSimon Atanasyan 
1039f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
104052a1509eSRui Ueyama     Driver->addFile(S);
104152a1509eSRui Ueyama   } else if (S.startswith("=")) {
104252a1509eSRui Ueyama     if (Config->Sysroot.empty())
104352a1509eSRui Ueyama       Driver->addFile(S.substr(1));
104452a1509eSRui Ueyama     else
104552a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
104652a1509eSRui Ueyama   } else if (S.startswith("-l")) {
104721eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
1048a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
1049a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
105052a1509eSRui Ueyama   } else {
105152a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
105252a1509eSRui Ueyama     if (Path.empty())
1053777f9630SGeorge Rimar       setError("unable to find " + S);
1054025d59b1SRui Ueyama     else
105552a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
105652a1509eSRui Ueyama   }
105752a1509eSRui Ueyama }
105852a1509eSRui Ueyama 
1059717677afSRui Ueyama void ScriptParser::readAsNeeded() {
1060f7c5fbb1SRui Ueyama   expect("(");
106135da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
106235da9b6eSRui Ueyama   Config->AsNeeded = true;
106383043f23SRui Ueyama   while (!Error && !consume(")"))
1064cd574a5eSGeorge Rimar     addFile(unquote(next()));
106535da9b6eSRui Ueyama   Config->AsNeeded = Orig;
1066f7c5fbb1SRui Ueyama }
1067f7c5fbb1SRui Ueyama 
1068717677afSRui Ueyama void ScriptParser::readEntry() {
106990c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
107090c5099eSDenis Protivensky   expect("(");
107190c5099eSDenis Protivensky   StringRef Tok = next();
107290c5099eSDenis Protivensky   if (Config->Entry.empty())
107390c5099eSDenis Protivensky     Config->Entry = Tok;
107490c5099eSDenis Protivensky   expect(")");
107590c5099eSDenis Protivensky }
107690c5099eSDenis Protivensky 
1077717677afSRui Ueyama void ScriptParser::readExtern() {
107883f406cfSGeorge Rimar   expect("(");
107983043f23SRui Ueyama   while (!Error && !consume(")"))
1080a2acc931SRui Ueyama     Config->Undefined.push_back(next());
108183f406cfSGeorge Rimar }
108283f406cfSGeorge Rimar 
1083717677afSRui Ueyama void ScriptParser::readGroup() {
1084f7c5fbb1SRui Ueyama   expect("(");
108583043f23SRui Ueyama   while (!Error && !consume(")")) {
1086f7c5fbb1SRui Ueyama     StringRef Tok = next();
1087a2acc931SRui Ueyama     if (Tok == "AS_NEEDED")
1088f7c5fbb1SRui Ueyama       readAsNeeded();
1089a2acc931SRui Ueyama     else
1090cd574a5eSGeorge Rimar       addFile(unquote(Tok));
1091f7c5fbb1SRui Ueyama   }
1092f7c5fbb1SRui Ueyama }
1093f7c5fbb1SRui Ueyama 
1094717677afSRui Ueyama void ScriptParser::readInclude() {
109531aa1f83SRui Ueyama   StringRef Tok = next();
1096cd574a5eSGeorge Rimar   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
1097025d59b1SRui Ueyama   if (!MBOrErr) {
10985761042dSGeorge Rimar     setError("cannot open " + Tok);
1099025d59b1SRui Ueyama     return;
1100025d59b1SRui Ueyama   }
110131aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
1102a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1103a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
110431aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
110531aa1f83SRui Ueyama }
110631aa1f83SRui Ueyama 
1107717677afSRui Ueyama void ScriptParser::readOutput() {
1108ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
1109ee59282bSRui Ueyama   expect("(");
1110ee59282bSRui Ueyama   StringRef Tok = next();
1111ee59282bSRui Ueyama   if (Config->OutputFile.empty())
1112cd574a5eSGeorge Rimar     Config->OutputFile = unquote(Tok);
1113ee59282bSRui Ueyama   expect(")");
1114ee59282bSRui Ueyama }
1115ee59282bSRui Ueyama 
1116717677afSRui Ueyama void ScriptParser::readOutputArch() {
11179159ce93SDavide Italiano   // Error checking only for now.
11189159ce93SDavide Italiano   expect("(");
11195424e7c7SJustin Bogner   skip();
11209159ce93SDavide Italiano   expect(")");
11219159ce93SDavide Italiano }
11229159ce93SDavide Italiano 
1123717677afSRui Ueyama void ScriptParser::readOutputFormat() {
1124f7c5fbb1SRui Ueyama   // Error checking only for now.
1125f7c5fbb1SRui Ueyama   expect("(");
11265424e7c7SJustin Bogner   skip();
11276836c618SDavide Italiano   StringRef Tok = next();
11286836c618SDavide Italiano   if (Tok == ")")
11296836c618SDavide Italiano     return;
1130025d59b1SRui Ueyama   if (Tok != ",") {
11315761042dSGeorge Rimar     setError("unexpected token: " + Tok);
1132025d59b1SRui Ueyama     return;
1133025d59b1SRui Ueyama   }
11345424e7c7SJustin Bogner   skip();
11356836c618SDavide Italiano   expect(",");
11365424e7c7SJustin Bogner   skip();
1137f7c5fbb1SRui Ueyama   expect(")");
1138f7c5fbb1SRui Ueyama }
1139f7c5fbb1SRui Ueyama 
1140bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
1141bbe38602SEugene Leviant   expect("{");
114283043f23SRui Ueyama   while (!Error && !consume("}")) {
1143bbe38602SEugene Leviant     StringRef Tok = next();
114456b21c86SEugene Leviant     Opt.PhdrsCommands.push_back(
114556b21c86SEugene Leviant         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1146bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1147bbe38602SEugene Leviant 
1148bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
1149bbe38602SEugene Leviant     do {
1150bbe38602SEugene Leviant       Tok = next();
1151bbe38602SEugene Leviant       if (Tok == ";")
1152bbe38602SEugene Leviant         break;
1153bbe38602SEugene Leviant       if (Tok == "FILEHDR")
1154bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
1155bbe38602SEugene Leviant       else if (Tok == "PHDRS")
1156bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
115756b21c86SEugene Leviant       else if (Tok == "AT")
115856b21c86SEugene Leviant         PhdrCmd.LMAExpr = readParenExpr();
1159865bf863SEugene Leviant       else if (Tok == "FLAGS") {
1160865bf863SEugene Leviant         expect("(");
1161eb685cd7SRafael Espindola         // Passing 0 for the value of dot is a bit of a hack. It means that
1162eb685cd7SRafael Espindola         // we accept expressions like ".|1".
1163eb685cd7SRafael Espindola         PhdrCmd.Flags = readExpr()(0);
1164865bf863SEugene Leviant         expect(")");
1165865bf863SEugene Leviant       } else
1166bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
1167bbe38602SEugene Leviant     } while (!Error);
1168bbe38602SEugene Leviant   }
1169bbe38602SEugene Leviant }
1170bbe38602SEugene Leviant 
1171717677afSRui Ueyama void ScriptParser::readSearchDir() {
117268a39a65SDavide Italiano   expect("(");
117386c5fb82SRui Ueyama   StringRef Tok = next();
11746c7ad13fSRui Ueyama   if (!Config->Nostdlib)
1175cd574a5eSGeorge Rimar     Config->SearchPaths.push_back(unquote(Tok));
117668a39a65SDavide Italiano   expect(")");
117768a39a65SDavide Italiano }
117868a39a65SDavide Italiano 
1179717677afSRui Ueyama void ScriptParser::readSections() {
1180e05336ffSEugene Leviant   Opt.HasSections = true;
11818e3b38abSDenis Protivensky   expect("{");
118283043f23SRui Ueyama   while (!Error && !consume("}")) {
1183113cdec9SRui Ueyama     StringRef Tok = next();
1184db741e72SEugene Leviant     BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
1185ceabe80eSEugene Leviant     if (!Cmd) {
1186ceabe80eSEugene Leviant       if (Tok == "ASSERT")
1187eefa758eSGeorge Rimar         Cmd = new AssertCommand(readAssert());
1188ceabe80eSEugene Leviant       else
118910416564SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
11908e3b38abSDenis Protivensky     }
119110416564SRui Ueyama     Opt.Commands.emplace_back(Cmd);
1192652852c5SGeorge Rimar   }
1193708019c4SRui Ueyama }
11948e3b38abSDenis Protivensky 
1195708019c4SRui Ueyama static int precedence(StringRef Op) {
1196708019c4SRui Ueyama   return StringSwitch<int>(Op)
11970120e3f2SRui Ueyama       .Cases("*", "/", 5)
11980120e3f2SRui Ueyama       .Cases("+", "-", 4)
11990120e3f2SRui Ueyama       .Cases("<<", ">>", 3)
12009c4ac5f2SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
12010120e3f2SRui Ueyama       .Cases("&", "|", 1)
1202708019c4SRui Ueyama       .Default(-1);
1203708019c4SRui Ueyama }
1204708019c4SRui Ueyama 
1205c91930a1SGeorge Rimar Regex ScriptParser::readFilePatterns() {
120610416564SRui Ueyama   std::vector<StringRef> V;
120783043f23SRui Ueyama   while (!Error && !consume(")"))
120810416564SRui Ueyama     V.push_back(next());
1209c91930a1SGeorge Rimar   return compileGlobPatterns(V);
12100702c4e8SGeorge Rimar }
12110702c4e8SGeorge Rimar 
1212be394db3SGeorge Rimar SortSectionPolicy ScriptParser::readSortKind() {
121383043f23SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
1214be394db3SGeorge Rimar     return SortSectionPolicy::Name;
121583043f23SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
1216be394db3SGeorge Rimar     return SortSectionPolicy::Alignment;
121783043f23SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
1218be394db3SGeorge Rimar     return SortSectionPolicy::Priority;
121983043f23SRui Ueyama   if (consume("SORT_NONE"))
1220be394db3SGeorge Rimar     return SortSectionPolicy::None;
1221b2a0abdfSRui Ueyama   return SortSectionPolicy::Default;
1222be394db3SGeorge Rimar }
1223be394db3SGeorge Rimar 
1224395281cfSGeorge Rimar // Method reads a list of sequence of excluded files and section globs given in
1225395281cfSGeorge Rimar // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1226395281cfSGeorge Rimar // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1227af03be19SGeorge Rimar // The semantics of that is next:
1228af03be19SGeorge Rimar // * Include .foo.1 from every file.
1229af03be19SGeorge Rimar // * Include .foo.2 from every file but a.o
1230af03be19SGeorge Rimar // * Include .foo.3 from every file but b.o
123107171f21SGeorge Rimar std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
123207171f21SGeorge Rimar   std::vector<SectionPattern> Ret;
1233601e9898SGeorge Rimar   while (!Error && peek() != ")") {
1234027a9e87SRui Ueyama     Regex ExcludeFileRe;
123583043f23SRui Ueyama     if (consume("EXCLUDE_FILE")) {
1236395281cfSGeorge Rimar       expect("(");
1237395281cfSGeorge Rimar       ExcludeFileRe = readFilePatterns();
1238395281cfSGeorge Rimar     }
1239395281cfSGeorge Rimar 
1240601e9898SGeorge Rimar     std::vector<StringRef> V;
1241601e9898SGeorge Rimar     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1242395281cfSGeorge Rimar       V.push_back(next());
1243601e9898SGeorge Rimar 
1244601e9898SGeorge Rimar     if (!V.empty())
124507171f21SGeorge Rimar       Ret.push_back({std::move(ExcludeFileRe), compileGlobPatterns(V)});
1246601e9898SGeorge Rimar     else
1247601e9898SGeorge Rimar       setError("section pattern is expected");
1248395281cfSGeorge Rimar   }
124907171f21SGeorge Rimar   return Ret;
1250395281cfSGeorge Rimar }
1251395281cfSGeorge Rimar 
125207171f21SGeorge Rimar // Section pattern grammar can have complex expressions, for example:
125307171f21SGeorge Rimar // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
125407171f21SGeorge Rimar // Generally is a sequence of globs and excludes that may be wrapped in a SORT()
125507171f21SGeorge Rimar // commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
125607171f21SGeorge Rimar // This methods handles wrapping sequences of excluded files and section globs
125707171f21SGeorge Rimar // into SORT() if that needed and reads them all.
1258a2496cbeSGeorge Rimar InputSectionDescription *
1259a2496cbeSGeorge Rimar ScriptParser::readInputSectionRules(StringRef FilePattern) {
1260c91930a1SGeorge Rimar   auto *Cmd = new InputSectionDescription(FilePattern);
12610ed42b0cSDavide Italiano   expect("(");
126283043f23SRui Ueyama   while (!HasError && !consume(")")) {
126307171f21SGeorge Rimar     SortSectionPolicy Outer = readSortKind();
126407171f21SGeorge Rimar     SortSectionPolicy Inner = SortSectionPolicy::Default;
126507171f21SGeorge Rimar     std::vector<SectionPattern> V;
126607171f21SGeorge Rimar     if (Outer != SortSectionPolicy::Default) {
12670702c4e8SGeorge Rimar       expect("(");
126807171f21SGeorge Rimar       Inner = readSortKind();
126907171f21SGeorge Rimar       if (Inner != SortSectionPolicy::Default) {
1270350ece4eSGeorge Rimar         expect("(");
127107171f21SGeorge Rimar         V = readInputSectionsList();
12720702c4e8SGeorge Rimar         expect(")");
1273350ece4eSGeorge Rimar       } else {
127407171f21SGeorge Rimar         V = readInputSectionsList();
1275350ece4eSGeorge Rimar       }
1276350ece4eSGeorge Rimar       expect(")");
127707171f21SGeorge Rimar     } else {
127807171f21SGeorge Rimar       V = readInputSectionsList();
12790659800eSGeorge Rimar     }
12800702c4e8SGeorge Rimar 
128107171f21SGeorge Rimar     for (SectionPattern &Pat : V) {
128207171f21SGeorge Rimar       Pat.SortInner = Inner;
128307171f21SGeorge Rimar       Pat.SortOuter = Outer;
128407171f21SGeorge Rimar     }
128507171f21SGeorge Rimar 
128607171f21SGeorge Rimar     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
128707171f21SGeorge Rimar   }
128810416564SRui Ueyama   return Cmd;
12890659800eSGeorge Rimar }
12900659800eSGeorge Rimar 
1291a2496cbeSGeorge Rimar InputSectionDescription *
1292a2496cbeSGeorge Rimar ScriptParser::readInputSectionDescription(StringRef Tok) {
12930659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
12940659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1295a2496cbeSGeorge Rimar   if (Tok == "KEEP") {
1296e7282797SDavide Italiano     expect("(");
1297a2496cbeSGeorge Rimar     StringRef FilePattern = next();
1298a2496cbeSGeorge Rimar     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
12990ed42b0cSDavide Italiano     expect(")");
1300cf43f179SEugene Leviant     Opt.KeptSections.push_back(Cmd);
130110416564SRui Ueyama     return Cmd;
130210416564SRui Ueyama   }
1303a2496cbeSGeorge Rimar   return readInputSectionRules(Tok);
13040659800eSGeorge Rimar }
13050659800eSGeorge Rimar 
130603fc010eSGeorge Rimar void ScriptParser::readSort() {
130703fc010eSGeorge Rimar   expect("(");
130803fc010eSGeorge Rimar   expect("CONSTRUCTORS");
130903fc010eSGeorge Rimar   expect(")");
131003fc010eSGeorge Rimar }
131103fc010eSGeorge Rimar 
1312eefa758eSGeorge Rimar Expr ScriptParser::readAssert() {
1313eefa758eSGeorge Rimar   expect("(");
1314eefa758eSGeorge Rimar   Expr E = readExpr();
1315eefa758eSGeorge Rimar   expect(",");
1316cd574a5eSGeorge Rimar   StringRef Msg = unquote(next());
1317eefa758eSGeorge Rimar   expect(")");
1318eefa758eSGeorge Rimar   return [=](uint64_t Dot) {
1319eefa758eSGeorge Rimar     uint64_t V = E(Dot);
1320eefa758eSGeorge Rimar     if (!V)
1321eefa758eSGeorge Rimar       error(Msg);
1322eefa758eSGeorge Rimar     return V;
1323eefa758eSGeorge Rimar   };
1324eefa758eSGeorge Rimar }
1325eefa758eSGeorge Rimar 
132625150e8bSRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
132725150e8bSRui Ueyama // alias for =fillexp section attribute, which is different from
132825150e8bSRui Ueyama // what GNU linkers do.
132925150e8bSRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1330ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readFill() {
1331ff1f29e0SGeorge Rimar   expect("(");
1332ff1f29e0SGeorge Rimar   std::vector<uint8_t> V = readOutputSectionFiller(next());
1333ff1f29e0SGeorge Rimar   expect(")");
1334ff1f29e0SGeorge Rimar   expect(";");
1335ff1f29e0SGeorge Rimar   return V;
1336ff1f29e0SGeorge Rimar }
1337ff1f29e0SGeorge Rimar 
133810416564SRui Ueyama OutputSectionCommand *
133910416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1340076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
134158e5c4dcSGeorge Rimar 
134258e5c4dcSGeorge Rimar   // Read an address expression.
134358e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
134458e5c4dcSGeorge Rimar   if (peek() != ":")
134558e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
134658e5c4dcSGeorge Rimar 
13478e3b38abSDenis Protivensky   expect(":");
1348246f681eSDavide Italiano 
134983043f23SRui Ueyama   if (consume("AT"))
1350b71d6f7aSEugene Leviant     Cmd->LMAExpr = readParenExpr();
135183043f23SRui Ueyama   if (consume("ALIGN"))
13526ad7dfccSRui Ueyama     Cmd->AlignExpr = readParenExpr();
135383043f23SRui Ueyama   if (consume("SUBALIGN"))
1354db24d9c3SGeorge Rimar     Cmd->SubalignExpr = readParenExpr();
1355630c6179SGeorge Rimar 
1356246f681eSDavide Italiano   // Parse constraints.
135783043f23SRui Ueyama   if (consume("ONLY_IF_RO"))
1358efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
135983043f23SRui Ueyama   if (consume("ONLY_IF_RW"))
1360efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
13618e3b38abSDenis Protivensky   expect("{");
13628ec77e64SRui Ueyama 
136383043f23SRui Ueyama   while (!Error && !consume("}")) {
1364ceabe80eSEugene Leviant     StringRef Tok = next();
1365db741e72SEugene Leviant     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
1366ceabe80eSEugene Leviant       Cmd->Commands.emplace_back(Assignment);
1367e38cbab5SGeorge Rimar     else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1368e38cbab5SGeorge Rimar       Cmd->Commands.emplace_back(Data);
1369ff1f29e0SGeorge Rimar     else if (Tok == "FILL")
1370ff1f29e0SGeorge Rimar       Cmd->Filler = readFill();
1371ceabe80eSEugene Leviant     else if (Tok == "SORT")
137203fc010eSGeorge Rimar       readSort();
1373a2496cbeSGeorge Rimar     else if (peek() == "(")
1374a2496cbeSGeorge Rimar       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1375ceabe80eSEugene Leviant     else
1376ceabe80eSEugene Leviant       setError("unknown command " + Tok);
13778e3b38abSDenis Protivensky   }
1378076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
13794ebc5620SGeorge Rimar 
138083043f23SRui Ueyama   if (consume("="))
13814ebc5620SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next());
13824ebc5620SGeorge Rimar   else if (peek().startswith("="))
1383ff1f29e0SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next().drop_front());
13844ebc5620SGeorge Rimar 
138510416564SRui Ueyama   return Cmd;
1386f71caa2bSRui Ueyama }
13878ec77e64SRui Ueyama 
13882c8f1f04SRui Ueyama // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
13892c8f1f04SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
13902c8f1f04SRui Ueyama //
13912c8f1f04SRui Ueyama // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
13922c8f1f04SRui Ueyama // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
13932c8f1f04SRui Ueyama // as 32-bit big-endian values. We will do the same as ld.gold does
13942c8f1f04SRui Ueyama // because it's simpler than what ld.bfd does.
1395ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1396965827d6SRui Ueyama   uint32_t V;
1397ff1f29e0SGeorge Rimar   if (Tok.getAsInteger(0, V)) {
1398965827d6SRui Ueyama     setError("invalid filler expression: " + Tok);
1399f71caa2bSRui Ueyama     return {};
1400e2ee72b5SGeorge Rimar   }
1401965827d6SRui Ueyama   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
14028e3b38abSDenis Protivensky }
14038e3b38abSDenis Protivensky 
1404a35e39caSPetr Hosek SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1405a31c91b1SEugene Leviant   expect("(");
1406174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
1407a35e39caSPetr Hosek   Cmd->Provide = Provide;
1408174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
1409a31c91b1SEugene Leviant   expect(")");
1410a31c91b1SEugene Leviant   expect(";");
141110416564SRui Ueyama   return Cmd;
1412eda81a1bSEugene Leviant }
1413eda81a1bSEugene Leviant 
1414db741e72SEugene Leviant SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1415db741e72SEugene Leviant                                                         bool MakeAbsolute) {
1416ceabe80eSEugene Leviant   SymbolAssignment *Cmd = nullptr;
1417ceabe80eSEugene Leviant   if (peek() == "=" || peek() == "+=") {
1418ceabe80eSEugene Leviant     Cmd = readAssignment(Tok);
1419ceabe80eSEugene Leviant     expect(";");
1420ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE") {
1421a35e39caSPetr Hosek     Cmd = readProvideHidden(true, false);
1422a35e39caSPetr Hosek   } else if (Tok == "HIDDEN") {
1423a35e39caSPetr Hosek     Cmd = readProvideHidden(false, true);
1424ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE_HIDDEN") {
1425a35e39caSPetr Hosek     Cmd = readProvideHidden(true, true);
1426ceabe80eSEugene Leviant   }
1427db741e72SEugene Leviant   if (Cmd && MakeAbsolute)
1428db741e72SEugene Leviant     Cmd->IsAbsolute = true;
1429ceabe80eSEugene Leviant   return Cmd;
1430ceabe80eSEugene Leviant }
1431ceabe80eSEugene Leviant 
143230835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
143330835ea4SGeorge Rimar   if (S == ".")
143430835ea4SGeorge Rimar     return Dot;
1435884e786dSGeorge Rimar   return ScriptBase->getSymbolValue(S);
1436e32a3598SGeorge Rimar }
1437e32a3598SGeorge Rimar 
143830835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
143930835ea4SGeorge Rimar   StringRef Op = next();
1440db741e72SEugene Leviant   bool IsAbsolute = false;
1441db741e72SEugene Leviant   Expr E;
144230835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
144383043f23SRui Ueyama   if (consume("ABSOLUTE")) {
14447c1381a0SRui Ueyama     // The RHS may be something like "ABSOLUTE(.) & 0xff".
14457c1381a0SRui Ueyama     // Call readExpr1 to read the whole expression.
14467c1381a0SRui Ueyama     E = readExpr1(readParenExpr(), 0);
1447db741e72SEugene Leviant     IsAbsolute = true;
1448db741e72SEugene Leviant   } else {
1449db741e72SEugene Leviant     E = readExpr();
1450db741e72SEugene Leviant   }
145130835ea4SGeorge Rimar   if (Op == "+=")
145230835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1453db741e72SEugene Leviant   return new SymbolAssignment(Name, E, IsAbsolute);
145430835ea4SGeorge Rimar }
145530835ea4SGeorge Rimar 
145630835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
145730835ea4SGeorge Rimar // script expression.
145830835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
145930835ea4SGeorge Rimar 
146036c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
146136c1cd23SRui Ueyama   if (Op == "*")
146236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
146336c1cd23SRui Ueyama   if (Op == "/") {
146436c1cd23SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
146536c1cd23SRui Ueyama       uint64_t RHS = R(Dot);
146636c1cd23SRui Ueyama       if (RHS == 0) {
146736c1cd23SRui Ueyama         error("division by zero");
146836c1cd23SRui Ueyama         return 0;
146936c1cd23SRui Ueyama       }
147036c1cd23SRui Ueyama       return L(Dot) / RHS;
147136c1cd23SRui Ueyama     };
147236c1cd23SRui Ueyama   }
147336c1cd23SRui Ueyama   if (Op == "+")
147436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
147536c1cd23SRui Ueyama   if (Op == "-")
147636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1477c8ccd1f1SGeorge Rimar   if (Op == "<<")
1478c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1479c8ccd1f1SGeorge Rimar   if (Op == ">>")
1480c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
148136c1cd23SRui Ueyama   if (Op == "<")
148236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
148336c1cd23SRui Ueyama   if (Op == ">")
148436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
148536c1cd23SRui Ueyama   if (Op == ">=")
148636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
148736c1cd23SRui Ueyama   if (Op == "<=")
148836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
148936c1cd23SRui Ueyama   if (Op == "==")
149036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
149136c1cd23SRui Ueyama   if (Op == "!=")
149236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
149336c1cd23SRui Ueyama   if (Op == "&")
149436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1495cc3dd629SRafael Espindola   if (Op == "|")
1496cc3dd629SRafael Espindola     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
149736c1cd23SRui Ueyama   llvm_unreachable("invalid operator");
149836c1cd23SRui Ueyama }
149936c1cd23SRui Ueyama 
1500708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
1501708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
1502708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1503708019c4SRui Ueyama   while (!atEOF() && !Error) {
1504708019c4SRui Ueyama     // Read an operator and an expression.
1505708019c4SRui Ueyama     StringRef Op1 = peek();
1506708019c4SRui Ueyama     if (Op1 == "?")
1507708019c4SRui Ueyama       return readTernary(Lhs);
1508708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
1509a31c91b1SEugene Leviant       break;
15105424e7c7SJustin Bogner     skip();
1511708019c4SRui Ueyama     Expr Rhs = readPrimary();
1512708019c4SRui Ueyama 
1513708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
1514708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
1515708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
1516708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
1517708019c4SRui Ueyama     while (!atEOF()) {
1518708019c4SRui Ueyama       StringRef Op2 = peek();
1519708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
1520eda81a1bSEugene Leviant         break;
1521708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
1522eda81a1bSEugene Leviant     }
1523708019c4SRui Ueyama 
1524708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
1525708019c4SRui Ueyama   }
1526708019c4SRui Ueyama   return Lhs;
1527708019c4SRui Ueyama }
1528708019c4SRui Ueyama 
1529708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
1530e2cc07bcSMichael J. Spencer   if (S == "COMMONPAGESIZE")
1531708019c4SRui Ueyama     return Target->PageSize;
1532e2cc07bcSMichael J. Spencer   if (S == "MAXPAGESIZE")
1533997f8838SPetr Hosek     return Config->MaxPageSize;
1534708019c4SRui Ueyama   error("unknown constant: " + S);
1535708019c4SRui Ueyama   return 0;
1536708019c4SRui Ueyama }
1537708019c4SRui Ueyama 
1538626e0b08SRui Ueyama // Parses Tok as an integer. Returns true if successful.
1539626e0b08SRui Ueyama // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1540626e0b08SRui Ueyama // and decimal numbers. Decimal numbers may have "K" (kilo) or
1541626e0b08SRui Ueyama // "M" (mega) prefixes.
15429f2f7ad9SGeorge Rimar static bool readInteger(StringRef Tok, uint64_t &Result) {
1543eaeafb2bSSimon Atanasyan   if (Tok.startswith("-")) {
1544eaeafb2bSSimon Atanasyan     if (!readInteger(Tok.substr(1), Result))
1545eaeafb2bSSimon Atanasyan       return false;
1546eaeafb2bSSimon Atanasyan     Result = -Result;
1547eaeafb2bSSimon Atanasyan     return true;
1548eaeafb2bSSimon Atanasyan   }
15499f2f7ad9SGeorge Rimar   if (Tok.startswith_lower("0x"))
15509f2f7ad9SGeorge Rimar     return !Tok.substr(2).getAsInteger(16, Result);
15519f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("H"))
15529f2f7ad9SGeorge Rimar     return !Tok.drop_back().getAsInteger(16, Result);
15539f2f7ad9SGeorge Rimar 
15549f2f7ad9SGeorge Rimar   int Suffix = 1;
15559f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("K")) {
15569f2f7ad9SGeorge Rimar     Suffix = 1024;
15579f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
15589f2f7ad9SGeorge Rimar   } else if (Tok.endswith_lower("M")) {
15599f2f7ad9SGeorge Rimar     Suffix = 1024 * 1024;
15609f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
15619f2f7ad9SGeorge Rimar   }
15629f2f7ad9SGeorge Rimar   if (Tok.getAsInteger(10, Result))
15639f2f7ad9SGeorge Rimar     return false;
15649f2f7ad9SGeorge Rimar   Result *= Suffix;
15659f2f7ad9SGeorge Rimar   return true;
15669f2f7ad9SGeorge Rimar }
15679f2f7ad9SGeorge Rimar 
1568e38cbab5SGeorge Rimar BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1569e38cbab5SGeorge Rimar   int Size = StringSwitch<unsigned>(Tok)
1570e38cbab5SGeorge Rimar                  .Case("BYTE", 1)
1571e38cbab5SGeorge Rimar                  .Case("SHORT", 2)
1572e38cbab5SGeorge Rimar                  .Case("LONG", 4)
1573e38cbab5SGeorge Rimar                  .Case("QUAD", 8)
1574e38cbab5SGeorge Rimar                  .Default(-1);
1575e38cbab5SGeorge Rimar   if (Size == -1)
1576e38cbab5SGeorge Rimar     return nullptr;
1577e38cbab5SGeorge Rimar 
1578e38cbab5SGeorge Rimar   expect("(");
1579e38cbab5SGeorge Rimar   uint64_t Val = 0;
1580e38cbab5SGeorge Rimar   StringRef S = next();
1581e38cbab5SGeorge Rimar   if (!readInteger(S, Val))
1582e38cbab5SGeorge Rimar     setError("unexpected value: " + S);
1583e38cbab5SGeorge Rimar   expect(")");
1584e38cbab5SGeorge Rimar   return new BytesDataCommand(Val, Size);
1585e38cbab5SGeorge Rimar }
1586e38cbab5SGeorge Rimar 
1587b71d6f7aSEugene Leviant StringRef ScriptParser::readParenLiteral() {
1588b71d6f7aSEugene Leviant   expect("(");
1589b71d6f7aSEugene Leviant   StringRef Tok = next();
1590b71d6f7aSEugene Leviant   expect(")");
1591b71d6f7aSEugene Leviant   return Tok;
1592b71d6f7aSEugene Leviant }
1593b71d6f7aSEugene Leviant 
1594708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
15956ad7dfccSRui Ueyama   if (peek() == "(")
15966ad7dfccSRui Ueyama     return readParenExpr();
1597708019c4SRui Ueyama 
15986ad7dfccSRui Ueyama   StringRef Tok = next();
1599708019c4SRui Ueyama 
1600eaeafb2bSSimon Atanasyan   if (Tok == "~") {
1601eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1602eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return ~E(Dot); };
1603eaeafb2bSSimon Atanasyan   }
1604eaeafb2bSSimon Atanasyan   if (Tok == "-") {
1605eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1606eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return -E(Dot); };
1607eaeafb2bSSimon Atanasyan   }
1608eaeafb2bSSimon Atanasyan 
1609708019c4SRui Ueyama   // Built-in functions are parsed here.
1610708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
161196659df0SGeorge Rimar   if (Tok == "ADDR") {
1612b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1613884e786dSGeorge Rimar     return
1614884e786dSGeorge Rimar         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
161596659df0SGeorge Rimar   }
1616b71d6f7aSEugene Leviant   if (Tok == "LOADADDR") {
1617b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1618b71d6f7aSEugene Leviant     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1619b71d6f7aSEugene Leviant   }
1620eefa758eSGeorge Rimar   if (Tok == "ASSERT")
1621eefa758eSGeorge Rimar     return readAssert();
1622708019c4SRui Ueyama   if (Tok == "ALIGN") {
16236ad7dfccSRui Ueyama     Expr E = readParenExpr();
1624708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1625708019c4SRui Ueyama   }
1626708019c4SRui Ueyama   if (Tok == "CONSTANT") {
1627b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1628b71d6f7aSEugene Leviant     return [=](uint64_t Dot) { return getConstant(Name); };
1629708019c4SRui Ueyama   }
1630f34f45fdSGeorge Rimar   if (Tok == "DEFINED") {
1631f34f45fdSGeorge Rimar     expect("(");
1632f34f45fdSGeorge Rimar     StringRef Tok = next();
1633f34f45fdSGeorge Rimar     expect(")");
1634f2821028SGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
1635f34f45fdSGeorge Rimar   }
163654c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
163754c145ceSRafael Espindola     expect("(");
16385424e7c7SJustin Bogner     skip();
163954c145ceSRafael Espindola     expect(",");
16408c658bf8SGeorge Rimar     Expr E = readExpr();
164154c145ceSRafael Espindola     expect(")");
16428c658bf8SGeorge Rimar     return [=](uint64_t Dot) { return E(Dot); };
164354c145ceSRafael Espindola   }
1644708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
1645708019c4SRui Ueyama     expect("(");
1646708019c4SRui Ueyama     Expr E = readExpr();
1647708019c4SRui Ueyama     expect(",");
1648708019c4SRui Ueyama     readExpr();
1649708019c4SRui Ueyama     expect(")");
1650f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1651708019c4SRui Ueyama   }
1652708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
1653708019c4SRui Ueyama     expect("(");
1654708019c4SRui Ueyama     expect(".");
1655708019c4SRui Ueyama     expect(")");
1656708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
1657708019c4SRui Ueyama   }
1658276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
1659276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1660276b4e64SGeorge Rimar   // the next page boundary for simplicity.
1661276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
1662276b4e64SGeorge Rimar     expect("(");
166397bdc722SRafael Espindola     readExpr();
1664276b4e64SGeorge Rimar     expect(",");
1665276b4e64SGeorge Rimar     readExpr();
1666276b4e64SGeorge Rimar     expect(")");
1667276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1668276b4e64SGeorge Rimar   }
16699e69450eSGeorge Rimar   if (Tok == "SIZEOF") {
1670b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1671884e786dSGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
16729e69450eSGeorge Rimar   }
167336fac7f0SEugene Leviant   if (Tok == "ALIGNOF") {
1674b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
167536fac7f0SEugene Leviant     return
167636fac7f0SEugene Leviant         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
167736fac7f0SEugene Leviant   }
1678e32a3598SGeorge Rimar   if (Tok == "SIZEOF_HEADERS")
1679884e786dSGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1680708019c4SRui Ueyama 
16819f2f7ad9SGeorge Rimar   // Tok is a literal number.
16829f2f7ad9SGeorge Rimar   uint64_t V;
16839f2f7ad9SGeorge Rimar   if (readInteger(Tok, V))
16849f2f7ad9SGeorge Rimar     return [=](uint64_t Dot) { return V; };
16859f2f7ad9SGeorge Rimar 
16869f2f7ad9SGeorge Rimar   // Tok is a symbol name.
168730835ea4SGeorge Rimar   if (Tok != "." && !isValidCIdentifier(Tok))
1688708019c4SRui Ueyama     setError("malformed number: " + Tok);
168930835ea4SGeorge Rimar   return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
1690a9c5a528SGeorge Rimar }
1691708019c4SRui Ueyama 
1692708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
16935424e7c7SJustin Bogner   skip();
1694708019c4SRui Ueyama   Expr L = readExpr();
1695708019c4SRui Ueyama   expect(":");
1696708019c4SRui Ueyama   Expr R = readExpr();
1697708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1698708019c4SRui Ueyama }
1699708019c4SRui Ueyama 
17006ad7dfccSRui Ueyama Expr ScriptParser::readParenExpr() {
17016ad7dfccSRui Ueyama   expect("(");
17026ad7dfccSRui Ueyama   Expr E = readExpr();
17036ad7dfccSRui Ueyama   expect(")");
17046ad7dfccSRui Ueyama   return E;
17056ad7dfccSRui Ueyama }
17066ad7dfccSRui Ueyama 
1707bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1708bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
1709bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
1710bbe38602SEugene Leviant     StringRef Tok = next();
1711bbe38602SEugene Leviant     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1712bbe38602SEugene Leviant     if (Tok.empty()) {
1713bbe38602SEugene Leviant       setError("section header name is empty");
1714bbe38602SEugene Leviant       break;
1715bbe38602SEugene Leviant     }
1716bbe38602SEugene Leviant     Phdrs.push_back(Tok);
1717bbe38602SEugene Leviant   }
1718bbe38602SEugene Leviant   return Phdrs;
1719bbe38602SEugene Leviant }
1720bbe38602SEugene Leviant 
172195dd718cSGeorge Rimar // Read a program header type name. The next token must be a
172295dd718cSGeorge Rimar // name of a program header type or a constant (e.g. "0x3").
1723bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
1724bbe38602SEugene Leviant   StringRef Tok = next();
172595dd718cSGeorge Rimar   uint64_t Val;
172695dd718cSGeorge Rimar   if (readInteger(Tok, Val))
172795dd718cSGeorge Rimar     return Val;
172895dd718cSGeorge Rimar 
1729b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
1730b0f6c590SRui Ueyama                      .Case("PT_NULL", PT_NULL)
1731b0f6c590SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
1732b0f6c590SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1733b0f6c590SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
1734b0f6c590SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
1735b0f6c590SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
1736b0f6c590SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
1737b0f6c590SRui Ueyama                      .Case("PT_TLS", PT_TLS)
1738b0f6c590SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1739b0f6c590SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1740b0f6c590SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1741270173f2SGeorge Rimar                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1742cc6e567cSGeorge Rimar                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1743b0f6c590SRui Ueyama                      .Default(-1);
1744bbe38602SEugene Leviant 
1745b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1746b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1747b0f6c590SRui Ueyama     return PT_NULL;
1748b0f6c590SRui Ueyama   }
1749b0f6c590SRui Ueyama   return Ret;
1750bbe38602SEugene Leviant }
1751bbe38602SEugene Leviant 
175295769b4aSRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
175320b6598cSGeorge Rimar   // Identifiers start at 2 because 0 and 1 are reserved
175420b6598cSGeorge Rimar   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
175520b6598cSGeorge Rimar   size_t VersionId = Config->VersionDefinitions.size() + 2;
175620b6598cSGeorge Rimar   Config->VersionDefinitions.push_back({VerStr, VersionId});
175720b6598cSGeorge Rimar 
175883043f23SRui Ueyama   if (consume("global:") || peek() != "local:")
175920b6598cSGeorge Rimar     readGlobal(VerStr);
176083043f23SRui Ueyama   if (consume("local:"))
176120b6598cSGeorge Rimar     readLocal();
176220b6598cSGeorge Rimar   expect("}");
176320b6598cSGeorge Rimar 
176420b6598cSGeorge Rimar   // Each version may have a parent version. For example, "Ver2" defined as
176520b6598cSGeorge Rimar   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
176620b6598cSGeorge Rimar   // version hierarchy is, probably against your instinct, purely for human; the
176720b6598cSGeorge Rimar   // runtime doesn't care about them at all. In LLD, we simply skip the token.
176820b6598cSGeorge Rimar   if (!VerStr.empty() && peek() != ";")
17695424e7c7SJustin Bogner     skip();
177020b6598cSGeorge Rimar   expect(";");
177120b6598cSGeorge Rimar }
177220b6598cSGeorge Rimar 
177320b6598cSGeorge Rimar void ScriptParser::readLocal() {
177420b6598cSGeorge Rimar   Config->DefaultSymbolVersion = VER_NDX_LOCAL;
177520b6598cSGeorge Rimar   expect("*");
177620b6598cSGeorge Rimar   expect(";");
177720b6598cSGeorge Rimar }
177820b6598cSGeorge Rimar 
177920b6598cSGeorge Rimar void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1780cd574a5eSGeorge Rimar   expect("\"C++\"");
178120b6598cSGeorge Rimar   expect("{");
178220b6598cSGeorge Rimar 
178320b6598cSGeorge Rimar   for (;;) {
178420b6598cSGeorge Rimar     if (peek() == "}" || Error)
178520b6598cSGeorge Rimar       break;
1786cd574a5eSGeorge Rimar     bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1787cd574a5eSGeorge Rimar     Globals->push_back({unquote(next()), true, HasWildcard});
178820b6598cSGeorge Rimar     expect(";");
178920b6598cSGeorge Rimar   }
179020b6598cSGeorge Rimar 
179120b6598cSGeorge Rimar   expect("}");
179220b6598cSGeorge Rimar   expect(";");
179320b6598cSGeorge Rimar }
179420b6598cSGeorge Rimar 
179520b6598cSGeorge Rimar void ScriptParser::readGlobal(StringRef VerStr) {
179620b6598cSGeorge Rimar   std::vector<SymbolVersion> *Globals;
179720b6598cSGeorge Rimar   if (VerStr.empty())
179820b6598cSGeorge Rimar     Globals = &Config->VersionScriptGlobals;
179920b6598cSGeorge Rimar   else
180020b6598cSGeorge Rimar     Globals = &Config->VersionDefinitions.back().Globals;
180120b6598cSGeorge Rimar 
180220b6598cSGeorge Rimar   for (;;) {
180383043f23SRui Ueyama     if (consume("extern"))
180420b6598cSGeorge Rimar       readExtern(Globals);
180520b6598cSGeorge Rimar 
180620b6598cSGeorge Rimar     StringRef Cur = peek();
180720b6598cSGeorge Rimar     if (Cur == "}" || Cur == "local:" || Error)
180820b6598cSGeorge Rimar       return;
18095424e7c7SJustin Bogner     skip();
1810cd574a5eSGeorge Rimar     Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
181120b6598cSGeorge Rimar     expect(";");
181220b6598cSGeorge Rimar   }
181320b6598cSGeorge Rimar }
181420b6598cSGeorge Rimar 
181516b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
181616b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
181716b0cc9eSSimon Atanasyan     return false;
181816b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
181916b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
182016b0cc9eSSimon Atanasyan       return true;
182116b0cc9eSSimon Atanasyan   return false;
182216b0cc9eSSimon Atanasyan }
182316b0cc9eSSimon Atanasyan 
182407320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
182516b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
182620b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
182720b6598cSGeorge Rimar }
182820b6598cSGeorge Rimar 
182920b6598cSGeorge Rimar void elf::readVersionScript(MemoryBufferRef MB) {
183020b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), false).readVersionScript();
1831f7c5fbb1SRui Ueyama }
18321ebc8ed7SRui Ueyama 
183307320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
183407320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
183507320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
183607320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1837