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 
2420b9ce6a4SRui Ueyama   return Ret;
2430b9ce6a4SRui Ueyama }
2440b9ce6a4SRui Ueyama 
245e5d3ca50SPetr Hosek template <class ELFT>
24610897f18SRafael Espindola static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
24710897f18SRafael Espindola                                             StringRef OutsecName) {
24810897f18SRafael Espindola   // When using linker script the merge rules are different.
24910897f18SRafael Espindola   // Unfortunately, linker scripts are name based. This means that expressions
25010897f18SRafael Espindola   // like *(.foo*) can refer to multiple input sections that would normally be
25110897f18SRafael Espindola   // placed in different output sections. We cannot put them in different
25210897f18SRafael Espindola   // output sections or we would produce wrong results for
25310897f18SRafael Espindola   // start = .; *(.foo.*) end = .; *(.bar)
25410897f18SRafael Espindola   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
25510897f18SRafael Espindola   // another. The problem is that there is no way to layout those output
25610897f18SRafael Espindola   // sections such that the .foo sections are the only thing between the
25710897f18SRafael Espindola   // start and end symbols.
25810897f18SRafael Espindola 
25910897f18SRafael Espindola   // An extra annoyance is that we cannot simply disable merging of the contents
26010897f18SRafael Espindola   // of SHF_MERGE sections, but our implementation requires one output section
26110897f18SRafael Espindola   // per "kind" (string or not, which size/aligment).
26210897f18SRafael Espindola   // Fortunately, creating symbols in the middle of a merge section is not
26310897f18SRafael Espindola   // supported by bfd or gold, so we can just create multiple section in that
26410897f18SRafael Espindola   // case.
26510897f18SRafael Espindola   const typename ELFT::Shdr *H = C->getSectionHdr();
26610897f18SRafael Espindola   typedef typename ELFT::uint uintX_t;
26710897f18SRafael Espindola   uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
26810897f18SRafael Espindola 
26910897f18SRafael Espindola   uintX_t Alignment = 0;
27010897f18SRafael Espindola   if (isa<MergeInputSection<ELFT>>(C))
27110897f18SRafael Espindola     Alignment = std::max(H->sh_addralign, H->sh_entsize);
27210897f18SRafael Espindola 
27310897f18SRafael Espindola   return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
27410897f18SRafael Espindola }
27510897f18SRafael Espindola 
27610897f18SRafael Espindola template <class ELFT>
27720d03194SEugene Leviant void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
27820d03194SEugene Leviant                                     InputSectionBase<ELFT> *Sec,
27920d03194SEugene Leviant                                     StringRef Name) {
28028c1597aSRafael Espindola   OutputSectionBase<ELFT> *OutSec;
28128c1597aSRafael Espindola   bool IsNew;
28210897f18SRafael Espindola   std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
28328c1597aSRafael Espindola   if (IsNew)
28428c1597aSRafael Espindola     OutputSections->push_back(OutSec);
28520d03194SEugene Leviant   OutSec->addSection(Sec);
28620d03194SEugene Leviant }
28720d03194SEugene Leviant 
28820d03194SEugene Leviant template <class ELFT>
28920d03194SEugene Leviant void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
29028c1597aSRafael Espindola 
2917c3ff2ebSRafael Espindola   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
2927c3ff2ebSRafael Espindola     auto Iter = Opt.Commands.begin() + I;
2937c3ff2ebSRafael Espindola     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
2942ab5f73dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
2952ab5f73dSRui Ueyama       if (shouldDefine<ELFT>(Cmd))
2962ab5f73dSRui Ueyama         addRegular<ELFT>(Cmd);
2972ab5f73dSRui Ueyama       continue;
2982ab5f73dSRui Ueyama     }
29920d03194SEugene Leviant     if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
30020d03194SEugene Leviant       // If we don't have SECTIONS then output sections have already been
301194470cdSGeorge Rimar       // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
30220d03194SEugene Leviant       // will not be called, so ASSERT should be evaluated now.
30320d03194SEugene Leviant       if (!Opt.HasSections)
30420d03194SEugene Leviant         Cmd->Expression(0);
30520d03194SEugene Leviant       continue;
30620d03194SEugene Leviant     }
3072ab5f73dSRui Ueyama 
308ceabe80eSEugene Leviant     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
3097bd37870SRafael Espindola       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
3107bd37870SRafael Espindola 
31148c3f1ceSRui Ueyama       if (Cmd->Name == "/DISCARD/") {
3127bd37870SRafael Espindola         discard(V);
31348c3f1ceSRui Ueyama         continue;
31448c3f1ceSRui Ueyama       }
3150b9ce6a4SRui Ueyama 
3167c3ff2ebSRafael Espindola       if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
3177c3ff2ebSRafael Espindola         for (InputSectionBase<ELFT> *S : V)
3187c3ff2ebSRafael Espindola           S->OutSec = nullptr;
3197c3ff2ebSRafael Espindola         Opt.Commands.erase(Iter);
320dfbbbc86SGeorge Rimar         --I;
3217c3ff2ebSRafael Espindola         continue;
3227c3ff2ebSRafael Espindola       }
3237c3ff2ebSRafael Espindola 
3247c3ff2ebSRafael Espindola       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
3257c3ff2ebSRafael Espindola         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
3267c3ff2ebSRafael Espindola           if (shouldDefine<ELFT>(OutCmd))
3277c3ff2ebSRafael Espindola             addSymbol<ELFT>(OutCmd);
3287c3ff2ebSRafael Espindola 
32997403d15SEugene Leviant       if (V.empty())
3300b9ce6a4SRui Ueyama         continue;
3310b9ce6a4SRui Ueyama 
332a14b13d8SGeorge Rimar       for (InputSectionBase<ELFT> *Sec : V) {
33320d03194SEugene Leviant         addSection(Factory, Sec, Cmd->Name);
33420d03194SEugene Leviant         if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
335db24d9c3SGeorge Rimar           Sec->Alignment = Subalign;
33620d03194SEugene Leviant       }
337eea3114fSGeorge Rimar     }
33848c3f1ceSRui Ueyama   }
339db24d9c3SGeorge Rimar }
340e63d81bdSEugene Leviant 
34120d03194SEugene Leviant template <class ELFT>
34220d03194SEugene Leviant void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
34320d03194SEugene Leviant   processCommands(Factory);
3440b9ce6a4SRui Ueyama   // Add orphan sections.
34520d03194SEugene Leviant   for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
34620d03194SEugene Leviant     for (InputSectionBase<ELFT> *S : F->getSections())
34720d03194SEugene Leviant       if (!isDiscarded(S) && !S->OutSec)
348a8d12ef8SEugene Leviant         addSection(Factory, S, getOutputSectionName(S->Name));
349e63d81bdSEugene Leviant }
350e63d81bdSEugene Leviant 
351db741e72SEugene Leviant // Sets value of a section-defined symbol. Two kinds of
352db741e72SEugene Leviant // symbols are processed: synthetic symbols, whose value
353db741e72SEugene Leviant // is an offset from beginning of section and regular
354db741e72SEugene Leviant // symbols whose value is absolute.
355db741e72SEugene Leviant template <class ELFT>
356db741e72SEugene Leviant static void assignSectionSymbol(SymbolAssignment *Cmd,
357db741e72SEugene Leviant                                 OutputSectionBase<ELFT> *Sec,
358db741e72SEugene Leviant                                 typename ELFT::uint Off) {
359db741e72SEugene Leviant   if (!Cmd->Sym)
360db741e72SEugene Leviant     return;
361db741e72SEugene Leviant 
362db741e72SEugene Leviant   if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
363db741e72SEugene Leviant     Body->Section = Sec;
364db741e72SEugene Leviant     Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
365db741e72SEugene Leviant     return;
366db741e72SEugene Leviant   }
367db741e72SEugene Leviant   auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
368db741e72SEugene Leviant   Body->Value = Cmd->Expression(Sec->getVA() + Off);
369db741e72SEugene Leviant }
370db741e72SEugene Leviant 
371a940e539SRafael Espindola template <class ELFT> static bool isTbss(OutputSectionBase<ELFT> *Sec) {
372a940e539SRafael Espindola   return (Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS;
373a940e539SRafael Espindola }
374a940e539SRafael Espindola 
375d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
376d3190795SRafael Espindola   if (!AlreadyOutputIS.insert(S).second)
377ceabe80eSEugene Leviant     return;
378a940e539SRafael Espindola   bool IsTbss = isTbss(CurOutSec);
379d3190795SRafael Espindola 
380d3190795SRafael Espindola   uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
381d3190795SRafael Espindola   Pos = alignTo(Pos, S->Alignment);
382d3190795SRafael Espindola   S->OutSecOff = Pos - CurOutSec->getVA();
383d3190795SRafael Espindola   Pos += S->getSize();
384d3190795SRafael Espindola 
385d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
386d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
387d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
388d3190795SRafael Espindola   CurOutSec->setSize(Pos - CurOutSec->getVA());
389d3190795SRafael Espindola 
3907252ae52SRafael Espindola   if (IsTbss)
3917252ae52SRafael Espindola     ThreadBssOffset = Pos - Dot;
3927252ae52SRafael Espindola   else
393d3190795SRafael Espindola     Dot = Pos;
3942de509c3SRui Ueyama }
395ceabe80eSEugene Leviant 
396d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::flush() {
39765499b90SRafael Espindola   if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
39865499b90SRafael Espindola     return;
39965499b90SRafael Espindola   if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
400d3190795SRafael Espindola     for (InputSection<ELFT> *I : OutSec->Sections)
401d3190795SRafael Espindola       output(I);
40265499b90SRafael Espindola   } else {
40365499b90SRafael Espindola     Dot += CurOutSec->getSize();
404d3190795SRafael Espindola   }
405d3190795SRafael Espindola }
40697403d15SEugene Leviant 
407d3190795SRafael Espindola template <class ELFT>
408d3190795SRafael Espindola void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
409d3190795SRafael Espindola   if (CurOutSec == Sec)
410d3190795SRafael Espindola     return;
411d3190795SRafael Espindola   if (AlreadyOutputOS.count(Sec))
412d3190795SRafael Espindola     return;
413d3190795SRafael Espindola 
414d3190795SRafael Espindola   flush();
415d3190795SRafael Espindola   CurOutSec = Sec;
416d3190795SRafael Espindola 
417d3190795SRafael Espindola   Dot = alignTo(Dot, CurOutSec->getAlignment());
418a940e539SRafael Espindola   CurOutSec->setVA(isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot);
419b71d6f7aSEugene Leviant 
420b71d6f7aSEugene Leviant   // If neither AT nor AT> is specified for an allocatable section, the linker
421b71d6f7aSEugene Leviant   // will set the LMA such that the difference between VMA and LMA for the
422b71d6f7aSEugene Leviant   // section is the same as the preceding output section in the same region
423b71d6f7aSEugene Leviant   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
424b71d6f7aSEugene Leviant   CurOutSec->setLMAOffset(LMAOffset);
425d3190795SRafael Espindola }
426d3190795SRafael Espindola 
427d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
428e38cbab5SGeorge Rimar   // This handles the assignments to symbol or to a location counter (.)
429d3190795SRafael Espindola   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
43097403d15SEugene Leviant     if (AssignCmd->Name == ".") {
43197403d15SEugene Leviant       // Update to location counter means update to section size.
432d3190795SRafael Espindola       Dot = AssignCmd->Expression(Dot);
433d3190795SRafael Espindola       CurOutSec->setSize(Dot - CurOutSec->getVA());
434d3190795SRafael Espindola       return;
43597403d15SEugene Leviant     }
436d3190795SRafael Espindola     assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
437d3190795SRafael Espindola     return;
43897403d15SEugene Leviant   }
439e38cbab5SGeorge Rimar 
440e38cbab5SGeorge Rimar   // Handle BYTE(), SHORT(), LONG(), or QUAD().
441e38cbab5SGeorge Rimar   if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
442e38cbab5SGeorge Rimar     DataCmd->Offset = Dot - CurOutSec->getVA();
443e38cbab5SGeorge Rimar     Dot += DataCmd->Size;
444e38cbab5SGeorge Rimar     CurOutSec->setSize(Dot - CurOutSec->getVA());
445e38cbab5SGeorge Rimar     return;
446e38cbab5SGeorge Rimar   }
447e38cbab5SGeorge Rimar 
448e38cbab5SGeorge Rimar   // It handles single input section description command,
449e38cbab5SGeorge Rimar   // calculates and assigns the offsets for each section and also
450e38cbab5SGeorge Rimar   // updates the output section size.
451d3190795SRafael Espindola   auto &ICmd = cast<InputSectionDescription>(Base);
452d3190795SRafael Espindola   for (InputSectionData *ID : ICmd.Sections) {
453d3190795SRafael Espindola     auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
454d3190795SRafael Espindola     switchTo(IB->OutSec);
455d3190795SRafael Espindola     if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
456d3190795SRafael Espindola       output(I);
45765499b90SRafael Espindola     else
45865499b90SRafael Espindola       flush();
459ceabe80eSEugene Leviant   }
460ceabe80eSEugene Leviant }
461ceabe80eSEugene Leviant 
4628f66df92SGeorge Rimar template <class ELFT>
463a14b13d8SGeorge Rimar static std::vector<OutputSectionBase<ELFT> *>
4649257764dSEugene Leviant findSections(StringRef Name,
465d3190795SRafael Espindola              const std::vector<OutputSectionBase<ELFT> *> &Sections) {
466a14b13d8SGeorge Rimar   std::vector<OutputSectionBase<ELFT> *> Ret;
467a14b13d8SGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : Sections)
4689257764dSEugene Leviant     if (Sec->getName() == Name)
469a14b13d8SGeorge Rimar       Ret.push_back(Sec);
470a14b13d8SGeorge Rimar   return Ret;
4718f66df92SGeorge Rimar }
4728f66df92SGeorge Rimar 
473d3190795SRafael Espindola template <class ELFT>
474d3190795SRafael Espindola void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
475b71d6f7aSEugene Leviant   if (Cmd->LMAExpr)
476b71d6f7aSEugene Leviant     LMAOffset = Cmd->LMAExpr(Dot) - Dot;
477d3190795SRafael Espindola   std::vector<OutputSectionBase<ELFT> *> Sections =
4789257764dSEugene Leviant       findSections(Cmd->Name, *OutputSections);
479d3190795SRafael Espindola   if (Sections.empty())
480d3190795SRafael Espindola     return;
481d3190795SRafael Espindola   switchTo(Sections[0]);
482d3190795SRafael Espindola   // Find the last section output location. We will output orphan sections
483d3190795SRafael Espindola   // there so that end symbols point to the correct location.
484d3190795SRafael Espindola   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
485d3190795SRafael Espindola                         [](const std::unique_ptr<BaseCommand> &Cmd) {
486d3190795SRafael Espindola                           return !isa<SymbolAssignment>(*Cmd);
487d3190795SRafael Espindola                         })
488d3190795SRafael Espindola                .base();
489d3190795SRafael Espindola   for (auto I = Cmd->Commands.begin(); I != E; ++I)
490d3190795SRafael Espindola     process(**I);
49165499b90SRafael Espindola   for (OutputSectionBase<ELFT> *Base : Sections)
492d3190795SRafael Espindola     switchTo(Base);
4932506cb4dSEugene Leviant   flush();
494b31dd370SGeorge Rimar   std::for_each(E, Cmd->Commands.end(),
495b31dd370SGeorge Rimar                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
496d3190795SRafael Espindola }
497d3190795SRafael Espindola 
4989546fffbSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
4996d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
5006d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
5016d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
5026d38e4dbSRafael Espindola   // clutter the output.
5036d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
5046d38e4dbSRafael Espindola   // more aggressive at removing them.
5056d38e4dbSRafael Espindola   auto Pos = std::remove_if(
5066d38e4dbSRafael Espindola       Opt.Commands.begin(), Opt.Commands.end(),
5076d38e4dbSRafael Espindola       [&](const std::unique_ptr<BaseCommand> &Base) {
5086d38e4dbSRafael Espindola         auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
5096d38e4dbSRafael Espindola         if (!Cmd)
5106d38e4dbSRafael Espindola           return false;
5116d38e4dbSRafael Espindola         std::vector<OutputSectionBase<ELFT> *> Secs =
5129257764dSEugene Leviant             findSections(Cmd->Name, *OutputSections);
5136d38e4dbSRafael Espindola         if (!Secs.empty())
5146d38e4dbSRafael Espindola           return false;
5156d38e4dbSRafael Espindola         for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
5166d38e4dbSRafael Espindola           if (!isa<InputSectionDescription>(I.get()))
5176d38e4dbSRafael Espindola             return false;
5186d38e4dbSRafael Espindola         return true;
5196d38e4dbSRafael Espindola       });
5206d38e4dbSRafael Espindola   Opt.Commands.erase(Pos, Opt.Commands.end());
5216d38e4dbSRafael Espindola 
5229546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
5239546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
5249546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
5259546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
5269546fffbSRafael Espindola   uintX_t Flags = SHF_ALLOC;
5279546fffbSRafael Espindola   uint32_t Type = 0;
5289546fffbSRafael Espindola   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
5299546fffbSRafael Espindola     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
5309546fffbSRafael Espindola     if (!Cmd)
5319546fffbSRafael Espindola       continue;
5329546fffbSRafael Espindola     std::vector<OutputSectionBase<ELFT> *> Secs =
5339257764dSEugene Leviant         findSections(Cmd->Name, *OutputSections);
5349546fffbSRafael Espindola     if (!Secs.empty()) {
5359546fffbSRafael Espindola       Flags = Secs[0]->getFlags();
5369546fffbSRafael Espindola       Type = Secs[0]->getType();
5379546fffbSRafael Espindola       continue;
5389546fffbSRafael Espindola     }
5399546fffbSRafael Espindola 
5409546fffbSRafael Espindola     auto *OutSec = new OutputSection<ELFT>(Cmd->Name, Type, Flags);
5419546fffbSRafael Espindola     Out<ELFT>::Pool.emplace_back(OutSec);
5429546fffbSRafael Espindola     OutputSections->push_back(OutSec);
5439546fffbSRafael Espindola   }
5449546fffbSRafael Espindola }
5459546fffbSRafael Espindola 
54615c57951SRafael Espindola // When placing orphan sections, we want to place them after symbol assignments
54715c57951SRafael Espindola // so that an orphan after
54815c57951SRafael Espindola //   begin_foo = .;
54915c57951SRafael Espindola //   foo : { *(foo) }
55015c57951SRafael Espindola //   end_foo = .;
55115c57951SRafael Espindola // doesn't break the intended meaning of the begin/end symbols.
55215c57951SRafael Espindola // We don't want to go over sections since Writer<ELFT>::sortSections is the
55315c57951SRafael Espindola // one in charge of deciding the order of the sections.
55415c57951SRafael Espindola // We don't want to go over alignments, since doing so in
55515c57951SRafael Espindola //  rx_sec : { *(rx_sec) }
55615c57951SRafael Espindola //  . = ALIGN(0x1000);
55715c57951SRafael Espindola //  /* The RW PT_LOAD starts here*/
55815c57951SRafael Espindola //  rw_sec : { *(rw_sec) }
55915c57951SRafael Espindola // would mean that the RW PT_LOAD would become unaligned.
56015c57951SRafael Espindola static bool shouldSkip(const BaseCommand &Cmd) {
56115c57951SRafael Espindola   if (isa<OutputSectionCommand>(Cmd))
56215c57951SRafael Espindola     return false;
56315c57951SRafael Espindola   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
56415c57951SRafael Espindola   if (!Assign)
56515c57951SRafael Espindola     return true;
56615c57951SRafael Espindola   return Assign->Name != ".";
56715c57951SRafael Espindola }
56815c57951SRafael Espindola 
5696d91fce5SRafael Espindola template <class ELFT>
5706d91fce5SRafael Espindola void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
571652852c5SGeorge Rimar   // Orphan sections are sections present in the input files which
5727c18c28cSRui Ueyama   // are not explicitly placed into the output file by the linker script.
5737c18c28cSRui Ueyama   // We place orphan sections at end of file.
5747c18c28cSRui Ueyama   // Other linkers places them using some heuristics as described in
575652852c5SGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
576aab6d5c5SRafael Espindola 
577aab6d5c5SRafael Espindola   // The OutputSections are already in the correct order.
578aab6d5c5SRafael Espindola   // This loops creates or moves commands as needed so that they are in the
579aab6d5c5SRafael Espindola   // correct order.
580aab6d5c5SRafael Espindola   int CmdIndex = 0;
581e5cc668eSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
582652852c5SGeorge Rimar     StringRef Name = Sec->getName();
583aab6d5c5SRafael Espindola 
584aab6d5c5SRafael Espindola     // Find the last spot where we can insert a command and still get the
58515c57951SRafael Espindola     // correct result.
586aab6d5c5SRafael Espindola     auto CmdIter = Opt.Commands.begin() + CmdIndex;
587aab6d5c5SRafael Espindola     auto E = Opt.Commands.end();
58815c57951SRafael Espindola     while (CmdIter != E && shouldSkip(**CmdIter)) {
589aab6d5c5SRafael Espindola       ++CmdIter;
590aab6d5c5SRafael Espindola       ++CmdIndex;
591aab6d5c5SRafael Espindola     }
592aab6d5c5SRafael Espindola 
593aab6d5c5SRafael Espindola     auto Pos =
594aab6d5c5SRafael Espindola         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
595aab6d5c5SRafael Espindola           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
596aab6d5c5SRafael Espindola           return Cmd && Cmd->Name == Name;
597aab6d5c5SRafael Espindola         });
598aab6d5c5SRafael Espindola     if (Pos == E) {
599aab6d5c5SRafael Espindola       Opt.Commands.insert(CmdIter,
600aab6d5c5SRafael Espindola                           llvm::make_unique<OutputSectionCommand>(Name));
601aab6d5c5SRafael Espindola       ++CmdIndex;
60215c57951SRafael Espindola       continue;
60315c57951SRafael Espindola     }
60415c57951SRafael Espindola 
60515c57951SRafael Espindola     // Continue from where we found it.
60615c57951SRafael Espindola     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
60715c57951SRafael Espindola     continue;
608652852c5SGeorge Rimar   }
609652852c5SGeorge Rimar 
6107c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
611be607334SRafael Espindola   Dot = 0;
612652852c5SGeorge Rimar 
613076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
614076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
6158d083e6aSRui Ueyama       if (Cmd->Name == ".") {
6168d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
6178d083e6aSRui Ueyama       } else if (Cmd->Sym) {
6188d083e6aSRui Ueyama         cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
6198d083e6aSRui Ueyama       }
62005ef4cffSRui Ueyama       continue;
621652852c5SGeorge Rimar     }
622652852c5SGeorge Rimar 
623eefa758eSGeorge Rimar     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
624eefa758eSGeorge Rimar       Cmd->Expression(Dot);
625eefa758eSGeorge Rimar       continue;
626eefa758eSGeorge Rimar     }
627eefa758eSGeorge Rimar 
628076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
629652852c5SGeorge Rimar 
63058e5c4dcSGeorge Rimar     if (Cmd->AddrExpr)
63158e5c4dcSGeorge Rimar       Dot = Cmd->AddrExpr(Dot);
63258e5c4dcSGeorge Rimar 
633d3190795SRafael Espindola     assignOffsets(Cmd);
634a14b13d8SGeorge Rimar   }
635467c4d55SEugene Leviant 
636aab6d5c5SRafael Espindola   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
637aab6d5c5SRafael Espindola   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
638aab6d5c5SRafael Espindola     if (Sec->getFlags() & SHF_ALLOC)
639aab6d5c5SRafael Espindola       MinVA = std::min(MinVA, Sec->getVA());
640aab6d5c5SRafael Espindola     else
641d3190795SRafael Espindola       Sec->setVA(0);
642aab6d5c5SRafael Espindola   }
643aab6d5c5SRafael Espindola 
6440d4b6d5cSRafael Espindola   uintX_t HeaderSize = getHeaderSize();
6456d91fce5SRafael Espindola   auto FirstPTLoad =
6466d91fce5SRafael Espindola       std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
6476d91fce5SRafael Espindola         return E.H.p_type == PT_LOAD;
6486d91fce5SRafael Espindola       });
6496d91fce5SRafael Espindola   if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
65064c32d6fSRafael Espindola     // ELF and Program headers need to be right before the first section in
651b91e7118SGeorge Rimar     // memory. Set their addresses accordingly.
6524ec013acSRafael Espindola     MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
653467c4d55SEugene Leviant     Out<ELFT>::ElfHeader->setVA(MinVA);
654467c4d55SEugene Leviant     Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
6556d91fce5SRafael Espindola     FirstPTLoad->First = Out<ELFT>::ElfHeader;
6566d91fce5SRafael Espindola     if (!FirstPTLoad->Last)
6576d91fce5SRafael Espindola       FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
658*cd8eaf89SEugene Leviant   } else if (!FirstPTLoad->First) {
659*cd8eaf89SEugene Leviant     // Sometimes the very first PT_LOAD segment can be empty.
660*cd8eaf89SEugene Leviant     // This happens if (all conditions met):
661*cd8eaf89SEugene Leviant     //  - Linker script is used
662*cd8eaf89SEugene Leviant     //  - First section in ELF image is not RO
663*cd8eaf89SEugene Leviant     //  - Not enough space for program headers.
664*cd8eaf89SEugene Leviant     // The code below removes empty PT_LOAD segment and updates
665*cd8eaf89SEugene Leviant     // program headers size.
666*cd8eaf89SEugene Leviant     Phdrs.erase(FirstPTLoad);
667*cd8eaf89SEugene Leviant     Out<ELFT>::ProgramHeaders->setSize(sizeof(typename ELFT::Phdr) *
668*cd8eaf89SEugene Leviant                                        Phdrs.size());
6696d91fce5SRafael Espindola   }
670fb8978fcSDima Stepanov }
671652852c5SGeorge Rimar 
672464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
67307320e40SRui Ueyama template <class ELFT>
674a4b41dcaSRafael Espindola std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
675edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
676bbe38602SEugene Leviant 
677464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
678464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
679bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
680edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
681edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
682bbe38602SEugene Leviant 
683bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
684adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
685bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
686adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
68756b21c86SEugene Leviant 
68856b21c86SEugene Leviant     if (Cmd.LMAExpr) {
68956b21c86SEugene Leviant       Phdr.H.p_paddr = Cmd.LMAExpr(0);
69056b21c86SEugene Leviant       Phdr.HasLMA = true;
69156b21c86SEugene Leviant     }
692bbe38602SEugene Leviant   }
693bbe38602SEugene Leviant 
694464daadcSRui Ueyama   // Add output sections to program headers.
695edebbdf1SRui Ueyama   PhdrEntry<ELFT> *Load = nullptr;
696edebbdf1SRui Ueyama   uintX_t Flags = PF_R;
697464daadcSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
698bbe38602SEugene Leviant     if (!(Sec->getFlags() & SHF_ALLOC))
699bbe38602SEugene Leviant       break;
700bbe38602SEugene Leviant 
701edebbdf1SRui Ueyama     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
702bbe38602SEugene Leviant     if (!PhdrIds.empty()) {
703bbe38602SEugene Leviant       // Assign headers specified by linker script
704bbe38602SEugene Leviant       for (size_t Id : PhdrIds) {
705edebbdf1SRui Ueyama         Ret[Id].add(Sec);
706865bf863SEugene Leviant         if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
7070b113671SRafael Espindola           Ret[Id].H.p_flags |= Sec->getPhdrFlags();
708bbe38602SEugene Leviant       }
709bbe38602SEugene Leviant     } else {
710bbe38602SEugene Leviant       // If we have no load segment or flags've changed then we want new load
711bbe38602SEugene Leviant       // segment.
7120b113671SRafael Espindola       uintX_t NewFlags = Sec->getPhdrFlags();
713bbe38602SEugene Leviant       if (Load == nullptr || Flags != NewFlags) {
714edebbdf1SRui Ueyama         Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
715bbe38602SEugene Leviant         Flags = NewFlags;
716bbe38602SEugene Leviant       }
71718f084ffSRui Ueyama       Load->add(Sec);
718bbe38602SEugene Leviant     }
719bbe38602SEugene Leviant   }
720edebbdf1SRui Ueyama   return Ret;
721bbe38602SEugene Leviant }
722bbe38602SEugene Leviant 
723f9bc3bd2SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
724f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
725f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
726f9bc3bd2SEugene Leviant   return !Opt.PhdrsCommands.empty() &&
727f9bc3bd2SEugene Leviant          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
728f9bc3bd2SEugene Leviant            return Cmd.Type == PT_INTERP;
729f9bc3bd2SEugene Leviant          }) == Opt.PhdrsCommands.end();
730f9bc3bd2SEugene Leviant }
731f9bc3bd2SEugene Leviant 
732bbe38602SEugene Leviant template <class ELFT>
73307320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
734f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
735f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
736f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
737f6c3ccefSGeorge Rimar         return Cmd->Filler;
738e2ee72b5SGeorge Rimar   return {};
739e2ee72b5SGeorge Rimar }
740e2ee72b5SGeorge Rimar 
741e38cbab5SGeorge Rimar template <class ELFT>
742e38cbab5SGeorge Rimar static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
743e38cbab5SGeorge Rimar   const endianness E = ELFT::TargetEndianness;
744e38cbab5SGeorge Rimar 
745e38cbab5SGeorge Rimar   switch (Size) {
746e38cbab5SGeorge Rimar   case 1:
747e38cbab5SGeorge Rimar     *Buf = (uint8_t)Data;
748e38cbab5SGeorge Rimar     break;
749e38cbab5SGeorge Rimar   case 2:
750e38cbab5SGeorge Rimar     write16<E>(Buf, Data);
751e38cbab5SGeorge Rimar     break;
752e38cbab5SGeorge Rimar   case 4:
753e38cbab5SGeorge Rimar     write32<E>(Buf, Data);
754e38cbab5SGeorge Rimar     break;
755e38cbab5SGeorge Rimar   case 8:
756e38cbab5SGeorge Rimar     write64<E>(Buf, Data);
757e38cbab5SGeorge Rimar     break;
758e38cbab5SGeorge Rimar   default:
759e38cbab5SGeorge Rimar     llvm_unreachable("unsupported Size argument");
760e38cbab5SGeorge Rimar   }
761e38cbab5SGeorge Rimar }
762e38cbab5SGeorge Rimar 
763e38cbab5SGeorge Rimar template <class ELFT>
764e38cbab5SGeorge Rimar void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
765e38cbab5SGeorge Rimar   int I = getSectionIndex(Name);
766e38cbab5SGeorge Rimar   if (I == INT_MAX)
767e38cbab5SGeorge Rimar     return;
768e38cbab5SGeorge Rimar 
769e38cbab5SGeorge Rimar   OutputSectionCommand *Cmd =
770e38cbab5SGeorge Rimar       dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
771e38cbab5SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
772e38cbab5SGeorge Rimar     if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
773e38cbab5SGeorge Rimar       writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
774e38cbab5SGeorge Rimar }
775e38cbab5SGeorge Rimar 
776b71d6f7aSEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
7778ceadb38SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
7788ceadb38SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
779b71d6f7aSEugene Leviant       if (Cmd->LMAExpr && Cmd->Name == Name)
780b71d6f7aSEugene Leviant         return true;
781b71d6f7aSEugene Leviant   return false;
7828ceadb38SGeorge Rimar }
7838ceadb38SGeorge Rimar 
784c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
785c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
786c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
787c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
788076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
789f510fa6bSRui Ueyama   int I = 0;
790f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
791076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
792076fe157SGeorge Rimar       if (Cmd->Name == Name)
793f510fa6bSRui Ueyama         return I;
794f510fa6bSRui Ueyama     ++I;
795f510fa6bSRui Ueyama   }
796f510fa6bSRui Ueyama   return INT_MAX;
79771b26e94SGeorge Rimar }
79871b26e94SGeorge Rimar 
799bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
800bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
801bbe38602SEugene Leviant }
802bbe38602SEugene Leviant 
8039e69450eSGeorge Rimar template <class ELFT>
804884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
80596659df0SGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
80696659df0SGeorge Rimar     if (Sec->getName() == Name)
80796659df0SGeorge Rimar       return Sec->getVA();
80896659df0SGeorge Rimar   error("undefined section " + Name);
80996659df0SGeorge Rimar   return 0;
81096659df0SGeorge Rimar }
81196659df0SGeorge Rimar 
81296659df0SGeorge Rimar template <class ELFT>
813b71d6f7aSEugene Leviant uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
814b71d6f7aSEugene Leviant   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
815b71d6f7aSEugene Leviant     if (Sec->getName() == Name)
816b71d6f7aSEugene Leviant       return Sec->getLMA();
817b71d6f7aSEugene Leviant   error("undefined section " + Name);
818b71d6f7aSEugene Leviant   return 0;
819b71d6f7aSEugene Leviant }
820b71d6f7aSEugene Leviant 
821b71d6f7aSEugene Leviant template <class ELFT>
822884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
8239e69450eSGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
8249e69450eSGeorge Rimar     if (Sec->getName() == Name)
8259e69450eSGeorge Rimar       return Sec->getSize();
8269e69450eSGeorge Rimar   error("undefined section " + Name);
8279e69450eSGeorge Rimar   return 0;
8289e69450eSGeorge Rimar }
8299e69450eSGeorge Rimar 
83036fac7f0SEugene Leviant template <class ELFT>
83136fac7f0SEugene Leviant uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
83236fac7f0SEugene Leviant   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
83336fac7f0SEugene Leviant     if (Sec->getName() == Name)
83436fac7f0SEugene Leviant       return Sec->getAlignment();
83536fac7f0SEugene Leviant   error("undefined section " + Name);
83636fac7f0SEugene Leviant   return 0;
83736fac7f0SEugene Leviant }
83836fac7f0SEugene Leviant 
839884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
8400d4b6d5cSRafael Espindola   return elf::getHeaderSize<ELFT>();
841e32a3598SGeorge Rimar }
842e32a3598SGeorge Rimar 
843884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
844884e786dSGeorge Rimar   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
845884e786dSGeorge Rimar     return B->getVA<ELFT>();
846884e786dSGeorge Rimar   error("symbol not found: " + S);
847884e786dSGeorge Rimar   return 0;
848884e786dSGeorge Rimar }
849884e786dSGeorge Rimar 
850f34f45fdSGeorge Rimar template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
851f34f45fdSGeorge Rimar   return Symtab<ELFT>::X->find(S) != nullptr;
852f34f45fdSGeorge Rimar }
853f34f45fdSGeorge Rimar 
854bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
855bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
856bbe38602SEugene Leviant // PHDRS {} script block.
857bbe38602SEugene Leviant template <class ELFT>
858edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
859076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
860076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
861edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
86231d842f5SGeorge Rimar       continue;
86331d842f5SGeorge Rimar 
86429c5a2a9SRui Ueyama     std::vector<size_t> Ret;
86529c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
86629c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
86729c5a2a9SRui Ueyama     return Ret;
868bbe38602SEugene Leviant   }
86931d842f5SGeorge Rimar   return {};
87031d842f5SGeorge Rimar }
871bbe38602SEugene Leviant 
87229c5a2a9SRui Ueyama template <class ELFT>
87329c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
87429c5a2a9SRui Ueyama   size_t I = 0;
87529c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
87629c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
87729c5a2a9SRui Ueyama       return I;
87829c5a2a9SRui Ueyama     ++I;
87929c5a2a9SRui Ueyama   }
88029c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
88129c5a2a9SRui Ueyama   return 0;
88229c5a2a9SRui Ueyama }
88329c5a2a9SRui Ueyama 
88407320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
885c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
886c3794e58SGeorge Rimar 
887f7c5fbb1SRui Ueyama public:
88807320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
889f23b2320SGeorge Rimar 
89020b6598cSGeorge Rimar   void readLinkerScript();
89120b6598cSGeorge Rimar   void readVersionScript();
892f7c5fbb1SRui Ueyama 
893f7c5fbb1SRui Ueyama private:
89452a1509eSRui Ueyama   void addFile(StringRef Path);
89552a1509eSRui Ueyama 
896f7c5fbb1SRui Ueyama   void readAsNeeded();
89790c5099eSDenis Protivensky   void readEntry();
89883f406cfSGeorge Rimar   void readExtern();
899f7c5fbb1SRui Ueyama   void readGroup();
90031aa1f83SRui Ueyama   void readInclude();
901ee59282bSRui Ueyama   void readOutput();
9029159ce93SDavide Italiano   void readOutputArch();
903f7c5fbb1SRui Ueyama   void readOutputFormat();
904bbe38602SEugene Leviant   void readPhdrs();
90568a39a65SDavide Italiano   void readSearchDir();
9068e3b38abSDenis Protivensky   void readSections();
90795769b4aSRui Ueyama   void readVersion();
90895769b4aSRui Ueyama   void readVersionScriptCommand();
9098e3b38abSDenis Protivensky 
910113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
911e38cbab5SGeorge Rimar   BytesDataCommand *readBytesDataCommand(StringRef Tok);
912ff1f29e0SGeorge Rimar   std::vector<uint8_t> readFill();
91310416564SRui Ueyama   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
914ff1f29e0SGeorge Rimar   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
915bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
916a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionDescription(StringRef Tok);
917c91930a1SGeorge Rimar   Regex readFilePatterns();
91807171f21SGeorge Rimar   std::vector<SectionPattern> readInputSectionsList();
919a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
920bbe38602SEugene Leviant   unsigned readPhdrType();
921be394db3SGeorge Rimar   SortSectionPolicy readSortKind();
922a35e39caSPetr Hosek   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
923db741e72SEugene Leviant   SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
92403fc010eSGeorge Rimar   void readSort();
925eefa758eSGeorge Rimar   Expr readAssert();
926708019c4SRui Ueyama 
927708019c4SRui Ueyama   Expr readExpr();
928708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
929b71d6f7aSEugene Leviant   StringRef readParenLiteral();
930708019c4SRui Ueyama   Expr readPrimary();
931708019c4SRui Ueyama   Expr readTernary(Expr Cond);
9326ad7dfccSRui Ueyama   Expr readParenExpr();
933f7c5fbb1SRui Ueyama 
93420b6598cSGeorge Rimar   // For parsing version script.
93520b6598cSGeorge Rimar   void readExtern(std::vector<SymbolVersion> *Globals);
93695769b4aSRui Ueyama   void readVersionDeclaration(StringRef VerStr);
93720b6598cSGeorge Rimar   void readGlobal(StringRef VerStr);
93820b6598cSGeorge Rimar   void readLocal();
93920b6598cSGeorge Rimar 
94007320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
94107320e40SRui Ueyama   StringSaver Saver = {ScriptConfig->Alloc};
94216b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
943f7c5fbb1SRui Ueyama };
944f7c5fbb1SRui Ueyama 
94520b6598cSGeorge Rimar void ScriptParser::readVersionScript() {
94695769b4aSRui Ueyama   readVersionScriptCommand();
94720b6598cSGeorge Rimar   if (!atEOF())
94895769b4aSRui Ueyama     setError("EOF expected, but got " + next());
94995769b4aSRui Ueyama }
95095769b4aSRui Ueyama 
95195769b4aSRui Ueyama void ScriptParser::readVersionScriptCommand() {
95295769b4aSRui Ueyama   if (skip("{")) {
95395769b4aSRui Ueyama     readVersionDeclaration("");
95420b6598cSGeorge Rimar     return;
95520b6598cSGeorge Rimar   }
95620b6598cSGeorge Rimar 
95795769b4aSRui Ueyama   while (!atEOF() && !Error && peek() != "}") {
95820b6598cSGeorge Rimar     StringRef VerStr = next();
95920b6598cSGeorge Rimar     if (VerStr == "{") {
96095769b4aSRui Ueyama       setError("anonymous version definition is used in "
96195769b4aSRui Ueyama                "combination with other version definitions");
96220b6598cSGeorge Rimar       return;
96320b6598cSGeorge Rimar     }
96420b6598cSGeorge Rimar     expect("{");
96595769b4aSRui Ueyama     readVersionDeclaration(VerStr);
96620b6598cSGeorge Rimar   }
96720b6598cSGeorge Rimar }
96820b6598cSGeorge Rimar 
96995769b4aSRui Ueyama void ScriptParser::readVersion() {
97095769b4aSRui Ueyama   expect("{");
97195769b4aSRui Ueyama   readVersionScriptCommand();
97295769b4aSRui Ueyama   expect("}");
97395769b4aSRui Ueyama }
97495769b4aSRui Ueyama 
97520b6598cSGeorge Rimar void ScriptParser::readLinkerScript() {
976f7c5fbb1SRui Ueyama   while (!atEOF()) {
977f7c5fbb1SRui Ueyama     StringRef Tok = next();
978a27eeccaSRui Ueyama     if (Tok == ";")
979a27eeccaSRui Ueyama       continue;
980a27eeccaSRui Ueyama 
98120d03194SEugene Leviant     if (Tok == "ASSERT") {
98220d03194SEugene Leviant       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
98320d03194SEugene Leviant     } else if (Tok == "ENTRY") {
984a27eeccaSRui Ueyama       readEntry();
985a27eeccaSRui Ueyama     } else if (Tok == "EXTERN") {
986a27eeccaSRui Ueyama       readExtern();
987a27eeccaSRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
988a27eeccaSRui Ueyama       readGroup();
989a27eeccaSRui Ueyama     } else if (Tok == "INCLUDE") {
990a27eeccaSRui Ueyama       readInclude();
991a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT") {
992a27eeccaSRui Ueyama       readOutput();
993a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
994a27eeccaSRui Ueyama       readOutputArch();
995a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
996a27eeccaSRui Ueyama       readOutputFormat();
997a27eeccaSRui Ueyama     } else if (Tok == "PHDRS") {
998a27eeccaSRui Ueyama       readPhdrs();
999a27eeccaSRui Ueyama     } else if (Tok == "SEARCH_DIR") {
1000a27eeccaSRui Ueyama       readSearchDir();
1001a27eeccaSRui Ueyama     } else if (Tok == "SECTIONS") {
1002a27eeccaSRui Ueyama       readSections();
1003a27eeccaSRui Ueyama     } else if (Tok == "VERSION") {
1004a27eeccaSRui Ueyama       readVersion();
1005db741e72SEugene Leviant     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
10060df80befSPetr Hosek       Opt.Commands.emplace_back(Cmd);
1007e5d3ca50SPetr Hosek     } else {
10085761042dSGeorge Rimar       setError("unknown directive: " + Tok);
1009f7c5fbb1SRui Ueyama     }
1010f7c5fbb1SRui Ueyama   }
1011e5d3ca50SPetr Hosek }
1012f7c5fbb1SRui Ueyama 
1013717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
101416b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
101516b0cc9eSSimon Atanasyan     SmallString<128> Path;
101616b0cc9eSSimon Atanasyan     (Config->Sysroot + S).toStringRef(Path);
101716b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
101816b0cc9eSSimon Atanasyan       Driver->addFile(Saver.save(Path.str()));
101916b0cc9eSSimon Atanasyan       return;
102016b0cc9eSSimon Atanasyan     }
102116b0cc9eSSimon Atanasyan   }
102216b0cc9eSSimon Atanasyan 
1023f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
102452a1509eSRui Ueyama     Driver->addFile(S);
102552a1509eSRui Ueyama   } else if (S.startswith("=")) {
102652a1509eSRui Ueyama     if (Config->Sysroot.empty())
102752a1509eSRui Ueyama       Driver->addFile(S.substr(1));
102852a1509eSRui Ueyama     else
102952a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
103052a1509eSRui Ueyama   } else if (S.startswith("-l")) {
103121eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
1032a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
1033a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
103452a1509eSRui Ueyama   } else {
103552a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
103652a1509eSRui Ueyama     if (Path.empty())
1037777f9630SGeorge Rimar       setError("unable to find " + S);
1038025d59b1SRui Ueyama     else
103952a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
104052a1509eSRui Ueyama   }
104152a1509eSRui Ueyama }
104252a1509eSRui Ueyama 
1043717677afSRui Ueyama void ScriptParser::readAsNeeded() {
1044f7c5fbb1SRui Ueyama   expect("(");
104535da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
104635da9b6eSRui Ueyama   Config->AsNeeded = true;
1047a2acc931SRui Ueyama   while (!Error && !skip(")"))
1048cd574a5eSGeorge Rimar     addFile(unquote(next()));
104935da9b6eSRui Ueyama   Config->AsNeeded = Orig;
1050f7c5fbb1SRui Ueyama }
1051f7c5fbb1SRui Ueyama 
1052717677afSRui Ueyama void ScriptParser::readEntry() {
105390c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
105490c5099eSDenis Protivensky   expect("(");
105590c5099eSDenis Protivensky   StringRef Tok = next();
105690c5099eSDenis Protivensky   if (Config->Entry.empty())
105790c5099eSDenis Protivensky     Config->Entry = Tok;
105890c5099eSDenis Protivensky   expect(")");
105990c5099eSDenis Protivensky }
106090c5099eSDenis Protivensky 
1061717677afSRui Ueyama void ScriptParser::readExtern() {
106283f406cfSGeorge Rimar   expect("(");
1063a2acc931SRui Ueyama   while (!Error && !skip(")"))
1064a2acc931SRui Ueyama     Config->Undefined.push_back(next());
106583f406cfSGeorge Rimar }
106683f406cfSGeorge Rimar 
1067717677afSRui Ueyama void ScriptParser::readGroup() {
1068f7c5fbb1SRui Ueyama   expect("(");
1069a2acc931SRui Ueyama   while (!Error && !skip(")")) {
1070f7c5fbb1SRui Ueyama     StringRef Tok = next();
1071a2acc931SRui Ueyama     if (Tok == "AS_NEEDED")
1072f7c5fbb1SRui Ueyama       readAsNeeded();
1073a2acc931SRui Ueyama     else
1074cd574a5eSGeorge Rimar       addFile(unquote(Tok));
1075f7c5fbb1SRui Ueyama   }
1076f7c5fbb1SRui Ueyama }
1077f7c5fbb1SRui Ueyama 
1078717677afSRui Ueyama void ScriptParser::readInclude() {
107931aa1f83SRui Ueyama   StringRef Tok = next();
1080cd574a5eSGeorge Rimar   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
1081025d59b1SRui Ueyama   if (!MBOrErr) {
10825761042dSGeorge Rimar     setError("cannot open " + Tok);
1083025d59b1SRui Ueyama     return;
1084025d59b1SRui Ueyama   }
108531aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
1086a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1087a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
108831aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
108931aa1f83SRui Ueyama }
109031aa1f83SRui Ueyama 
1091717677afSRui Ueyama void ScriptParser::readOutput() {
1092ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
1093ee59282bSRui Ueyama   expect("(");
1094ee59282bSRui Ueyama   StringRef Tok = next();
1095ee59282bSRui Ueyama   if (Config->OutputFile.empty())
1096cd574a5eSGeorge Rimar     Config->OutputFile = unquote(Tok);
1097ee59282bSRui Ueyama   expect(")");
1098ee59282bSRui Ueyama }
1099ee59282bSRui Ueyama 
1100717677afSRui Ueyama void ScriptParser::readOutputArch() {
11019159ce93SDavide Italiano   // Error checking only for now.
11029159ce93SDavide Italiano   expect("(");
11039159ce93SDavide Italiano   next();
11049159ce93SDavide Italiano   expect(")");
11059159ce93SDavide Italiano }
11069159ce93SDavide Italiano 
1107717677afSRui Ueyama void ScriptParser::readOutputFormat() {
1108f7c5fbb1SRui Ueyama   // Error checking only for now.
1109f7c5fbb1SRui Ueyama   expect("(");
1110f7c5fbb1SRui Ueyama   next();
11116836c618SDavide Italiano   StringRef Tok = next();
11126836c618SDavide Italiano   if (Tok == ")")
11136836c618SDavide Italiano     return;
1114025d59b1SRui Ueyama   if (Tok != ",") {
11155761042dSGeorge Rimar     setError("unexpected token: " + Tok);
1116025d59b1SRui Ueyama     return;
1117025d59b1SRui Ueyama   }
11186836c618SDavide Italiano   next();
11196836c618SDavide Italiano   expect(",");
11206836c618SDavide Italiano   next();
1121f7c5fbb1SRui Ueyama   expect(")");
1122f7c5fbb1SRui Ueyama }
1123f7c5fbb1SRui Ueyama 
1124bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
1125bbe38602SEugene Leviant   expect("{");
1126bbe38602SEugene Leviant   while (!Error && !skip("}")) {
1127bbe38602SEugene Leviant     StringRef Tok = next();
112856b21c86SEugene Leviant     Opt.PhdrsCommands.push_back(
112956b21c86SEugene Leviant         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1130bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1131bbe38602SEugene Leviant 
1132bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
1133bbe38602SEugene Leviant     do {
1134bbe38602SEugene Leviant       Tok = next();
1135bbe38602SEugene Leviant       if (Tok == ";")
1136bbe38602SEugene Leviant         break;
1137bbe38602SEugene Leviant       if (Tok == "FILEHDR")
1138bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
1139bbe38602SEugene Leviant       else if (Tok == "PHDRS")
1140bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
114156b21c86SEugene Leviant       else if (Tok == "AT")
114256b21c86SEugene Leviant         PhdrCmd.LMAExpr = readParenExpr();
1143865bf863SEugene Leviant       else if (Tok == "FLAGS") {
1144865bf863SEugene Leviant         expect("(");
1145eb685cd7SRafael Espindola         // Passing 0 for the value of dot is a bit of a hack. It means that
1146eb685cd7SRafael Espindola         // we accept expressions like ".|1".
1147eb685cd7SRafael Espindola         PhdrCmd.Flags = readExpr()(0);
1148865bf863SEugene Leviant         expect(")");
1149865bf863SEugene Leviant       } else
1150bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
1151bbe38602SEugene Leviant     } while (!Error);
1152bbe38602SEugene Leviant   }
1153bbe38602SEugene Leviant }
1154bbe38602SEugene Leviant 
1155717677afSRui Ueyama void ScriptParser::readSearchDir() {
115668a39a65SDavide Italiano   expect("(");
115786c5fb82SRui Ueyama   StringRef Tok = next();
11586c7ad13fSRui Ueyama   if (!Config->Nostdlib)
1159cd574a5eSGeorge Rimar     Config->SearchPaths.push_back(unquote(Tok));
116068a39a65SDavide Italiano   expect(")");
116168a39a65SDavide Italiano }
116268a39a65SDavide Italiano 
1163717677afSRui Ueyama void ScriptParser::readSections() {
1164e05336ffSEugene Leviant   Opt.HasSections = true;
11658e3b38abSDenis Protivensky   expect("{");
1166652852c5SGeorge Rimar   while (!Error && !skip("}")) {
1167113cdec9SRui Ueyama     StringRef Tok = next();
1168db741e72SEugene Leviant     BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
1169ceabe80eSEugene Leviant     if (!Cmd) {
1170ceabe80eSEugene Leviant       if (Tok == "ASSERT")
1171eefa758eSGeorge Rimar         Cmd = new AssertCommand(readAssert());
1172ceabe80eSEugene Leviant       else
117310416564SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
11748e3b38abSDenis Protivensky     }
117510416564SRui Ueyama     Opt.Commands.emplace_back(Cmd);
1176652852c5SGeorge Rimar   }
1177708019c4SRui Ueyama }
11788e3b38abSDenis Protivensky 
1179708019c4SRui Ueyama static int precedence(StringRef Op) {
1180708019c4SRui Ueyama   return StringSwitch<int>(Op)
11810120e3f2SRui Ueyama       .Cases("*", "/", 5)
11820120e3f2SRui Ueyama       .Cases("+", "-", 4)
11830120e3f2SRui Ueyama       .Cases("<<", ">>", 3)
11849c4ac5f2SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
11850120e3f2SRui Ueyama       .Cases("&", "|", 1)
1186708019c4SRui Ueyama       .Default(-1);
1187708019c4SRui Ueyama }
1188708019c4SRui Ueyama 
1189c91930a1SGeorge Rimar Regex ScriptParser::readFilePatterns() {
119010416564SRui Ueyama   std::vector<StringRef> V;
119110416564SRui Ueyama   while (!Error && !skip(")"))
119210416564SRui Ueyama     V.push_back(next());
1193c91930a1SGeorge Rimar   return compileGlobPatterns(V);
11940702c4e8SGeorge Rimar }
11950702c4e8SGeorge Rimar 
1196be394db3SGeorge Rimar SortSectionPolicy ScriptParser::readSortKind() {
1197742c3836SRui Ueyama   if (skip("SORT") || skip("SORT_BY_NAME"))
1198be394db3SGeorge Rimar     return SortSectionPolicy::Name;
1199742c3836SRui Ueyama   if (skip("SORT_BY_ALIGNMENT"))
1200be394db3SGeorge Rimar     return SortSectionPolicy::Alignment;
1201575208caSGeorge Rimar   if (skip("SORT_BY_INIT_PRIORITY"))
1202be394db3SGeorge Rimar     return SortSectionPolicy::Priority;
1203be394db3SGeorge Rimar   if (skip("SORT_NONE"))
1204be394db3SGeorge Rimar     return SortSectionPolicy::None;
1205b2a0abdfSRui Ueyama   return SortSectionPolicy::Default;
1206be394db3SGeorge Rimar }
1207be394db3SGeorge Rimar 
1208395281cfSGeorge Rimar // Method reads a list of sequence of excluded files and section globs given in
1209395281cfSGeorge Rimar // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1210395281cfSGeorge Rimar // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1211af03be19SGeorge Rimar // The semantics of that is next:
1212af03be19SGeorge Rimar // * Include .foo.1 from every file.
1213af03be19SGeorge Rimar // * Include .foo.2 from every file but a.o
1214af03be19SGeorge Rimar // * Include .foo.3 from every file but b.o
121507171f21SGeorge Rimar std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
121607171f21SGeorge Rimar   std::vector<SectionPattern> Ret;
1217601e9898SGeorge Rimar   while (!Error && peek() != ")") {
1218027a9e87SRui Ueyama     Regex ExcludeFileRe;
1219395281cfSGeorge Rimar     if (skip("EXCLUDE_FILE")) {
1220395281cfSGeorge Rimar       expect("(");
1221395281cfSGeorge Rimar       ExcludeFileRe = readFilePatterns();
1222395281cfSGeorge Rimar     }
1223395281cfSGeorge Rimar 
1224601e9898SGeorge Rimar     std::vector<StringRef> V;
1225601e9898SGeorge Rimar     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1226395281cfSGeorge Rimar       V.push_back(next());
1227601e9898SGeorge Rimar 
1228601e9898SGeorge Rimar     if (!V.empty())
122907171f21SGeorge Rimar       Ret.push_back({std::move(ExcludeFileRe), compileGlobPatterns(V)});
1230601e9898SGeorge Rimar     else
1231601e9898SGeorge Rimar       setError("section pattern is expected");
1232395281cfSGeorge Rimar   }
123307171f21SGeorge Rimar   return Ret;
1234395281cfSGeorge Rimar }
1235395281cfSGeorge Rimar 
123607171f21SGeorge Rimar // Section pattern grammar can have complex expressions, for example:
123707171f21SGeorge Rimar // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
123807171f21SGeorge Rimar // Generally is a sequence of globs and excludes that may be wrapped in a SORT()
123907171f21SGeorge Rimar // commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
124007171f21SGeorge Rimar // This methods handles wrapping sequences of excluded files and section globs
124107171f21SGeorge Rimar // into SORT() if that needed and reads them all.
1242a2496cbeSGeorge Rimar InputSectionDescription *
1243a2496cbeSGeorge Rimar ScriptParser::readInputSectionRules(StringRef FilePattern) {
1244c91930a1SGeorge Rimar   auto *Cmd = new InputSectionDescription(FilePattern);
12450ed42b0cSDavide Italiano   expect("(");
124607171f21SGeorge Rimar   while (!HasError && !skip(")")) {
124707171f21SGeorge Rimar     SortSectionPolicy Outer = readSortKind();
124807171f21SGeorge Rimar     SortSectionPolicy Inner = SortSectionPolicy::Default;
124907171f21SGeorge Rimar     std::vector<SectionPattern> V;
125007171f21SGeorge Rimar     if (Outer != SortSectionPolicy::Default) {
12510702c4e8SGeorge Rimar       expect("(");
125207171f21SGeorge Rimar       Inner = readSortKind();
125307171f21SGeorge Rimar       if (Inner != SortSectionPolicy::Default) {
1254350ece4eSGeorge Rimar         expect("(");
125507171f21SGeorge Rimar         V = readInputSectionsList();
12560702c4e8SGeorge Rimar         expect(")");
1257350ece4eSGeorge Rimar       } else {
125807171f21SGeorge Rimar         V = readInputSectionsList();
1259350ece4eSGeorge Rimar       }
1260350ece4eSGeorge Rimar       expect(")");
126107171f21SGeorge Rimar     } else {
126207171f21SGeorge Rimar       V = readInputSectionsList();
12630659800eSGeorge Rimar     }
12640702c4e8SGeorge Rimar 
126507171f21SGeorge Rimar     for (SectionPattern &Pat : V) {
126607171f21SGeorge Rimar       Pat.SortInner = Inner;
126707171f21SGeorge Rimar       Pat.SortOuter = Outer;
126807171f21SGeorge Rimar     }
126907171f21SGeorge Rimar 
127007171f21SGeorge Rimar     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
127107171f21SGeorge Rimar   }
127210416564SRui Ueyama   return Cmd;
12730659800eSGeorge Rimar }
12740659800eSGeorge Rimar 
1275a2496cbeSGeorge Rimar InputSectionDescription *
1276a2496cbeSGeorge Rimar ScriptParser::readInputSectionDescription(StringRef Tok) {
12770659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
12780659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1279a2496cbeSGeorge Rimar   if (Tok == "KEEP") {
1280e7282797SDavide Italiano     expect("(");
1281a2496cbeSGeorge Rimar     StringRef FilePattern = next();
1282a2496cbeSGeorge Rimar     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
12830ed42b0cSDavide Italiano     expect(")");
1284cf43f179SEugene Leviant     Opt.KeptSections.push_back(Cmd);
128510416564SRui Ueyama     return Cmd;
128610416564SRui Ueyama   }
1287a2496cbeSGeorge Rimar   return readInputSectionRules(Tok);
12880659800eSGeorge Rimar }
12890659800eSGeorge Rimar 
129003fc010eSGeorge Rimar void ScriptParser::readSort() {
129103fc010eSGeorge Rimar   expect("(");
129203fc010eSGeorge Rimar   expect("CONSTRUCTORS");
129303fc010eSGeorge Rimar   expect(")");
129403fc010eSGeorge Rimar }
129503fc010eSGeorge Rimar 
1296eefa758eSGeorge Rimar Expr ScriptParser::readAssert() {
1297eefa758eSGeorge Rimar   expect("(");
1298eefa758eSGeorge Rimar   Expr E = readExpr();
1299eefa758eSGeorge Rimar   expect(",");
1300cd574a5eSGeorge Rimar   StringRef Msg = unquote(next());
1301eefa758eSGeorge Rimar   expect(")");
1302eefa758eSGeorge Rimar   return [=](uint64_t Dot) {
1303eefa758eSGeorge Rimar     uint64_t V = E(Dot);
1304eefa758eSGeorge Rimar     if (!V)
1305eefa758eSGeorge Rimar       error(Msg);
1306eefa758eSGeorge Rimar     return V;
1307eefa758eSGeorge Rimar   };
1308eefa758eSGeorge Rimar }
1309eefa758eSGeorge Rimar 
131025150e8bSRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
131125150e8bSRui Ueyama // alias for =fillexp section attribute, which is different from
131225150e8bSRui Ueyama // what GNU linkers do.
131325150e8bSRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1314ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readFill() {
1315ff1f29e0SGeorge Rimar   expect("(");
1316ff1f29e0SGeorge Rimar   std::vector<uint8_t> V = readOutputSectionFiller(next());
1317ff1f29e0SGeorge Rimar   expect(")");
1318ff1f29e0SGeorge Rimar   expect(";");
1319ff1f29e0SGeorge Rimar   return V;
1320ff1f29e0SGeorge Rimar }
1321ff1f29e0SGeorge Rimar 
132210416564SRui Ueyama OutputSectionCommand *
132310416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1324076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
132558e5c4dcSGeorge Rimar 
132658e5c4dcSGeorge Rimar   // Read an address expression.
132758e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
132858e5c4dcSGeorge Rimar   if (peek() != ":")
132958e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
133058e5c4dcSGeorge Rimar 
13318e3b38abSDenis Protivensky   expect(":");
1332246f681eSDavide Italiano 
13338ceadb38SGeorge Rimar   if (skip("AT"))
1334b71d6f7aSEugene Leviant     Cmd->LMAExpr = readParenExpr();
1335630c6179SGeorge Rimar   if (skip("ALIGN"))
13366ad7dfccSRui Ueyama     Cmd->AlignExpr = readParenExpr();
1337db24d9c3SGeorge Rimar   if (skip("SUBALIGN"))
1338db24d9c3SGeorge Rimar     Cmd->SubalignExpr = readParenExpr();
1339630c6179SGeorge Rimar 
1340246f681eSDavide Italiano   // Parse constraints.
1341246f681eSDavide Italiano   if (skip("ONLY_IF_RO"))
1342efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
1343246f681eSDavide Italiano   if (skip("ONLY_IF_RW"))
1344efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
13458e3b38abSDenis Protivensky   expect("{");
13468ec77e64SRui Ueyama 
1347025d59b1SRui Ueyama   while (!Error && !skip("}")) {
1348ceabe80eSEugene Leviant     StringRef Tok = next();
1349db741e72SEugene Leviant     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
1350ceabe80eSEugene Leviant       Cmd->Commands.emplace_back(Assignment);
1351e38cbab5SGeorge Rimar     else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1352e38cbab5SGeorge Rimar       Cmd->Commands.emplace_back(Data);
1353ff1f29e0SGeorge Rimar     else if (Tok == "FILL")
1354ff1f29e0SGeorge Rimar       Cmd->Filler = readFill();
1355ceabe80eSEugene Leviant     else if (Tok == "SORT")
135603fc010eSGeorge Rimar       readSort();
1357a2496cbeSGeorge Rimar     else if (peek() == "(")
1358a2496cbeSGeorge Rimar       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1359ceabe80eSEugene Leviant     else
1360ceabe80eSEugene Leviant       setError("unknown command " + Tok);
13618e3b38abSDenis Protivensky   }
1362076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
13634ebc5620SGeorge Rimar 
13644ebc5620SGeorge Rimar   if (skip("="))
13654ebc5620SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next());
13664ebc5620SGeorge Rimar   else if (peek().startswith("="))
1367ff1f29e0SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next().drop_front());
13684ebc5620SGeorge Rimar 
136910416564SRui Ueyama   return Cmd;
1370f71caa2bSRui Ueyama }
13718ec77e64SRui Ueyama 
13722c8f1f04SRui Ueyama // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
13732c8f1f04SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
13742c8f1f04SRui Ueyama //
13752c8f1f04SRui Ueyama // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
13762c8f1f04SRui Ueyama // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
13772c8f1f04SRui Ueyama // as 32-bit big-endian values. We will do the same as ld.gold does
13782c8f1f04SRui Ueyama // because it's simpler than what ld.bfd does.
1379ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1380965827d6SRui Ueyama   uint32_t V;
1381ff1f29e0SGeorge Rimar   if (Tok.getAsInteger(0, V)) {
1382965827d6SRui Ueyama     setError("invalid filler expression: " + Tok);
1383f71caa2bSRui Ueyama     return {};
1384e2ee72b5SGeorge Rimar   }
1385965827d6SRui Ueyama   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
13868e3b38abSDenis Protivensky }
13878e3b38abSDenis Protivensky 
1388a35e39caSPetr Hosek SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1389a31c91b1SEugene Leviant   expect("(");
1390174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
1391a35e39caSPetr Hosek   Cmd->Provide = Provide;
1392174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
1393a31c91b1SEugene Leviant   expect(")");
1394a31c91b1SEugene Leviant   expect(";");
139510416564SRui Ueyama   return Cmd;
1396eda81a1bSEugene Leviant }
1397eda81a1bSEugene Leviant 
1398db741e72SEugene Leviant SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1399db741e72SEugene Leviant                                                         bool MakeAbsolute) {
1400ceabe80eSEugene Leviant   SymbolAssignment *Cmd = nullptr;
1401ceabe80eSEugene Leviant   if (peek() == "=" || peek() == "+=") {
1402ceabe80eSEugene Leviant     Cmd = readAssignment(Tok);
1403ceabe80eSEugene Leviant     expect(";");
1404ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE") {
1405a35e39caSPetr Hosek     Cmd = readProvideHidden(true, false);
1406a35e39caSPetr Hosek   } else if (Tok == "HIDDEN") {
1407a35e39caSPetr Hosek     Cmd = readProvideHidden(false, true);
1408ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE_HIDDEN") {
1409a35e39caSPetr Hosek     Cmd = readProvideHidden(true, true);
1410ceabe80eSEugene Leviant   }
1411db741e72SEugene Leviant   if (Cmd && MakeAbsolute)
1412db741e72SEugene Leviant     Cmd->IsAbsolute = true;
1413ceabe80eSEugene Leviant   return Cmd;
1414ceabe80eSEugene Leviant }
1415ceabe80eSEugene Leviant 
141630835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
141730835ea4SGeorge Rimar   if (S == ".")
141830835ea4SGeorge Rimar     return Dot;
1419884e786dSGeorge Rimar   return ScriptBase->getSymbolValue(S);
1420e32a3598SGeorge Rimar }
1421e32a3598SGeorge Rimar 
142230835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
142330835ea4SGeorge Rimar   StringRef Op = next();
1424db741e72SEugene Leviant   bool IsAbsolute = false;
1425db741e72SEugene Leviant   Expr E;
142630835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
1427db741e72SEugene Leviant   if (skip("ABSOLUTE")) {
1428db741e72SEugene Leviant     E = readParenExpr();
1429db741e72SEugene Leviant     IsAbsolute = true;
1430db741e72SEugene Leviant   } else {
1431db741e72SEugene Leviant     E = readExpr();
1432db741e72SEugene Leviant   }
143330835ea4SGeorge Rimar   if (Op == "+=")
143430835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1435db741e72SEugene Leviant   return new SymbolAssignment(Name, E, IsAbsolute);
143630835ea4SGeorge Rimar }
143730835ea4SGeorge Rimar 
143830835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
143930835ea4SGeorge Rimar // script expression.
144030835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
144130835ea4SGeorge Rimar 
144236c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
144336c1cd23SRui Ueyama   if (Op == "*")
144436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
144536c1cd23SRui Ueyama   if (Op == "/") {
144636c1cd23SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
144736c1cd23SRui Ueyama       uint64_t RHS = R(Dot);
144836c1cd23SRui Ueyama       if (RHS == 0) {
144936c1cd23SRui Ueyama         error("division by zero");
145036c1cd23SRui Ueyama         return 0;
145136c1cd23SRui Ueyama       }
145236c1cd23SRui Ueyama       return L(Dot) / RHS;
145336c1cd23SRui Ueyama     };
145436c1cd23SRui Ueyama   }
145536c1cd23SRui Ueyama   if (Op == "+")
145636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
145736c1cd23SRui Ueyama   if (Op == "-")
145836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1459c8ccd1f1SGeorge Rimar   if (Op == "<<")
1460c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1461c8ccd1f1SGeorge Rimar   if (Op == ">>")
1462c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
146336c1cd23SRui Ueyama   if (Op == "<")
146436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
146536c1cd23SRui Ueyama   if (Op == ">")
146636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
146736c1cd23SRui Ueyama   if (Op == ">=")
146836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
146936c1cd23SRui Ueyama   if (Op == "<=")
147036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
147136c1cd23SRui Ueyama   if (Op == "==")
147236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
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); };
1477cc3dd629SRafael Espindola   if (Op == "|")
1478cc3dd629SRafael Espindola     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
147936c1cd23SRui Ueyama   llvm_unreachable("invalid operator");
148036c1cd23SRui Ueyama }
148136c1cd23SRui Ueyama 
1482708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
1483708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
1484708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1485708019c4SRui Ueyama   while (!atEOF() && !Error) {
1486708019c4SRui Ueyama     // Read an operator and an expression.
1487708019c4SRui Ueyama     StringRef Op1 = peek();
1488708019c4SRui Ueyama     if (Op1 == "?")
1489708019c4SRui Ueyama       return readTernary(Lhs);
1490708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
1491a31c91b1SEugene Leviant       break;
1492a31c91b1SEugene Leviant     next();
1493708019c4SRui Ueyama     Expr Rhs = readPrimary();
1494708019c4SRui Ueyama 
1495708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
1496708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
1497708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
1498708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
1499708019c4SRui Ueyama     while (!atEOF()) {
1500708019c4SRui Ueyama       StringRef Op2 = peek();
1501708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
1502eda81a1bSEugene Leviant         break;
1503708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
1504eda81a1bSEugene Leviant     }
1505708019c4SRui Ueyama 
1506708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
1507708019c4SRui Ueyama   }
1508708019c4SRui Ueyama   return Lhs;
1509708019c4SRui Ueyama }
1510708019c4SRui Ueyama 
1511708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
1512e2cc07bcSMichael J. Spencer   if (S == "COMMONPAGESIZE")
1513708019c4SRui Ueyama     return Target->PageSize;
1514e2cc07bcSMichael J. Spencer   if (S == "MAXPAGESIZE")
1515997f8838SPetr Hosek     return Config->MaxPageSize;
1516708019c4SRui Ueyama   error("unknown constant: " + S);
1517708019c4SRui Ueyama   return 0;
1518708019c4SRui Ueyama }
1519708019c4SRui Ueyama 
1520626e0b08SRui Ueyama // Parses Tok as an integer. Returns true if successful.
1521626e0b08SRui Ueyama // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1522626e0b08SRui Ueyama // and decimal numbers. Decimal numbers may have "K" (kilo) or
1523626e0b08SRui Ueyama // "M" (mega) prefixes.
15249f2f7ad9SGeorge Rimar static bool readInteger(StringRef Tok, uint64_t &Result) {
1525eaeafb2bSSimon Atanasyan   if (Tok.startswith("-")) {
1526eaeafb2bSSimon Atanasyan     if (!readInteger(Tok.substr(1), Result))
1527eaeafb2bSSimon Atanasyan       return false;
1528eaeafb2bSSimon Atanasyan     Result = -Result;
1529eaeafb2bSSimon Atanasyan     return true;
1530eaeafb2bSSimon Atanasyan   }
15319f2f7ad9SGeorge Rimar   if (Tok.startswith_lower("0x"))
15329f2f7ad9SGeorge Rimar     return !Tok.substr(2).getAsInteger(16, Result);
15339f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("H"))
15349f2f7ad9SGeorge Rimar     return !Tok.drop_back().getAsInteger(16, Result);
15359f2f7ad9SGeorge Rimar 
15369f2f7ad9SGeorge Rimar   int Suffix = 1;
15379f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("K")) {
15389f2f7ad9SGeorge Rimar     Suffix = 1024;
15399f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
15409f2f7ad9SGeorge Rimar   } else if (Tok.endswith_lower("M")) {
15419f2f7ad9SGeorge Rimar     Suffix = 1024 * 1024;
15429f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
15439f2f7ad9SGeorge Rimar   }
15449f2f7ad9SGeorge Rimar   if (Tok.getAsInteger(10, Result))
15459f2f7ad9SGeorge Rimar     return false;
15469f2f7ad9SGeorge Rimar   Result *= Suffix;
15479f2f7ad9SGeorge Rimar   return true;
15489f2f7ad9SGeorge Rimar }
15499f2f7ad9SGeorge Rimar 
1550e38cbab5SGeorge Rimar BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1551e38cbab5SGeorge Rimar   int Size = StringSwitch<unsigned>(Tok)
1552e38cbab5SGeorge Rimar                  .Case("BYTE", 1)
1553e38cbab5SGeorge Rimar                  .Case("SHORT", 2)
1554e38cbab5SGeorge Rimar                  .Case("LONG", 4)
1555e38cbab5SGeorge Rimar                  .Case("QUAD", 8)
1556e38cbab5SGeorge Rimar                  .Default(-1);
1557e38cbab5SGeorge Rimar   if (Size == -1)
1558e38cbab5SGeorge Rimar     return nullptr;
1559e38cbab5SGeorge Rimar 
1560e38cbab5SGeorge Rimar   expect("(");
1561e38cbab5SGeorge Rimar   uint64_t Val = 0;
1562e38cbab5SGeorge Rimar   StringRef S = next();
1563e38cbab5SGeorge Rimar   if (!readInteger(S, Val))
1564e38cbab5SGeorge Rimar     setError("unexpected value: " + S);
1565e38cbab5SGeorge Rimar   expect(")");
1566e38cbab5SGeorge Rimar   return new BytesDataCommand(Val, Size);
1567e38cbab5SGeorge Rimar }
1568e38cbab5SGeorge Rimar 
1569b71d6f7aSEugene Leviant StringRef ScriptParser::readParenLiteral() {
1570b71d6f7aSEugene Leviant   expect("(");
1571b71d6f7aSEugene Leviant   StringRef Tok = next();
1572b71d6f7aSEugene Leviant   expect(")");
1573b71d6f7aSEugene Leviant   return Tok;
1574b71d6f7aSEugene Leviant }
1575b71d6f7aSEugene Leviant 
1576708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
15776ad7dfccSRui Ueyama   if (peek() == "(")
15786ad7dfccSRui Ueyama     return readParenExpr();
1579708019c4SRui Ueyama 
15806ad7dfccSRui Ueyama   StringRef Tok = next();
1581708019c4SRui Ueyama 
1582eaeafb2bSSimon Atanasyan   if (Tok == "~") {
1583eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1584eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return ~E(Dot); };
1585eaeafb2bSSimon Atanasyan   }
1586eaeafb2bSSimon Atanasyan   if (Tok == "-") {
1587eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1588eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return -E(Dot); };
1589eaeafb2bSSimon Atanasyan   }
1590eaeafb2bSSimon Atanasyan 
1591708019c4SRui Ueyama   // Built-in functions are parsed here.
1592708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
159396659df0SGeorge Rimar   if (Tok == "ADDR") {
1594b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1595884e786dSGeorge Rimar     return
1596884e786dSGeorge Rimar         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
159796659df0SGeorge Rimar   }
1598b71d6f7aSEugene Leviant   if (Tok == "LOADADDR") {
1599b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1600b71d6f7aSEugene Leviant     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1601b71d6f7aSEugene Leviant   }
1602eefa758eSGeorge Rimar   if (Tok == "ASSERT")
1603eefa758eSGeorge Rimar     return readAssert();
1604708019c4SRui Ueyama   if (Tok == "ALIGN") {
16056ad7dfccSRui Ueyama     Expr E = readParenExpr();
1606708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1607708019c4SRui Ueyama   }
1608708019c4SRui Ueyama   if (Tok == "CONSTANT") {
1609b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1610b71d6f7aSEugene Leviant     return [=](uint64_t Dot) { return getConstant(Name); };
1611708019c4SRui Ueyama   }
1612f34f45fdSGeorge Rimar   if (Tok == "DEFINED") {
1613f34f45fdSGeorge Rimar     expect("(");
1614f34f45fdSGeorge Rimar     StringRef Tok = next();
1615f34f45fdSGeorge Rimar     expect(")");
1616f2821028SGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
1617f34f45fdSGeorge Rimar   }
161854c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
161954c145ceSRafael Espindola     expect("(");
162054c145ceSRafael Espindola     next();
162154c145ceSRafael Espindola     expect(",");
16228c658bf8SGeorge Rimar     Expr E = readExpr();
162354c145ceSRafael Espindola     expect(")");
16248c658bf8SGeorge Rimar     return [=](uint64_t Dot) { return E(Dot); };
162554c145ceSRafael Espindola   }
1626708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
1627708019c4SRui Ueyama     expect("(");
1628708019c4SRui Ueyama     Expr E = readExpr();
1629708019c4SRui Ueyama     expect(",");
1630708019c4SRui Ueyama     readExpr();
1631708019c4SRui Ueyama     expect(")");
1632f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1633708019c4SRui Ueyama   }
1634708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
1635708019c4SRui Ueyama     expect("(");
1636708019c4SRui Ueyama     expect(".");
1637708019c4SRui Ueyama     expect(")");
1638708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
1639708019c4SRui Ueyama   }
1640276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
1641276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1642276b4e64SGeorge Rimar   // the next page boundary for simplicity.
1643276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
1644276b4e64SGeorge Rimar     expect("(");
164597bdc722SRafael Espindola     readExpr();
1646276b4e64SGeorge Rimar     expect(",");
1647276b4e64SGeorge Rimar     readExpr();
1648276b4e64SGeorge Rimar     expect(")");
1649276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1650276b4e64SGeorge Rimar   }
16519e69450eSGeorge Rimar   if (Tok == "SIZEOF") {
1652b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
1653884e786dSGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
16549e69450eSGeorge Rimar   }
165536fac7f0SEugene Leviant   if (Tok == "ALIGNOF") {
1656b71d6f7aSEugene Leviant     StringRef Name = readParenLiteral();
165736fac7f0SEugene Leviant     return
165836fac7f0SEugene Leviant         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
165936fac7f0SEugene Leviant   }
1660e32a3598SGeorge Rimar   if (Tok == "SIZEOF_HEADERS")
1661884e786dSGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1662708019c4SRui Ueyama 
16639f2f7ad9SGeorge Rimar   // Tok is a literal number.
16649f2f7ad9SGeorge Rimar   uint64_t V;
16659f2f7ad9SGeorge Rimar   if (readInteger(Tok, V))
16669f2f7ad9SGeorge Rimar     return [=](uint64_t Dot) { return V; };
16679f2f7ad9SGeorge Rimar 
16689f2f7ad9SGeorge Rimar   // Tok is a symbol name.
166930835ea4SGeorge Rimar   if (Tok != "." && !isValidCIdentifier(Tok))
1670708019c4SRui Ueyama     setError("malformed number: " + Tok);
167130835ea4SGeorge Rimar   return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
1672a9c5a528SGeorge Rimar }
1673708019c4SRui Ueyama 
1674708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
1675708019c4SRui Ueyama   next();
1676708019c4SRui Ueyama   Expr L = readExpr();
1677708019c4SRui Ueyama   expect(":");
1678708019c4SRui Ueyama   Expr R = readExpr();
1679708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1680708019c4SRui Ueyama }
1681708019c4SRui Ueyama 
16826ad7dfccSRui Ueyama Expr ScriptParser::readParenExpr() {
16836ad7dfccSRui Ueyama   expect("(");
16846ad7dfccSRui Ueyama   Expr E = readExpr();
16856ad7dfccSRui Ueyama   expect(")");
16866ad7dfccSRui Ueyama   return E;
16876ad7dfccSRui Ueyama }
16886ad7dfccSRui Ueyama 
1689bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1690bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
1691bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
1692bbe38602SEugene Leviant     StringRef Tok = next();
1693bbe38602SEugene Leviant     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1694bbe38602SEugene Leviant     if (Tok.empty()) {
1695bbe38602SEugene Leviant       setError("section header name is empty");
1696bbe38602SEugene Leviant       break;
1697bbe38602SEugene Leviant     }
1698bbe38602SEugene Leviant     Phdrs.push_back(Tok);
1699bbe38602SEugene Leviant   }
1700bbe38602SEugene Leviant   return Phdrs;
1701bbe38602SEugene Leviant }
1702bbe38602SEugene Leviant 
1703bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
1704bbe38602SEugene Leviant   StringRef Tok = next();
1705b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
1706b0f6c590SRui Ueyama                      .Case("PT_NULL", PT_NULL)
1707b0f6c590SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
1708b0f6c590SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1709b0f6c590SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
1710b0f6c590SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
1711b0f6c590SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
1712b0f6c590SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
1713b0f6c590SRui Ueyama                      .Case("PT_TLS", PT_TLS)
1714b0f6c590SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1715b0f6c590SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1716b0f6c590SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1717b0f6c590SRui Ueyama                      .Default(-1);
1718bbe38602SEugene Leviant 
1719b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1720b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1721b0f6c590SRui Ueyama     return PT_NULL;
1722b0f6c590SRui Ueyama   }
1723b0f6c590SRui Ueyama   return Ret;
1724bbe38602SEugene Leviant }
1725bbe38602SEugene Leviant 
172695769b4aSRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
172720b6598cSGeorge Rimar   // Identifiers start at 2 because 0 and 1 are reserved
172820b6598cSGeorge Rimar   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
172920b6598cSGeorge Rimar   size_t VersionId = Config->VersionDefinitions.size() + 2;
173020b6598cSGeorge Rimar   Config->VersionDefinitions.push_back({VerStr, VersionId});
173120b6598cSGeorge Rimar 
173220b6598cSGeorge Rimar   if (skip("global:") || peek() != "local:")
173320b6598cSGeorge Rimar     readGlobal(VerStr);
173420b6598cSGeorge Rimar   if (skip("local:"))
173520b6598cSGeorge Rimar     readLocal();
173620b6598cSGeorge Rimar   expect("}");
173720b6598cSGeorge Rimar 
173820b6598cSGeorge Rimar   // Each version may have a parent version. For example, "Ver2" defined as
173920b6598cSGeorge Rimar   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
174020b6598cSGeorge Rimar   // version hierarchy is, probably against your instinct, purely for human; the
174120b6598cSGeorge Rimar   // runtime doesn't care about them at all. In LLD, we simply skip the token.
174220b6598cSGeorge Rimar   if (!VerStr.empty() && peek() != ";")
174320b6598cSGeorge Rimar     next();
174420b6598cSGeorge Rimar   expect(";");
174520b6598cSGeorge Rimar }
174620b6598cSGeorge Rimar 
174720b6598cSGeorge Rimar void ScriptParser::readLocal() {
174820b6598cSGeorge Rimar   Config->DefaultSymbolVersion = VER_NDX_LOCAL;
174920b6598cSGeorge Rimar   expect("*");
175020b6598cSGeorge Rimar   expect(";");
175120b6598cSGeorge Rimar }
175220b6598cSGeorge Rimar 
175320b6598cSGeorge Rimar void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1754cd574a5eSGeorge Rimar   expect("\"C++\"");
175520b6598cSGeorge Rimar   expect("{");
175620b6598cSGeorge Rimar 
175720b6598cSGeorge Rimar   for (;;) {
175820b6598cSGeorge Rimar     if (peek() == "}" || Error)
175920b6598cSGeorge Rimar       break;
1760cd574a5eSGeorge Rimar     bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1761cd574a5eSGeorge Rimar     Globals->push_back({unquote(next()), true, HasWildcard});
176220b6598cSGeorge Rimar     expect(";");
176320b6598cSGeorge Rimar   }
176420b6598cSGeorge Rimar 
176520b6598cSGeorge Rimar   expect("}");
176620b6598cSGeorge Rimar   expect(";");
176720b6598cSGeorge Rimar }
176820b6598cSGeorge Rimar 
176920b6598cSGeorge Rimar void ScriptParser::readGlobal(StringRef VerStr) {
177020b6598cSGeorge Rimar   std::vector<SymbolVersion> *Globals;
177120b6598cSGeorge Rimar   if (VerStr.empty())
177220b6598cSGeorge Rimar     Globals = &Config->VersionScriptGlobals;
177320b6598cSGeorge Rimar   else
177420b6598cSGeorge Rimar     Globals = &Config->VersionDefinitions.back().Globals;
177520b6598cSGeorge Rimar 
177620b6598cSGeorge Rimar   for (;;) {
177720b6598cSGeorge Rimar     if (skip("extern"))
177820b6598cSGeorge Rimar       readExtern(Globals);
177920b6598cSGeorge Rimar 
178020b6598cSGeorge Rimar     StringRef Cur = peek();
178120b6598cSGeorge Rimar     if (Cur == "}" || Cur == "local:" || Error)
178220b6598cSGeorge Rimar       return;
178320b6598cSGeorge Rimar     next();
1784cd574a5eSGeorge Rimar     Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
178520b6598cSGeorge Rimar     expect(";");
178620b6598cSGeorge Rimar   }
178720b6598cSGeorge Rimar }
178820b6598cSGeorge Rimar 
178916b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
179016b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
179116b0cc9eSSimon Atanasyan     return false;
179216b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
179316b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
179416b0cc9eSSimon Atanasyan       return true;
179516b0cc9eSSimon Atanasyan   return false;
179616b0cc9eSSimon Atanasyan }
179716b0cc9eSSimon Atanasyan 
179807320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
179916b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
180020b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
180120b6598cSGeorge Rimar }
180220b6598cSGeorge Rimar 
180320b6598cSGeorge Rimar void elf::readVersionScript(MemoryBufferRef MB) {
180420b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), false).readVersionScript();
1805f7c5fbb1SRui Ueyama }
18061ebc8ed7SRui Ueyama 
180707320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
180807320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
180907320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
181007320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1811