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;
41f7c5fbb1SRui Ueyama using namespace lld;
42e0df00b9SRafael Espindola using namespace lld::elf;
43f7c5fbb1SRui Ueyama 
44884e786dSGeorge Rimar LinkerScriptBase *elf::ScriptBase;
4507320e40SRui Ueyama ScriptConfiguration *elf::ScriptConfig;
46717677afSRui Ueyama 
476c55f0e3SGeorge Rimar template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
481602421cSRui Ueyama   Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
491602421cSRui Ueyama   Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
501602421cSRui Ueyama   Cmd->Sym = Sym->body();
5120d03194SEugene Leviant 
5220d03194SEugene Leviant   // If we have no SECTIONS then we don't have '.' and don't call
5320d03194SEugene Leviant   // assignAddresses(). We calculate symbol value immediately in this case.
5420d03194SEugene Leviant   if (!ScriptConfig->HasSections)
5520d03194SEugene Leviant     cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
56ceabe80eSEugene Leviant }
57ceabe80eSEugene Leviant 
580c70d3ccSRui Ueyama template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
59e1937bb5SGeorge Rimar   Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
60e1937bb5SGeorge Rimar       Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
611602421cSRui Ueyama   Cmd->Sym = Sym->body();
62ceabe80eSEugene Leviant }
63ceabe80eSEugene Leviant 
64db741e72SEugene Leviant template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
65db741e72SEugene Leviant   if (Cmd->IsAbsolute)
66db741e72SEugene Leviant     addRegular<ELFT>(Cmd);
67db741e72SEugene Leviant   else
68db741e72SEugene Leviant     addSynthetic<ELFT>(Cmd);
69db741e72SEugene Leviant }
701602421cSRui Ueyama // If a symbol was in PROVIDE(), we need to define it only when
711602421cSRui Ueyama // it is an undefined symbol.
721602421cSRui Ueyama template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
731602421cSRui Ueyama   if (Cmd->Name == ".")
74ceabe80eSEugene Leviant     return false;
751602421cSRui Ueyama   if (!Cmd->Provide)
76ceabe80eSEugene Leviant     return true;
771602421cSRui Ueyama   SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
781602421cSRui Ueyama   return B && B->isUndefined();
79ceabe80eSEugene Leviant }
80ceabe80eSEugene Leviant 
81076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
82076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
83076fe157SGeorge Rimar }
84076fe157SGeorge Rimar 
85076fe157SGeorge Rimar bool OutputSectionCommand::classof(const BaseCommand *C) {
86076fe157SGeorge Rimar   return C->Kind == OutputSectionKind;
87076fe157SGeorge Rimar }
88076fe157SGeorge Rimar 
89eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
90eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
91eea3114fSGeorge Rimar }
92eea3114fSGeorge Rimar 
93eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
94eefa758eSGeorge Rimar   return C->Kind == AssertKind;
95eefa758eSGeorge Rimar }
96eefa758eSGeorge Rimar 
9736a153cdSRui Ueyama template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
98eea3114fSGeorge Rimar   return !S || !S->Live;
99717677afSRui Ueyama }
100717677afSRui Ueyama 
101f34d0e08SRui Ueyama template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
102f34d0e08SRui Ueyama template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
103f34d0e08SRui Ueyama 
10407320e40SRui Ueyama template <class ELFT>
10507320e40SRui Ueyama bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
106c91930a1SGeorge Rimar   for (Regex *Re : Opt.KeptSections)
107042a3f20SRafael Espindola     if (Re->match(S->Name))
108eea3114fSGeorge Rimar       return true;
109eea3114fSGeorge Rimar   return false;
110eea3114fSGeorge Rimar }
111eea3114fSGeorge Rimar 
112575208caSGeorge Rimar static bool comparePriority(InputSectionData *A, InputSectionData *B) {
113575208caSGeorge Rimar   return getPriority(A->Name) < getPriority(B->Name);
114575208caSGeorge Rimar }
115575208caSGeorge Rimar 
116c0028d3dSRafael Espindola static bool compareName(InputSectionData *A, InputSectionData *B) {
117042a3f20SRafael Espindola   return A->Name < B->Name;
1180702c4e8SGeorge Rimar }
119742c3836SRui Ueyama 
120c0028d3dSRafael Espindola static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
121742c3836SRui Ueyama   // ">" is not a mistake. Larger alignments are placed before smaller
122742c3836SRui Ueyama   // alignments in order to reduce the amount of padding necessary.
123742c3836SRui Ueyama   // This is compatible with GNU.
124742c3836SRui Ueyama   return A->Alignment > B->Alignment;
125742c3836SRui Ueyama }
126742c3836SRui Ueyama 
127c0028d3dSRafael Espindola static std::function<bool(InputSectionData *, InputSectionData *)>
128be394db3SGeorge Rimar getComparator(SortSectionPolicy K) {
129be394db3SGeorge Rimar   switch (K) {
130be394db3SGeorge Rimar   case SortSectionPolicy::Alignment:
131c0028d3dSRafael Espindola     return compareAlignment;
132be394db3SGeorge Rimar   case SortSectionPolicy::Name:
133be394db3SGeorge Rimar     return compareName;
134be394db3SGeorge Rimar   case SortSectionPolicy::Priority:
135be394db3SGeorge Rimar     return comparePriority;
136be394db3SGeorge Rimar   default:
137be394db3SGeorge Rimar     llvm_unreachable("unknown sort policy");
138be394db3SGeorge Rimar   }
139742c3836SRui Ueyama }
1400702c4e8SGeorge Rimar 
14148c3f1ceSRui Ueyama template <class ELFT>
142e71a3f8aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
14306ae6836SGeorge Rimar                              ConstraintKind Kind) {
1448f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
1458f66df92SGeorge Rimar     return true;
146e746e52cSRafael Espindola   bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
147d3190795SRafael Espindola     auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
148e746e52cSRafael Espindola     return Sec->getSectionHdr()->sh_flags & SHF_WRITE;
14906ae6836SGeorge Rimar   });
150e746e52cSRafael Espindola   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
151e746e52cSRafael Espindola          (!IsRW && Kind == ConstraintKind::ReadOnly);
15206ae6836SGeorge Rimar }
15306ae6836SGeorge Rimar 
15407171f21SGeorge Rimar static void sortSections(InputSectionData **Begin, InputSectionData **End,
155ee924709SRui Ueyama                          SortSectionPolicy K) {
156ee924709SRui Ueyama   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
15707171f21SGeorge Rimar     std::stable_sort(Begin, End, getComparator(K));
158ee924709SRui Ueyama }
159ee924709SRui Ueyama 
160d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
161be94e1b6SRafael Espindola template <class ELFT>
162e71a3f8aSRafael Espindola void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
1634dc07becSRui Ueyama   // Collects all sections that satisfy constraints of I
1644dc07becSRui Ueyama   // and attach them to I.
1654dc07becSRui Ueyama   for (SectionPattern &Pat : I->SectionPatterns) {
16607171f21SGeorge Rimar     size_t SizeBefore = I->Sections.size();
167395281cfSGeorge Rimar     for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
1683ff27f49SRui Ueyama       StringRef Filename = sys::path::filename(F->getName());
169f135f0ecSRafael Espindola       if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
1703ff27f49SRui Ueyama         continue;
1714dc07becSRui Ueyama 
172be94e1b6SRafael Espindola       for (InputSectionBase<ELFT> *S : F->getSections())
173f135f0ecSRafael Espindola         if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
174d3190795SRafael Espindola           I->Sections.push_back(S);
175f135f0ecSRafael Espindola       if (Pat.SectionRe.match("COMMON"))
176d3190795SRafael Espindola         I->Sections.push_back(CommonInputSection<ELFT>::X);
177395281cfSGeorge Rimar     }
178d3190795SRafael Espindola 
179ee924709SRui Ueyama     // Sort sections as instructed by SORT-family commands and --sort-section
180ee924709SRui Ueyama     // option. Because SORT-family commands can be nested at most two depth
181ee924709SRui Ueyama     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
182ee924709SRui Ueyama     // line option is respected even if a SORT command is given, the exact
183ee924709SRui Ueyama     // behavior we have here is a bit complicated. Here are the rules.
184ee924709SRui Ueyama     //
185ee924709SRui Ueyama     // 1. If two SORT commands are given, --sort-section is ignored.
186ee924709SRui Ueyama     // 2. If one SORT command is given, and if it is not SORT_NONE,
187ee924709SRui Ueyama     //    --sort-section is handled as an inner SORT command.
188ee924709SRui Ueyama     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
189ee924709SRui Ueyama     // 4. If no SORT command is given, sort according to --sort-section.
19007171f21SGeorge Rimar     InputSectionData **Begin = I->Sections.data() + SizeBefore;
19107171f21SGeorge Rimar     InputSectionData **End = I->Sections.data() + I->Sections.size();
19207171f21SGeorge Rimar     if (Pat.SortOuter != SortSectionPolicy::None) {
19307171f21SGeorge Rimar       if (Pat.SortInner == SortSectionPolicy::Default)
19407171f21SGeorge Rimar         sortSections(Begin, End, Config->SortSection);
195ee924709SRui Ueyama       else
19607171f21SGeorge Rimar         sortSections(Begin, End, Pat.SortInner);
19707171f21SGeorge Rimar       sortSections(Begin, End, Pat.SortOuter);
19807171f21SGeorge Rimar     }
199ee924709SRui Ueyama   }
200d3190795SRafael Espindola 
201d3190795SRafael Espindola   // We do not add duplicate input sections, so mark them with a dummy output
202d3190795SRafael Espindola   // section for now.
203d3190795SRafael Espindola   for (InputSectionData *S : I->Sections) {
204d3190795SRafael Espindola     auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
205d3190795SRafael Espindola     S2->OutSec = (OutputSectionBase<ELFT> *)-1;
206d3190795SRafael Espindola   }
207be94e1b6SRafael Espindola }
208be94e1b6SRafael Espindola 
209be94e1b6SRafael Espindola template <class ELFT>
210be94e1b6SRafael Espindola void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
211be94e1b6SRafael Espindola   for (InputSectionBase<ELFT> *S : V) {
212be94e1b6SRafael Espindola     S->Live = false;
213be94e1b6SRafael Espindola     reportDiscarded(S);
214be94e1b6SRafael Espindola   }
215be94e1b6SRafael Espindola }
216be94e1b6SRafael Espindola 
21706ae6836SGeorge Rimar template <class ELFT>
2180b9ce6a4SRui Ueyama std::vector<InputSectionBase<ELFT> *>
21906ae6836SGeorge Rimar LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
2200b9ce6a4SRui Ueyama   std::vector<InputSectionBase<ELFT> *> Ret;
221e7f912cdSRui Ueyama 
22206ae6836SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
2237c3ff2ebSRafael Espindola     auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
2247c3ff2ebSRafael Espindola     if (!Cmd)
2250b9ce6a4SRui Ueyama       continue;
226e71a3f8aSRafael Espindola     computeInputSections(Cmd);
227d3190795SRafael Espindola     for (InputSectionData *S : Cmd->Sections)
228d3190795SRafael Espindola       Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
2290b9ce6a4SRui Ueyama   }
230e71a3f8aSRafael Espindola 
2310b9ce6a4SRui Ueyama   return Ret;
2320b9ce6a4SRui Ueyama }
2330b9ce6a4SRui Ueyama 
234e5d3ca50SPetr Hosek template <class ELFT>
23510897f18SRafael Espindola static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
23610897f18SRafael Espindola                                             StringRef OutsecName) {
23710897f18SRafael Espindola   // When using linker script the merge rules are different.
23810897f18SRafael Espindola   // Unfortunately, linker scripts are name based. This means that expressions
23910897f18SRafael Espindola   // like *(.foo*) can refer to multiple input sections that would normally be
24010897f18SRafael Espindola   // placed in different output sections. We cannot put them in different
24110897f18SRafael Espindola   // output sections or we would produce wrong results for
24210897f18SRafael Espindola   // start = .; *(.foo.*) end = .; *(.bar)
24310897f18SRafael Espindola   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
24410897f18SRafael Espindola   // another. The problem is that there is no way to layout those output
24510897f18SRafael Espindola   // sections such that the .foo sections are the only thing between the
24610897f18SRafael Espindola   // start and end symbols.
24710897f18SRafael Espindola 
24810897f18SRafael Espindola   // An extra annoyance is that we cannot simply disable merging of the contents
24910897f18SRafael Espindola   // of SHF_MERGE sections, but our implementation requires one output section
25010897f18SRafael Espindola   // per "kind" (string or not, which size/aligment).
25110897f18SRafael Espindola   // Fortunately, creating symbols in the middle of a merge section is not
25210897f18SRafael Espindola   // supported by bfd or gold, so we can just create multiple section in that
25310897f18SRafael Espindola   // case.
25410897f18SRafael Espindola   const typename ELFT::Shdr *H = C->getSectionHdr();
25510897f18SRafael Espindola   typedef typename ELFT::uint uintX_t;
25610897f18SRafael Espindola   uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
25710897f18SRafael Espindola 
25810897f18SRafael Espindola   uintX_t Alignment = 0;
25910897f18SRafael Espindola   if (isa<MergeInputSection<ELFT>>(C))
26010897f18SRafael Espindola     Alignment = std::max(H->sh_addralign, H->sh_entsize);
26110897f18SRafael Espindola 
26210897f18SRafael Espindola   return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
26310897f18SRafael Espindola }
26410897f18SRafael Espindola 
26510897f18SRafael Espindola template <class ELFT>
26620d03194SEugene Leviant void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
26720d03194SEugene Leviant                                     InputSectionBase<ELFT> *Sec,
26820d03194SEugene Leviant                                     StringRef Name) {
26928c1597aSRafael Espindola   OutputSectionBase<ELFT> *OutSec;
27028c1597aSRafael Espindola   bool IsNew;
27110897f18SRafael Espindola   std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
27228c1597aSRafael Espindola   if (IsNew)
27328c1597aSRafael Espindola     OutputSections->push_back(OutSec);
27420d03194SEugene Leviant   OutSec->addSection(Sec);
27520d03194SEugene Leviant }
27620d03194SEugene Leviant 
27720d03194SEugene Leviant template <class ELFT>
27820d03194SEugene Leviant void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
27928c1597aSRafael Espindola 
2807c3ff2ebSRafael Espindola   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
2817c3ff2ebSRafael Espindola     auto Iter = Opt.Commands.begin() + I;
2827c3ff2ebSRafael Espindola     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
2832ab5f73dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
2842ab5f73dSRui Ueyama       if (shouldDefine<ELFT>(Cmd))
2852ab5f73dSRui Ueyama         addRegular<ELFT>(Cmd);
2862ab5f73dSRui Ueyama       continue;
2872ab5f73dSRui Ueyama     }
28820d03194SEugene Leviant     if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
28920d03194SEugene Leviant       // If we don't have SECTIONS then output sections have already been
290194470cdSGeorge Rimar       // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
29120d03194SEugene Leviant       // will not be called, so ASSERT should be evaluated now.
29220d03194SEugene Leviant       if (!Opt.HasSections)
29320d03194SEugene Leviant         Cmd->Expression(0);
29420d03194SEugene Leviant       continue;
29520d03194SEugene Leviant     }
2962ab5f73dSRui Ueyama 
297ceabe80eSEugene Leviant     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
2987bd37870SRafael Espindola       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
2997bd37870SRafael Espindola 
30048c3f1ceSRui Ueyama       if (Cmd->Name == "/DISCARD/") {
3017bd37870SRafael Espindola         discard(V);
30248c3f1ceSRui Ueyama         continue;
30348c3f1ceSRui Ueyama       }
3040b9ce6a4SRui Ueyama 
3057c3ff2ebSRafael Espindola       if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
3067c3ff2ebSRafael Espindola         for (InputSectionBase<ELFT> *S : V)
3077c3ff2ebSRafael Espindola           S->OutSec = nullptr;
3087c3ff2ebSRafael Espindola         Opt.Commands.erase(Iter);
309dfbbbc86SGeorge Rimar         --I;
3107c3ff2ebSRafael Espindola         continue;
3117c3ff2ebSRafael Espindola       }
3127c3ff2ebSRafael Espindola 
3137c3ff2ebSRafael Espindola       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
3147c3ff2ebSRafael Espindola         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
3157c3ff2ebSRafael Espindola           if (shouldDefine<ELFT>(OutCmd))
3167c3ff2ebSRafael Espindola             addSymbol<ELFT>(OutCmd);
3177c3ff2ebSRafael Espindola 
31897403d15SEugene Leviant       if (V.empty())
3190b9ce6a4SRui Ueyama         continue;
3200b9ce6a4SRui Ueyama 
321a14b13d8SGeorge Rimar       for (InputSectionBase<ELFT> *Sec : V) {
32220d03194SEugene Leviant         addSection(Factory, Sec, Cmd->Name);
32320d03194SEugene Leviant         if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
324db24d9c3SGeorge Rimar           Sec->Alignment = Subalign;
32520d03194SEugene Leviant       }
326eea3114fSGeorge Rimar     }
32748c3f1ceSRui Ueyama   }
328db24d9c3SGeorge Rimar }
329e63d81bdSEugene Leviant 
33020d03194SEugene Leviant template <class ELFT>
33120d03194SEugene Leviant void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
33220d03194SEugene Leviant   processCommands(Factory);
3330b9ce6a4SRui Ueyama   // Add orphan sections.
33420d03194SEugene Leviant   for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
33520d03194SEugene Leviant     for (InputSectionBase<ELFT> *S : F->getSections())
33620d03194SEugene Leviant       if (!isDiscarded(S) && !S->OutSec)
33720d03194SEugene Leviant         addSection(Factory, S, getOutputSectionName(S));
338e63d81bdSEugene Leviant }
339e63d81bdSEugene Leviant 
340db741e72SEugene Leviant // Sets value of a section-defined symbol. Two kinds of
341db741e72SEugene Leviant // symbols are processed: synthetic symbols, whose value
342db741e72SEugene Leviant // is an offset from beginning of section and regular
343db741e72SEugene Leviant // symbols whose value is absolute.
344db741e72SEugene Leviant template <class ELFT>
345db741e72SEugene Leviant static void assignSectionSymbol(SymbolAssignment *Cmd,
346db741e72SEugene Leviant                                 OutputSectionBase<ELFT> *Sec,
347db741e72SEugene Leviant                                 typename ELFT::uint Off) {
348db741e72SEugene Leviant   if (!Cmd->Sym)
349db741e72SEugene Leviant     return;
350db741e72SEugene Leviant 
351db741e72SEugene Leviant   if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
352db741e72SEugene Leviant     Body->Section = Sec;
353db741e72SEugene Leviant     Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
354db741e72SEugene Leviant     return;
355db741e72SEugene Leviant   }
356db741e72SEugene Leviant   auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
357db741e72SEugene Leviant   Body->Value = Cmd->Expression(Sec->getVA() + Off);
358db741e72SEugene Leviant }
359db741e72SEugene Leviant 
360a940e539SRafael Espindola template <class ELFT> static bool isTbss(OutputSectionBase<ELFT> *Sec) {
361a940e539SRafael Espindola   return (Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS;
362a940e539SRafael Espindola }
363a940e539SRafael Espindola 
364d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
365d3190795SRafael Espindola   if (!AlreadyOutputIS.insert(S).second)
366ceabe80eSEugene Leviant     return;
367a940e539SRafael Espindola   bool IsTbss = isTbss(CurOutSec);
368d3190795SRafael Espindola 
369d3190795SRafael Espindola   uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
370d3190795SRafael Espindola   Pos = alignTo(Pos, S->Alignment);
371d3190795SRafael Espindola   S->OutSecOff = Pos - CurOutSec->getVA();
372d3190795SRafael Espindola   Pos += S->getSize();
373d3190795SRafael Espindola 
374d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
375d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
376d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
377d3190795SRafael Espindola   CurOutSec->setSize(Pos - CurOutSec->getVA());
378d3190795SRafael Espindola 
3797252ae52SRafael Espindola   if (IsTbss)
3807252ae52SRafael Espindola     ThreadBssOffset = Pos - Dot;
3817252ae52SRafael Espindola   else
382d3190795SRafael Espindola     Dot = Pos;
3832de509c3SRui Ueyama }
384ceabe80eSEugene Leviant 
385d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::flush() {
38665499b90SRafael Espindola   if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
38765499b90SRafael Espindola     return;
38865499b90SRafael Espindola   if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
389d3190795SRafael Espindola     for (InputSection<ELFT> *I : OutSec->Sections)
390d3190795SRafael Espindola       output(I);
39165499b90SRafael Espindola   } else {
39265499b90SRafael Espindola     Dot += CurOutSec->getSize();
393d3190795SRafael Espindola   }
394d3190795SRafael Espindola }
39597403d15SEugene Leviant 
396d3190795SRafael Espindola template <class ELFT>
397d3190795SRafael Espindola void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
398d3190795SRafael Espindola   if (CurOutSec == Sec)
399d3190795SRafael Espindola     return;
400d3190795SRafael Espindola   if (AlreadyOutputOS.count(Sec))
401d3190795SRafael Espindola     return;
402d3190795SRafael Espindola 
403d3190795SRafael Espindola   flush();
404d3190795SRafael Espindola   CurOutSec = Sec;
405d3190795SRafael Espindola 
406d3190795SRafael Espindola   Dot = alignTo(Dot, CurOutSec->getAlignment());
407a940e539SRafael Espindola   CurOutSec->setVA(isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot);
408d3190795SRafael Espindola }
409d3190795SRafael Espindola 
410d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
411d3190795SRafael Espindola   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
41297403d15SEugene Leviant     if (AssignCmd->Name == ".") {
41397403d15SEugene Leviant       // Update to location counter means update to section size.
414d3190795SRafael Espindola       Dot = AssignCmd->Expression(Dot);
415d3190795SRafael Espindola       CurOutSec->setSize(Dot - CurOutSec->getVA());
416d3190795SRafael Espindola       return;
41797403d15SEugene Leviant     }
418d3190795SRafael Espindola     assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
419d3190795SRafael Espindola     return;
42097403d15SEugene Leviant   }
421d3190795SRafael Espindola   auto &ICmd = cast<InputSectionDescription>(Base);
422d3190795SRafael Espindola   for (InputSectionData *ID : ICmd.Sections) {
423d3190795SRafael Espindola     auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
424d3190795SRafael Espindola     switchTo(IB->OutSec);
425d3190795SRafael Espindola     if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
426d3190795SRafael Espindola       output(I);
42765499b90SRafael Espindola     else
42865499b90SRafael Espindola       flush();
429ceabe80eSEugene Leviant   }
430ceabe80eSEugene Leviant }
431ceabe80eSEugene Leviant 
4328f66df92SGeorge Rimar template <class ELFT>
433a14b13d8SGeorge Rimar static std::vector<OutputSectionBase<ELFT> *>
434a14b13d8SGeorge Rimar findSections(OutputSectionCommand &Cmd,
435d3190795SRafael Espindola              const std::vector<OutputSectionBase<ELFT> *> &Sections) {
436a14b13d8SGeorge Rimar   std::vector<OutputSectionBase<ELFT> *> Ret;
437a14b13d8SGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : Sections)
4387c3ff2ebSRafael Espindola     if (Sec->getName() == Cmd.Name)
439a14b13d8SGeorge Rimar       Ret.push_back(Sec);
440a14b13d8SGeorge Rimar   return Ret;
4418f66df92SGeorge Rimar }
4428f66df92SGeorge Rimar 
443d3190795SRafael Espindola template <class ELFT>
444d3190795SRafael Espindola void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
445d3190795SRafael Espindola   std::vector<OutputSectionBase<ELFT> *> Sections =
446d3190795SRafael Espindola       findSections(*Cmd, *OutputSections);
447d3190795SRafael Espindola   if (Sections.empty())
448d3190795SRafael Espindola     return;
449d3190795SRafael Espindola   switchTo(Sections[0]);
450d3190795SRafael Espindola 
451d3190795SRafael Espindola   // Find the last section output location. We will output orphan sections
452d3190795SRafael Espindola   // there so that end symbols point to the correct location.
453d3190795SRafael Espindola   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
454d3190795SRafael Espindola                         [](const std::unique_ptr<BaseCommand> &Cmd) {
455d3190795SRafael Espindola                           return !isa<SymbolAssignment>(*Cmd);
456d3190795SRafael Espindola                         })
457d3190795SRafael Espindola                .base();
458d3190795SRafael Espindola   for (auto I = Cmd->Commands.begin(); I != E; ++I)
459d3190795SRafael Espindola     process(**I);
46065499b90SRafael Espindola   for (OutputSectionBase<ELFT> *Base : Sections)
461d3190795SRafael Espindola     switchTo(Base);
4622506cb4dSEugene Leviant   flush();
463b31dd370SGeorge Rimar   std::for_each(E, Cmd->Commands.end(),
464b31dd370SGeorge Rimar                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
465d3190795SRafael Espindola }
466d3190795SRafael Espindola 
4679546fffbSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
4686d38e4dbSRafael Espindola   // It is common practice to use very generic linker scripts. So for any
4696d38e4dbSRafael Espindola   // given run some of the output sections in the script will be empty.
4706d38e4dbSRafael Espindola   // We could create corresponding empty output sections, but that would
4716d38e4dbSRafael Espindola   // clutter the output.
4726d38e4dbSRafael Espindola   // We instead remove trivially empty sections. The bfd linker seems even
4736d38e4dbSRafael Espindola   // more aggressive at removing them.
4746d38e4dbSRafael Espindola   auto Pos = std::remove_if(
4756d38e4dbSRafael Espindola       Opt.Commands.begin(), Opt.Commands.end(),
4766d38e4dbSRafael Espindola       [&](const std::unique_ptr<BaseCommand> &Base) {
4776d38e4dbSRafael Espindola         auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
4786d38e4dbSRafael Espindola         if (!Cmd)
4796d38e4dbSRafael Espindola           return false;
4806d38e4dbSRafael Espindola         std::vector<OutputSectionBase<ELFT> *> Secs =
4816d38e4dbSRafael Espindola             findSections(*Cmd, *OutputSections);
4826d38e4dbSRafael Espindola         if (!Secs.empty())
4836d38e4dbSRafael Espindola           return false;
4846d38e4dbSRafael Espindola         for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
4856d38e4dbSRafael Espindola           if (!isa<InputSectionDescription>(I.get()))
4866d38e4dbSRafael Espindola             return false;
4876d38e4dbSRafael Espindola         return true;
4886d38e4dbSRafael Espindola       });
4896d38e4dbSRafael Espindola   Opt.Commands.erase(Pos, Opt.Commands.end());
4906d38e4dbSRafael Espindola 
4919546fffbSRafael Espindola   // If the output section contains only symbol assignments, create a
4929546fffbSRafael Espindola   // corresponding output section. The bfd linker seems to only create them if
4939546fffbSRafael Espindola   // '.' is assigned to, but creating these section should not have any bad
4949546fffbSRafael Espindola   // consequeces and gives us a section to put the symbol in.
4959546fffbSRafael Espindola   uintX_t Flags = SHF_ALLOC;
4969546fffbSRafael Espindola   uint32_t Type = 0;
4979546fffbSRafael Espindola   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
4989546fffbSRafael Espindola     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
4999546fffbSRafael Espindola     if (!Cmd)
5009546fffbSRafael Espindola       continue;
5019546fffbSRafael Espindola     std::vector<OutputSectionBase<ELFT> *> Secs =
5029546fffbSRafael Espindola         findSections(*Cmd, *OutputSections);
5039546fffbSRafael Espindola     if (!Secs.empty()) {
5049546fffbSRafael Espindola       Flags = Secs[0]->getFlags();
5059546fffbSRafael Espindola       Type = Secs[0]->getType();
5069546fffbSRafael Espindola       continue;
5079546fffbSRafael Espindola     }
5089546fffbSRafael Espindola 
5099546fffbSRafael Espindola     auto *OutSec = new OutputSection<ELFT>(Cmd->Name, Type, Flags);
5109546fffbSRafael Espindola     Out<ELFT>::Pool.emplace_back(OutSec);
5119546fffbSRafael Espindola     OutputSections->push_back(OutSec);
5129546fffbSRafael Espindola   }
5139546fffbSRafael Espindola }
5149546fffbSRafael Espindola 
51515c57951SRafael Espindola // When placing orphan sections, we want to place them after symbol assignments
51615c57951SRafael Espindola // so that an orphan after
51715c57951SRafael Espindola //   begin_foo = .;
51815c57951SRafael Espindola //   foo : { *(foo) }
51915c57951SRafael Espindola //   end_foo = .;
52015c57951SRafael Espindola // doesn't break the intended meaning of the begin/end symbols.
52115c57951SRafael Espindola // We don't want to go over sections since Writer<ELFT>::sortSections is the
52215c57951SRafael Espindola // one in charge of deciding the order of the sections.
52315c57951SRafael Espindola // We don't want to go over alignments, since doing so in
52415c57951SRafael Espindola //  rx_sec : { *(rx_sec) }
52515c57951SRafael Espindola //  . = ALIGN(0x1000);
52615c57951SRafael Espindola //  /* The RW PT_LOAD starts here*/
52715c57951SRafael Espindola //  rw_sec : { *(rw_sec) }
52815c57951SRafael Espindola // would mean that the RW PT_LOAD would become unaligned.
52915c57951SRafael Espindola static bool shouldSkip(const BaseCommand &Cmd) {
53015c57951SRafael Espindola   if (isa<OutputSectionCommand>(Cmd))
53115c57951SRafael Espindola     return false;
53215c57951SRafael Espindola   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
53315c57951SRafael Espindola   if (!Assign)
53415c57951SRafael Espindola     return true;
53515c57951SRafael Espindola   return Assign->Name != ".";
53615c57951SRafael Espindola }
53715c57951SRafael Espindola 
5389546fffbSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
539652852c5SGeorge Rimar   // Orphan sections are sections present in the input files which
5407c18c28cSRui Ueyama   // are not explicitly placed into the output file by the linker script.
5417c18c28cSRui Ueyama   // We place orphan sections at end of file.
5427c18c28cSRui Ueyama   // Other linkers places them using some heuristics as described in
543652852c5SGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
544aab6d5c5SRafael Espindola 
545aab6d5c5SRafael Espindola   // The OutputSections are already in the correct order.
546aab6d5c5SRafael Espindola   // This loops creates or moves commands as needed so that they are in the
547aab6d5c5SRafael Espindola   // correct order.
548aab6d5c5SRafael Espindola   int CmdIndex = 0;
549e5cc668eSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
550652852c5SGeorge Rimar     StringRef Name = Sec->getName();
551aab6d5c5SRafael Espindola 
552aab6d5c5SRafael Espindola     // Find the last spot where we can insert a command and still get the
55315c57951SRafael Espindola     // correct result.
554aab6d5c5SRafael Espindola     auto CmdIter = Opt.Commands.begin() + CmdIndex;
555aab6d5c5SRafael Espindola     auto E = Opt.Commands.end();
55615c57951SRafael Espindola     while (CmdIter != E && shouldSkip(**CmdIter)) {
557aab6d5c5SRafael Espindola       ++CmdIter;
558aab6d5c5SRafael Espindola       ++CmdIndex;
559aab6d5c5SRafael Espindola     }
560aab6d5c5SRafael Espindola 
561aab6d5c5SRafael Espindola     auto Pos =
562aab6d5c5SRafael Espindola         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
563aab6d5c5SRafael Espindola           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
564aab6d5c5SRafael Espindola           return Cmd && Cmd->Name == Name;
565aab6d5c5SRafael Espindola         });
566aab6d5c5SRafael Espindola     if (Pos == E) {
567aab6d5c5SRafael Espindola       Opt.Commands.insert(CmdIter,
568aab6d5c5SRafael Espindola                           llvm::make_unique<OutputSectionCommand>(Name));
569aab6d5c5SRafael Espindola       ++CmdIndex;
57015c57951SRafael Espindola       continue;
57115c57951SRafael Espindola     }
57215c57951SRafael Espindola 
57315c57951SRafael Espindola     // Continue from where we found it.
57415c57951SRafael Espindola     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
57515c57951SRafael Espindola     continue;
576652852c5SGeorge Rimar   }
577652852c5SGeorge Rimar 
5787c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
5794f7500bfSRui Ueyama   Dot = getHeaderSize();
580652852c5SGeorge Rimar 
581076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
582076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
5838d083e6aSRui Ueyama       if (Cmd->Name == ".") {
5848d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
5858d083e6aSRui Ueyama       } else if (Cmd->Sym) {
5868d083e6aSRui Ueyama         cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
5878d083e6aSRui Ueyama       }
58805ef4cffSRui Ueyama       continue;
589652852c5SGeorge Rimar     }
590652852c5SGeorge Rimar 
591eefa758eSGeorge Rimar     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
592eefa758eSGeorge Rimar       Cmd->Expression(Dot);
593eefa758eSGeorge Rimar       continue;
594eefa758eSGeorge Rimar     }
595eefa758eSGeorge Rimar 
596076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
597652852c5SGeorge Rimar 
59858e5c4dcSGeorge Rimar     if (Cmd->AddrExpr)
59958e5c4dcSGeorge Rimar       Dot = Cmd->AddrExpr(Dot);
60058e5c4dcSGeorge Rimar 
601d3190795SRafael Espindola     assignOffsets(Cmd);
602a14b13d8SGeorge Rimar   }
603467c4d55SEugene Leviant 
604aab6d5c5SRafael Espindola   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
605aab6d5c5SRafael Espindola   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
606aab6d5c5SRafael Espindola     if (Sec->getFlags() & SHF_ALLOC)
607aab6d5c5SRafael Espindola       MinVA = std::min(MinVA, Sec->getVA());
608aab6d5c5SRafael Espindola     else
609d3190795SRafael Espindola       Sec->setVA(0);
610aab6d5c5SRafael Espindola   }
611aab6d5c5SRafael Espindola 
6120d4b6d5cSRafael Espindola   uintX_t HeaderSize = getHeaderSize();
6134ec013acSRafael Espindola   if (HeaderSize > MinVA)
6144ec013acSRafael Espindola     fatal("Not enough space for ELF and program headers");
6154ec013acSRafael Espindola 
61664c32d6fSRafael Espindola   // ELF and Program headers need to be right before the first section in
617b91e7118SGeorge Rimar   // memory. Set their addresses accordingly.
6184ec013acSRafael Espindola   MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
619467c4d55SEugene Leviant   Out<ELFT>::ElfHeader->setVA(MinVA);
620467c4d55SEugene Leviant   Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
621fb8978fcSDima Stepanov }
622652852c5SGeorge Rimar 
623464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
62407320e40SRui Ueyama template <class ELFT>
625a4b41dcaSRafael Espindola std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
626edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
627bbe38602SEugene Leviant 
628464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
629464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
630bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
631edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
632edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
633bbe38602SEugene Leviant 
634bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
635adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
636bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
637adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
63856b21c86SEugene Leviant 
63956b21c86SEugene Leviant     if (Cmd.LMAExpr) {
64056b21c86SEugene Leviant       Phdr.H.p_paddr = Cmd.LMAExpr(0);
64156b21c86SEugene Leviant       Phdr.HasLMA = true;
64256b21c86SEugene Leviant     }
643bbe38602SEugene Leviant   }
644bbe38602SEugene Leviant 
645464daadcSRui Ueyama   // Add output sections to program headers.
646edebbdf1SRui Ueyama   PhdrEntry<ELFT> *Load = nullptr;
647edebbdf1SRui Ueyama   uintX_t Flags = PF_R;
648464daadcSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
649bbe38602SEugene Leviant     if (!(Sec->getFlags() & SHF_ALLOC))
650bbe38602SEugene Leviant       break;
651bbe38602SEugene Leviant 
652edebbdf1SRui Ueyama     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
653bbe38602SEugene Leviant     if (!PhdrIds.empty()) {
654bbe38602SEugene Leviant       // Assign headers specified by linker script
655bbe38602SEugene Leviant       for (size_t Id : PhdrIds) {
656edebbdf1SRui Ueyama         Ret[Id].add(Sec);
657865bf863SEugene Leviant         if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
6580b113671SRafael Espindola           Ret[Id].H.p_flags |= Sec->getPhdrFlags();
659bbe38602SEugene Leviant       }
660bbe38602SEugene Leviant     } else {
661bbe38602SEugene Leviant       // If we have no load segment or flags've changed then we want new load
662bbe38602SEugene Leviant       // segment.
6630b113671SRafael Espindola       uintX_t NewFlags = Sec->getPhdrFlags();
664bbe38602SEugene Leviant       if (Load == nullptr || Flags != NewFlags) {
665edebbdf1SRui Ueyama         Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
666bbe38602SEugene Leviant         Flags = NewFlags;
667bbe38602SEugene Leviant       }
66818f084ffSRui Ueyama       Load->add(Sec);
669bbe38602SEugene Leviant     }
670bbe38602SEugene Leviant   }
671edebbdf1SRui Ueyama   return Ret;
672bbe38602SEugene Leviant }
673bbe38602SEugene Leviant 
674f9bc3bd2SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
675f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
676f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
677f9bc3bd2SEugene Leviant   return !Opt.PhdrsCommands.empty() &&
678f9bc3bd2SEugene Leviant          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
679f9bc3bd2SEugene Leviant            return Cmd.Type == PT_INTERP;
680f9bc3bd2SEugene Leviant          }) == Opt.PhdrsCommands.end();
681f9bc3bd2SEugene Leviant }
682f9bc3bd2SEugene Leviant 
683bbe38602SEugene Leviant template <class ELFT>
68407320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
685f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
686f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
687f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
688f6c3ccefSGeorge Rimar         return Cmd->Filler;
689e2ee72b5SGeorge Rimar   return {};
690e2ee72b5SGeorge Rimar }
691e2ee72b5SGeorge Rimar 
692206fffa1SGeorge Rimar template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
6938ceadb38SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
6948ceadb38SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
6958ceadb38SGeorge Rimar       if (Cmd->LmaExpr && Cmd->Name == Name)
6968ceadb38SGeorge Rimar         return Cmd->LmaExpr;
6978ceadb38SGeorge Rimar   return {};
6988ceadb38SGeorge Rimar }
6998ceadb38SGeorge Rimar 
700c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
701c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
702c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
703c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
704076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
705f510fa6bSRui Ueyama   int I = 0;
706f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
707076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
708076fe157SGeorge Rimar       if (Cmd->Name == Name)
709f510fa6bSRui Ueyama         return I;
710f510fa6bSRui Ueyama     ++I;
711f510fa6bSRui Ueyama   }
712f510fa6bSRui Ueyama   return INT_MAX;
71371b26e94SGeorge Rimar }
71471b26e94SGeorge Rimar 
715bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
716bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
717bbe38602SEugene Leviant }
718bbe38602SEugene Leviant 
7199e69450eSGeorge Rimar template <class ELFT>
720884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
72196659df0SGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
72296659df0SGeorge Rimar     if (Sec->getName() == Name)
72396659df0SGeorge Rimar       return Sec->getVA();
72496659df0SGeorge Rimar   error("undefined section " + Name);
72596659df0SGeorge Rimar   return 0;
72696659df0SGeorge Rimar }
72796659df0SGeorge Rimar 
72896659df0SGeorge Rimar template <class ELFT>
729884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
7309e69450eSGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
7319e69450eSGeorge Rimar     if (Sec->getName() == Name)
7329e69450eSGeorge Rimar       return Sec->getSize();
7339e69450eSGeorge Rimar   error("undefined section " + Name);
7349e69450eSGeorge Rimar   return 0;
7359e69450eSGeorge Rimar }
7369e69450eSGeorge Rimar 
73736fac7f0SEugene Leviant template <class ELFT>
73836fac7f0SEugene Leviant uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
73936fac7f0SEugene Leviant   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
74036fac7f0SEugene Leviant     if (Sec->getName() == Name)
74136fac7f0SEugene Leviant       return Sec->getAlignment();
74236fac7f0SEugene Leviant   error("undefined section " + Name);
74336fac7f0SEugene Leviant   return 0;
74436fac7f0SEugene Leviant }
74536fac7f0SEugene Leviant 
746884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
7470d4b6d5cSRafael Espindola   return elf::getHeaderSize<ELFT>();
748e32a3598SGeorge Rimar }
749e32a3598SGeorge Rimar 
750884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
751884e786dSGeorge Rimar   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
752884e786dSGeorge Rimar     return B->getVA<ELFT>();
753884e786dSGeorge Rimar   error("symbol not found: " + S);
754884e786dSGeorge Rimar   return 0;
755884e786dSGeorge Rimar }
756884e786dSGeorge Rimar 
757f34f45fdSGeorge Rimar template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
758f34f45fdSGeorge Rimar   return Symtab<ELFT>::X->find(S) != nullptr;
759f34f45fdSGeorge Rimar }
760f34f45fdSGeorge Rimar 
761bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
762bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
763bbe38602SEugene Leviant // PHDRS {} script block.
764bbe38602SEugene Leviant template <class ELFT>
765edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
766076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
767076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
768edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
76931d842f5SGeorge Rimar       continue;
77031d842f5SGeorge Rimar 
77129c5a2a9SRui Ueyama     std::vector<size_t> Ret;
77229c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
77329c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
77429c5a2a9SRui Ueyama     return Ret;
775bbe38602SEugene Leviant   }
77631d842f5SGeorge Rimar   return {};
77731d842f5SGeorge Rimar }
778bbe38602SEugene Leviant 
77929c5a2a9SRui Ueyama template <class ELFT>
78029c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
78129c5a2a9SRui Ueyama   size_t I = 0;
78229c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
78329c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
78429c5a2a9SRui Ueyama       return I;
78529c5a2a9SRui Ueyama     ++I;
78629c5a2a9SRui Ueyama   }
78729c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
78829c5a2a9SRui Ueyama   return 0;
78929c5a2a9SRui Ueyama }
79029c5a2a9SRui Ueyama 
79107320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
792c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
793c3794e58SGeorge Rimar 
794f7c5fbb1SRui Ueyama public:
79507320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
796f23b2320SGeorge Rimar 
79720b6598cSGeorge Rimar   void readLinkerScript();
79820b6598cSGeorge Rimar   void readVersionScript();
799f7c5fbb1SRui Ueyama 
800f7c5fbb1SRui Ueyama private:
80152a1509eSRui Ueyama   void addFile(StringRef Path);
80252a1509eSRui Ueyama 
803f7c5fbb1SRui Ueyama   void readAsNeeded();
80490c5099eSDenis Protivensky   void readEntry();
80583f406cfSGeorge Rimar   void readExtern();
806f7c5fbb1SRui Ueyama   void readGroup();
80731aa1f83SRui Ueyama   void readInclude();
808ee59282bSRui Ueyama   void readOutput();
8099159ce93SDavide Italiano   void readOutputArch();
810f7c5fbb1SRui Ueyama   void readOutputFormat();
811bbe38602SEugene Leviant   void readPhdrs();
81268a39a65SDavide Italiano   void readSearchDir();
8138e3b38abSDenis Protivensky   void readSections();
81495769b4aSRui Ueyama   void readVersion();
81595769b4aSRui Ueyama   void readVersionScriptCommand();
8168e3b38abSDenis Protivensky 
817113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
818ff1f29e0SGeorge Rimar   std::vector<uint8_t> readFill();
81910416564SRui Ueyama   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
820ff1f29e0SGeorge Rimar   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
821bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
822a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionDescription(StringRef Tok);
823c91930a1SGeorge Rimar   Regex readFilePatterns();
82407171f21SGeorge Rimar   std::vector<SectionPattern> readInputSectionsList();
825a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
826bbe38602SEugene Leviant   unsigned readPhdrType();
827be394db3SGeorge Rimar   SortSectionPolicy readSortKind();
828a35e39caSPetr Hosek   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
829db741e72SEugene Leviant   SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
83003fc010eSGeorge Rimar   void readSort();
831eefa758eSGeorge Rimar   Expr readAssert();
832708019c4SRui Ueyama 
833708019c4SRui Ueyama   Expr readExpr();
834708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
835708019c4SRui Ueyama   Expr readPrimary();
836708019c4SRui Ueyama   Expr readTernary(Expr Cond);
8376ad7dfccSRui Ueyama   Expr readParenExpr();
838f7c5fbb1SRui Ueyama 
83920b6598cSGeorge Rimar   // For parsing version script.
84020b6598cSGeorge Rimar   void readExtern(std::vector<SymbolVersion> *Globals);
84195769b4aSRui Ueyama   void readVersionDeclaration(StringRef VerStr);
84220b6598cSGeorge Rimar   void readGlobal(StringRef VerStr);
84320b6598cSGeorge Rimar   void readLocal();
84420b6598cSGeorge Rimar 
84507320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
84607320e40SRui Ueyama   StringSaver Saver = {ScriptConfig->Alloc};
84716b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
848f7c5fbb1SRui Ueyama };
849f7c5fbb1SRui Ueyama 
85020b6598cSGeorge Rimar void ScriptParser::readVersionScript() {
85195769b4aSRui Ueyama   readVersionScriptCommand();
85220b6598cSGeorge Rimar   if (!atEOF())
85395769b4aSRui Ueyama     setError("EOF expected, but got " + next());
85495769b4aSRui Ueyama }
85595769b4aSRui Ueyama 
85695769b4aSRui Ueyama void ScriptParser::readVersionScriptCommand() {
85795769b4aSRui Ueyama   if (skip("{")) {
85895769b4aSRui Ueyama     readVersionDeclaration("");
85920b6598cSGeorge Rimar     return;
86020b6598cSGeorge Rimar   }
86120b6598cSGeorge Rimar 
86295769b4aSRui Ueyama   while (!atEOF() && !Error && peek() != "}") {
86320b6598cSGeorge Rimar     StringRef VerStr = next();
86420b6598cSGeorge Rimar     if (VerStr == "{") {
86595769b4aSRui Ueyama       setError("anonymous version definition is used in "
86695769b4aSRui Ueyama                "combination with other version definitions");
86720b6598cSGeorge Rimar       return;
86820b6598cSGeorge Rimar     }
86920b6598cSGeorge Rimar     expect("{");
87095769b4aSRui Ueyama     readVersionDeclaration(VerStr);
87120b6598cSGeorge Rimar   }
87220b6598cSGeorge Rimar }
87320b6598cSGeorge Rimar 
87495769b4aSRui Ueyama void ScriptParser::readVersion() {
87595769b4aSRui Ueyama   expect("{");
87695769b4aSRui Ueyama   readVersionScriptCommand();
87795769b4aSRui Ueyama   expect("}");
87895769b4aSRui Ueyama }
87995769b4aSRui Ueyama 
88020b6598cSGeorge Rimar void ScriptParser::readLinkerScript() {
881f7c5fbb1SRui Ueyama   while (!atEOF()) {
882f7c5fbb1SRui Ueyama     StringRef Tok = next();
883a27eeccaSRui Ueyama     if (Tok == ";")
884a27eeccaSRui Ueyama       continue;
885a27eeccaSRui Ueyama 
88620d03194SEugene Leviant     if (Tok == "ASSERT") {
88720d03194SEugene Leviant       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
88820d03194SEugene Leviant     } else if (Tok == "ENTRY") {
889a27eeccaSRui Ueyama       readEntry();
890a27eeccaSRui Ueyama     } else if (Tok == "EXTERN") {
891a27eeccaSRui Ueyama       readExtern();
892a27eeccaSRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
893a27eeccaSRui Ueyama       readGroup();
894a27eeccaSRui Ueyama     } else if (Tok == "INCLUDE") {
895a27eeccaSRui Ueyama       readInclude();
896a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT") {
897a27eeccaSRui Ueyama       readOutput();
898a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
899a27eeccaSRui Ueyama       readOutputArch();
900a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
901a27eeccaSRui Ueyama       readOutputFormat();
902a27eeccaSRui Ueyama     } else if (Tok == "PHDRS") {
903a27eeccaSRui Ueyama       readPhdrs();
904a27eeccaSRui Ueyama     } else if (Tok == "SEARCH_DIR") {
905a27eeccaSRui Ueyama       readSearchDir();
906a27eeccaSRui Ueyama     } else if (Tok == "SECTIONS") {
907a27eeccaSRui Ueyama       readSections();
908a27eeccaSRui Ueyama     } else if (Tok == "VERSION") {
909a27eeccaSRui Ueyama       readVersion();
910db741e72SEugene Leviant     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
9110df80befSPetr Hosek       Opt.Commands.emplace_back(Cmd);
912e5d3ca50SPetr Hosek     } else {
9135761042dSGeorge Rimar       setError("unknown directive: " + Tok);
914f7c5fbb1SRui Ueyama     }
915f7c5fbb1SRui Ueyama   }
916e5d3ca50SPetr Hosek }
917f7c5fbb1SRui Ueyama 
918717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
91916b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
92016b0cc9eSSimon Atanasyan     SmallString<128> Path;
92116b0cc9eSSimon Atanasyan     (Config->Sysroot + S).toStringRef(Path);
92216b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
92316b0cc9eSSimon Atanasyan       Driver->addFile(Saver.save(Path.str()));
92416b0cc9eSSimon Atanasyan       return;
92516b0cc9eSSimon Atanasyan     }
92616b0cc9eSSimon Atanasyan   }
92716b0cc9eSSimon Atanasyan 
928f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
92952a1509eSRui Ueyama     Driver->addFile(S);
93052a1509eSRui Ueyama   } else if (S.startswith("=")) {
93152a1509eSRui Ueyama     if (Config->Sysroot.empty())
93252a1509eSRui Ueyama       Driver->addFile(S.substr(1));
93352a1509eSRui Ueyama     else
93452a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
93552a1509eSRui Ueyama   } else if (S.startswith("-l")) {
93621eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
937a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
938a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
93952a1509eSRui Ueyama   } else {
94052a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
94152a1509eSRui Ueyama     if (Path.empty())
942777f9630SGeorge Rimar       setError("unable to find " + S);
943025d59b1SRui Ueyama     else
94452a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
94552a1509eSRui Ueyama   }
94652a1509eSRui Ueyama }
94752a1509eSRui Ueyama 
948717677afSRui Ueyama void ScriptParser::readAsNeeded() {
949f7c5fbb1SRui Ueyama   expect("(");
95035da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
95135da9b6eSRui Ueyama   Config->AsNeeded = true;
952a2acc931SRui Ueyama   while (!Error && !skip(")"))
953cd574a5eSGeorge Rimar     addFile(unquote(next()));
95435da9b6eSRui Ueyama   Config->AsNeeded = Orig;
955f7c5fbb1SRui Ueyama }
956f7c5fbb1SRui Ueyama 
957717677afSRui Ueyama void ScriptParser::readEntry() {
95890c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
95990c5099eSDenis Protivensky   expect("(");
96090c5099eSDenis Protivensky   StringRef Tok = next();
96190c5099eSDenis Protivensky   if (Config->Entry.empty())
96290c5099eSDenis Protivensky     Config->Entry = Tok;
96390c5099eSDenis Protivensky   expect(")");
96490c5099eSDenis Protivensky }
96590c5099eSDenis Protivensky 
966717677afSRui Ueyama void ScriptParser::readExtern() {
96783f406cfSGeorge Rimar   expect("(");
968a2acc931SRui Ueyama   while (!Error && !skip(")"))
969a2acc931SRui Ueyama     Config->Undefined.push_back(next());
97083f406cfSGeorge Rimar }
97183f406cfSGeorge Rimar 
972717677afSRui Ueyama void ScriptParser::readGroup() {
973f7c5fbb1SRui Ueyama   expect("(");
974a2acc931SRui Ueyama   while (!Error && !skip(")")) {
975f7c5fbb1SRui Ueyama     StringRef Tok = next();
976a2acc931SRui Ueyama     if (Tok == "AS_NEEDED")
977f7c5fbb1SRui Ueyama       readAsNeeded();
978a2acc931SRui Ueyama     else
979cd574a5eSGeorge Rimar       addFile(unquote(Tok));
980f7c5fbb1SRui Ueyama   }
981f7c5fbb1SRui Ueyama }
982f7c5fbb1SRui Ueyama 
983717677afSRui Ueyama void ScriptParser::readInclude() {
98431aa1f83SRui Ueyama   StringRef Tok = next();
985cd574a5eSGeorge Rimar   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
986025d59b1SRui Ueyama   if (!MBOrErr) {
9875761042dSGeorge Rimar     setError("cannot open " + Tok);
988025d59b1SRui Ueyama     return;
989025d59b1SRui Ueyama   }
99031aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
991a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
992a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
99331aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
99431aa1f83SRui Ueyama }
99531aa1f83SRui Ueyama 
996717677afSRui Ueyama void ScriptParser::readOutput() {
997ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
998ee59282bSRui Ueyama   expect("(");
999ee59282bSRui Ueyama   StringRef Tok = next();
1000ee59282bSRui Ueyama   if (Config->OutputFile.empty())
1001cd574a5eSGeorge Rimar     Config->OutputFile = unquote(Tok);
1002ee59282bSRui Ueyama   expect(")");
1003ee59282bSRui Ueyama }
1004ee59282bSRui Ueyama 
1005717677afSRui Ueyama void ScriptParser::readOutputArch() {
10069159ce93SDavide Italiano   // Error checking only for now.
10079159ce93SDavide Italiano   expect("(");
10089159ce93SDavide Italiano   next();
10099159ce93SDavide Italiano   expect(")");
10109159ce93SDavide Italiano }
10119159ce93SDavide Italiano 
1012717677afSRui Ueyama void ScriptParser::readOutputFormat() {
1013f7c5fbb1SRui Ueyama   // Error checking only for now.
1014f7c5fbb1SRui Ueyama   expect("(");
1015f7c5fbb1SRui Ueyama   next();
10166836c618SDavide Italiano   StringRef Tok = next();
10176836c618SDavide Italiano   if (Tok == ")")
10186836c618SDavide Italiano     return;
1019025d59b1SRui Ueyama   if (Tok != ",") {
10205761042dSGeorge Rimar     setError("unexpected token: " + Tok);
1021025d59b1SRui Ueyama     return;
1022025d59b1SRui Ueyama   }
10236836c618SDavide Italiano   next();
10246836c618SDavide Italiano   expect(",");
10256836c618SDavide Italiano   next();
1026f7c5fbb1SRui Ueyama   expect(")");
1027f7c5fbb1SRui Ueyama }
1028f7c5fbb1SRui Ueyama 
1029bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
1030bbe38602SEugene Leviant   expect("{");
1031bbe38602SEugene Leviant   while (!Error && !skip("}")) {
1032bbe38602SEugene Leviant     StringRef Tok = next();
103356b21c86SEugene Leviant     Opt.PhdrsCommands.push_back(
103456b21c86SEugene Leviant         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1035bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1036bbe38602SEugene Leviant 
1037bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
1038bbe38602SEugene Leviant     do {
1039bbe38602SEugene Leviant       Tok = next();
1040bbe38602SEugene Leviant       if (Tok == ";")
1041bbe38602SEugene Leviant         break;
1042bbe38602SEugene Leviant       if (Tok == "FILEHDR")
1043bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
1044bbe38602SEugene Leviant       else if (Tok == "PHDRS")
1045bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
104656b21c86SEugene Leviant       else if (Tok == "AT")
104756b21c86SEugene Leviant         PhdrCmd.LMAExpr = readParenExpr();
1048865bf863SEugene Leviant       else if (Tok == "FLAGS") {
1049865bf863SEugene Leviant         expect("(");
1050eb685cd7SRafael Espindola         // Passing 0 for the value of dot is a bit of a hack. It means that
1051eb685cd7SRafael Espindola         // we accept expressions like ".|1".
1052eb685cd7SRafael Espindola         PhdrCmd.Flags = readExpr()(0);
1053865bf863SEugene Leviant         expect(")");
1054865bf863SEugene Leviant       } else
1055bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
1056bbe38602SEugene Leviant     } while (!Error);
1057bbe38602SEugene Leviant   }
1058bbe38602SEugene Leviant }
1059bbe38602SEugene Leviant 
1060717677afSRui Ueyama void ScriptParser::readSearchDir() {
106168a39a65SDavide Italiano   expect("(");
106286c5fb82SRui Ueyama   StringRef Tok = next();
10636c7ad13fSRui Ueyama   if (!Config->Nostdlib)
1064cd574a5eSGeorge Rimar     Config->SearchPaths.push_back(unquote(Tok));
106568a39a65SDavide Italiano   expect(")");
106668a39a65SDavide Italiano }
106768a39a65SDavide Italiano 
1068717677afSRui Ueyama void ScriptParser::readSections() {
1069e05336ffSEugene Leviant   Opt.HasSections = true;
10708e3b38abSDenis Protivensky   expect("{");
1071652852c5SGeorge Rimar   while (!Error && !skip("}")) {
1072113cdec9SRui Ueyama     StringRef Tok = next();
1073db741e72SEugene Leviant     BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
1074ceabe80eSEugene Leviant     if (!Cmd) {
1075ceabe80eSEugene Leviant       if (Tok == "ASSERT")
1076eefa758eSGeorge Rimar         Cmd = new AssertCommand(readAssert());
1077ceabe80eSEugene Leviant       else
107810416564SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
10798e3b38abSDenis Protivensky     }
108010416564SRui Ueyama     Opt.Commands.emplace_back(Cmd);
1081652852c5SGeorge Rimar   }
1082708019c4SRui Ueyama }
10838e3b38abSDenis Protivensky 
1084708019c4SRui Ueyama static int precedence(StringRef Op) {
1085708019c4SRui Ueyama   return StringSwitch<int>(Op)
10860120e3f2SRui Ueyama       .Cases("*", "/", 5)
10870120e3f2SRui Ueyama       .Cases("+", "-", 4)
10880120e3f2SRui Ueyama       .Cases("<<", ">>", 3)
10899c4ac5f2SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
10900120e3f2SRui Ueyama       .Cases("&", "|", 1)
1091708019c4SRui Ueyama       .Default(-1);
1092708019c4SRui Ueyama }
1093708019c4SRui Ueyama 
1094c91930a1SGeorge Rimar Regex ScriptParser::readFilePatterns() {
109510416564SRui Ueyama   std::vector<StringRef> V;
109610416564SRui Ueyama   while (!Error && !skip(")"))
109710416564SRui Ueyama     V.push_back(next());
1098c91930a1SGeorge Rimar   return compileGlobPatterns(V);
10990702c4e8SGeorge Rimar }
11000702c4e8SGeorge Rimar 
1101be394db3SGeorge Rimar SortSectionPolicy ScriptParser::readSortKind() {
1102742c3836SRui Ueyama   if (skip("SORT") || skip("SORT_BY_NAME"))
1103be394db3SGeorge Rimar     return SortSectionPolicy::Name;
1104742c3836SRui Ueyama   if (skip("SORT_BY_ALIGNMENT"))
1105be394db3SGeorge Rimar     return SortSectionPolicy::Alignment;
1106575208caSGeorge Rimar   if (skip("SORT_BY_INIT_PRIORITY"))
1107be394db3SGeorge Rimar     return SortSectionPolicy::Priority;
1108be394db3SGeorge Rimar   if (skip("SORT_NONE"))
1109be394db3SGeorge Rimar     return SortSectionPolicy::None;
1110b2a0abdfSRui Ueyama   return SortSectionPolicy::Default;
1111be394db3SGeorge Rimar }
1112be394db3SGeorge Rimar 
1113395281cfSGeorge Rimar // Method reads a list of sequence of excluded files and section globs given in
1114395281cfSGeorge Rimar // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1115395281cfSGeorge Rimar // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1116af03be19SGeorge Rimar // The semantics of that is next:
1117af03be19SGeorge Rimar // * Include .foo.1 from every file.
1118af03be19SGeorge Rimar // * Include .foo.2 from every file but a.o
1119af03be19SGeorge Rimar // * Include .foo.3 from every file but b.o
112007171f21SGeorge Rimar std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
112107171f21SGeorge Rimar   std::vector<SectionPattern> Ret;
1122601e9898SGeorge Rimar   while (!Error && peek() != ")") {
1123027a9e87SRui Ueyama     Regex ExcludeFileRe;
1124395281cfSGeorge Rimar     if (skip("EXCLUDE_FILE")) {
1125395281cfSGeorge Rimar       expect("(");
1126395281cfSGeorge Rimar       ExcludeFileRe = readFilePatterns();
1127395281cfSGeorge Rimar     }
1128395281cfSGeorge Rimar 
1129601e9898SGeorge Rimar     std::vector<StringRef> V;
1130601e9898SGeorge Rimar     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1131395281cfSGeorge Rimar       V.push_back(next());
1132601e9898SGeorge Rimar 
1133601e9898SGeorge Rimar     if (!V.empty())
113407171f21SGeorge Rimar       Ret.push_back({std::move(ExcludeFileRe), compileGlobPatterns(V)});
1135601e9898SGeorge Rimar     else
1136601e9898SGeorge Rimar       setError("section pattern is expected");
1137395281cfSGeorge Rimar   }
113807171f21SGeorge Rimar   return Ret;
1139395281cfSGeorge Rimar }
1140395281cfSGeorge Rimar 
114107171f21SGeorge Rimar // Section pattern grammar can have complex expressions, for example:
114207171f21SGeorge Rimar // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
114307171f21SGeorge Rimar // Generally is a sequence of globs and excludes that may be wrapped in a SORT()
114407171f21SGeorge Rimar // commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
114507171f21SGeorge Rimar // This methods handles wrapping sequences of excluded files and section globs
114607171f21SGeorge Rimar // into SORT() if that needed and reads them all.
1147a2496cbeSGeorge Rimar InputSectionDescription *
1148a2496cbeSGeorge Rimar ScriptParser::readInputSectionRules(StringRef FilePattern) {
1149c91930a1SGeorge Rimar   auto *Cmd = new InputSectionDescription(FilePattern);
11500ed42b0cSDavide Italiano   expect("(");
115107171f21SGeorge Rimar   while (!HasError && !skip(")")) {
115207171f21SGeorge Rimar     SortSectionPolicy Outer = readSortKind();
115307171f21SGeorge Rimar     SortSectionPolicy Inner = SortSectionPolicy::Default;
115407171f21SGeorge Rimar     std::vector<SectionPattern> V;
115507171f21SGeorge Rimar     if (Outer != SortSectionPolicy::Default) {
11560702c4e8SGeorge Rimar       expect("(");
115707171f21SGeorge Rimar       Inner = readSortKind();
115807171f21SGeorge Rimar       if (Inner != SortSectionPolicy::Default) {
1159350ece4eSGeorge Rimar         expect("(");
116007171f21SGeorge Rimar         V = readInputSectionsList();
11610702c4e8SGeorge Rimar         expect(")");
1162350ece4eSGeorge Rimar       } else {
116307171f21SGeorge Rimar         V = readInputSectionsList();
1164350ece4eSGeorge Rimar       }
1165350ece4eSGeorge Rimar       expect(")");
116607171f21SGeorge Rimar     } else {
116707171f21SGeorge Rimar       V = readInputSectionsList();
11680659800eSGeorge Rimar     }
11690702c4e8SGeorge Rimar 
117007171f21SGeorge Rimar     for (SectionPattern &Pat : V) {
117107171f21SGeorge Rimar       Pat.SortInner = Inner;
117207171f21SGeorge Rimar       Pat.SortOuter = Outer;
117307171f21SGeorge Rimar     }
117407171f21SGeorge Rimar 
117507171f21SGeorge Rimar     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
117607171f21SGeorge Rimar   }
117710416564SRui Ueyama   return Cmd;
11780659800eSGeorge Rimar }
11790659800eSGeorge Rimar 
1180a2496cbeSGeorge Rimar InputSectionDescription *
1181a2496cbeSGeorge Rimar ScriptParser::readInputSectionDescription(StringRef Tok) {
11820659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
11830659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1184a2496cbeSGeorge Rimar   if (Tok == "KEEP") {
1185e7282797SDavide Italiano     expect("(");
1186a2496cbeSGeorge Rimar     StringRef FilePattern = next();
1187a2496cbeSGeorge Rimar     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
11880ed42b0cSDavide Italiano     expect(")");
11894dc07becSRui Ueyama     for (SectionPattern &Pat : Cmd->SectionPatterns)
11904dc07becSRui Ueyama       Opt.KeptSections.push_back(&Pat.SectionRe);
119110416564SRui Ueyama     return Cmd;
119210416564SRui Ueyama   }
1193a2496cbeSGeorge Rimar   return readInputSectionRules(Tok);
11940659800eSGeorge Rimar }
11950659800eSGeorge Rimar 
119603fc010eSGeorge Rimar void ScriptParser::readSort() {
119703fc010eSGeorge Rimar   expect("(");
119803fc010eSGeorge Rimar   expect("CONSTRUCTORS");
119903fc010eSGeorge Rimar   expect(")");
120003fc010eSGeorge Rimar }
120103fc010eSGeorge Rimar 
1202eefa758eSGeorge Rimar Expr ScriptParser::readAssert() {
1203eefa758eSGeorge Rimar   expect("(");
1204eefa758eSGeorge Rimar   Expr E = readExpr();
1205eefa758eSGeorge Rimar   expect(",");
1206cd574a5eSGeorge Rimar   StringRef Msg = unquote(next());
1207eefa758eSGeorge Rimar   expect(")");
1208eefa758eSGeorge Rimar   return [=](uint64_t Dot) {
1209eefa758eSGeorge Rimar     uint64_t V = E(Dot);
1210eefa758eSGeorge Rimar     if (!V)
1211eefa758eSGeorge Rimar       error(Msg);
1212eefa758eSGeorge Rimar     return V;
1213eefa758eSGeorge Rimar   };
1214eefa758eSGeorge Rimar }
1215eefa758eSGeorge Rimar 
121625150e8bSRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
121725150e8bSRui Ueyama // alias for =fillexp section attribute, which is different from
121825150e8bSRui Ueyama // what GNU linkers do.
121925150e8bSRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1220ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readFill() {
1221ff1f29e0SGeorge Rimar   expect("(");
1222ff1f29e0SGeorge Rimar   std::vector<uint8_t> V = readOutputSectionFiller(next());
1223ff1f29e0SGeorge Rimar   expect(")");
1224ff1f29e0SGeorge Rimar   expect(";");
1225ff1f29e0SGeorge Rimar   return V;
1226ff1f29e0SGeorge Rimar }
1227ff1f29e0SGeorge Rimar 
122810416564SRui Ueyama OutputSectionCommand *
122910416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1230076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
123158e5c4dcSGeorge Rimar 
123258e5c4dcSGeorge Rimar   // Read an address expression.
123358e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
123458e5c4dcSGeorge Rimar   if (peek() != ":")
123558e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
123658e5c4dcSGeorge Rimar 
12378e3b38abSDenis Protivensky   expect(":");
1238246f681eSDavide Italiano 
12398ceadb38SGeorge Rimar   if (skip("AT"))
12406ad7dfccSRui Ueyama     Cmd->LmaExpr = readParenExpr();
1241630c6179SGeorge Rimar   if (skip("ALIGN"))
12426ad7dfccSRui Ueyama     Cmd->AlignExpr = readParenExpr();
1243db24d9c3SGeorge Rimar   if (skip("SUBALIGN"))
1244db24d9c3SGeorge Rimar     Cmd->SubalignExpr = readParenExpr();
1245630c6179SGeorge Rimar 
1246246f681eSDavide Italiano   // Parse constraints.
1247246f681eSDavide Italiano   if (skip("ONLY_IF_RO"))
1248efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
1249246f681eSDavide Italiano   if (skip("ONLY_IF_RW"))
1250efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
12518e3b38abSDenis Protivensky   expect("{");
12528ec77e64SRui Ueyama 
1253025d59b1SRui Ueyama   while (!Error && !skip("}")) {
1254ceabe80eSEugene Leviant     StringRef Tok = next();
1255db741e72SEugene Leviant     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
1256ceabe80eSEugene Leviant       Cmd->Commands.emplace_back(Assignment);
1257ff1f29e0SGeorge Rimar     else if (Tok == "FILL")
1258ff1f29e0SGeorge Rimar       Cmd->Filler = readFill();
1259ceabe80eSEugene Leviant     else if (Tok == "SORT")
126003fc010eSGeorge Rimar       readSort();
1261a2496cbeSGeorge Rimar     else if (peek() == "(")
1262a2496cbeSGeorge Rimar       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1263ceabe80eSEugene Leviant     else
1264ceabe80eSEugene Leviant       setError("unknown command " + Tok);
12658e3b38abSDenis Protivensky   }
1266076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
12674ebc5620SGeorge Rimar 
12684ebc5620SGeorge Rimar   if (skip("="))
12694ebc5620SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next());
12704ebc5620SGeorge Rimar   else if (peek().startswith("="))
1271ff1f29e0SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next().drop_front());
12724ebc5620SGeorge Rimar 
127310416564SRui Ueyama   return Cmd;
1274f71caa2bSRui Ueyama }
12758ec77e64SRui Ueyama 
12762c8f1f04SRui Ueyama // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
12772c8f1f04SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
12782c8f1f04SRui Ueyama //
12792c8f1f04SRui Ueyama // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
12802c8f1f04SRui Ueyama // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
12812c8f1f04SRui Ueyama // as 32-bit big-endian values. We will do the same as ld.gold does
12822c8f1f04SRui Ueyama // because it's simpler than what ld.bfd does.
1283ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1284965827d6SRui Ueyama   uint32_t V;
1285ff1f29e0SGeorge Rimar   if (Tok.getAsInteger(0, V)) {
1286965827d6SRui Ueyama     setError("invalid filler expression: " + Tok);
1287f71caa2bSRui Ueyama     return {};
1288e2ee72b5SGeorge Rimar   }
1289965827d6SRui Ueyama   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
12908e3b38abSDenis Protivensky }
12918e3b38abSDenis Protivensky 
1292a35e39caSPetr Hosek SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1293a31c91b1SEugene Leviant   expect("(");
1294174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
1295a35e39caSPetr Hosek   Cmd->Provide = Provide;
1296174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
1297a31c91b1SEugene Leviant   expect(")");
1298a31c91b1SEugene Leviant   expect(";");
129910416564SRui Ueyama   return Cmd;
1300eda81a1bSEugene Leviant }
1301eda81a1bSEugene Leviant 
1302db741e72SEugene Leviant SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1303db741e72SEugene Leviant                                                         bool MakeAbsolute) {
1304ceabe80eSEugene Leviant   SymbolAssignment *Cmd = nullptr;
1305ceabe80eSEugene Leviant   if (peek() == "=" || peek() == "+=") {
1306ceabe80eSEugene Leviant     Cmd = readAssignment(Tok);
1307ceabe80eSEugene Leviant     expect(";");
1308ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE") {
1309a35e39caSPetr Hosek     Cmd = readProvideHidden(true, false);
1310a35e39caSPetr Hosek   } else if (Tok == "HIDDEN") {
1311a35e39caSPetr Hosek     Cmd = readProvideHidden(false, true);
1312ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE_HIDDEN") {
1313a35e39caSPetr Hosek     Cmd = readProvideHidden(true, true);
1314ceabe80eSEugene Leviant   }
1315db741e72SEugene Leviant   if (Cmd && MakeAbsolute)
1316db741e72SEugene Leviant     Cmd->IsAbsolute = true;
1317ceabe80eSEugene Leviant   return Cmd;
1318ceabe80eSEugene Leviant }
1319ceabe80eSEugene Leviant 
132030835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
132130835ea4SGeorge Rimar   if (S == ".")
132230835ea4SGeorge Rimar     return Dot;
1323884e786dSGeorge Rimar   return ScriptBase->getSymbolValue(S);
1324e32a3598SGeorge Rimar }
1325e32a3598SGeorge Rimar 
132630835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
132730835ea4SGeorge Rimar   StringRef Op = next();
1328db741e72SEugene Leviant   bool IsAbsolute = false;
1329db741e72SEugene Leviant   Expr E;
133030835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
1331db741e72SEugene Leviant   if (skip("ABSOLUTE")) {
1332db741e72SEugene Leviant     E = readParenExpr();
1333db741e72SEugene Leviant     IsAbsolute = true;
1334db741e72SEugene Leviant   } else {
1335db741e72SEugene Leviant     E = readExpr();
1336db741e72SEugene Leviant   }
133730835ea4SGeorge Rimar   if (Op == "+=")
133830835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1339db741e72SEugene Leviant   return new SymbolAssignment(Name, E, IsAbsolute);
134030835ea4SGeorge Rimar }
134130835ea4SGeorge Rimar 
134230835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
134330835ea4SGeorge Rimar // script expression.
134430835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
134530835ea4SGeorge Rimar 
134636c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
134736c1cd23SRui Ueyama   if (Op == "*")
134836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
134936c1cd23SRui Ueyama   if (Op == "/") {
135036c1cd23SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
135136c1cd23SRui Ueyama       uint64_t RHS = R(Dot);
135236c1cd23SRui Ueyama       if (RHS == 0) {
135336c1cd23SRui Ueyama         error("division by zero");
135436c1cd23SRui Ueyama         return 0;
135536c1cd23SRui Ueyama       }
135636c1cd23SRui Ueyama       return L(Dot) / RHS;
135736c1cd23SRui Ueyama     };
135836c1cd23SRui Ueyama   }
135936c1cd23SRui Ueyama   if (Op == "+")
136036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
136136c1cd23SRui Ueyama   if (Op == "-")
136236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1363c8ccd1f1SGeorge Rimar   if (Op == "<<")
1364c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1365c8ccd1f1SGeorge Rimar   if (Op == ">>")
1366c8ccd1f1SGeorge Rimar     return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
136736c1cd23SRui Ueyama   if (Op == "<")
136836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
136936c1cd23SRui Ueyama   if (Op == ">")
137036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
137136c1cd23SRui Ueyama   if (Op == ">=")
137236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
137336c1cd23SRui Ueyama   if (Op == "<=")
137436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
137536c1cd23SRui Ueyama   if (Op == "==")
137636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
137736c1cd23SRui Ueyama   if (Op == "!=")
137836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
137936c1cd23SRui Ueyama   if (Op == "&")
138036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1381cc3dd629SRafael Espindola   if (Op == "|")
1382cc3dd629SRafael Espindola     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
138336c1cd23SRui Ueyama   llvm_unreachable("invalid operator");
138436c1cd23SRui Ueyama }
138536c1cd23SRui Ueyama 
1386708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
1387708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
1388708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1389708019c4SRui Ueyama   while (!atEOF() && !Error) {
1390708019c4SRui Ueyama     // Read an operator and an expression.
1391708019c4SRui Ueyama     StringRef Op1 = peek();
1392708019c4SRui Ueyama     if (Op1 == "?")
1393708019c4SRui Ueyama       return readTernary(Lhs);
1394708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
1395a31c91b1SEugene Leviant       break;
1396a31c91b1SEugene Leviant     next();
1397708019c4SRui Ueyama     Expr Rhs = readPrimary();
1398708019c4SRui Ueyama 
1399708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
1400708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
1401708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
1402708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
1403708019c4SRui Ueyama     while (!atEOF()) {
1404708019c4SRui Ueyama       StringRef Op2 = peek();
1405708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
1406eda81a1bSEugene Leviant         break;
1407708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
1408eda81a1bSEugene Leviant     }
1409708019c4SRui Ueyama 
1410708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
1411708019c4SRui Ueyama   }
1412708019c4SRui Ueyama   return Lhs;
1413708019c4SRui Ueyama }
1414708019c4SRui Ueyama 
1415708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
1416e2cc07bcSMichael J. Spencer   if (S == "COMMONPAGESIZE")
1417708019c4SRui Ueyama     return Target->PageSize;
1418e2cc07bcSMichael J. Spencer   if (S == "MAXPAGESIZE")
1419e2cc07bcSMichael J. Spencer     return Target->MaxPageSize;
1420708019c4SRui Ueyama   error("unknown constant: " + S);
1421708019c4SRui Ueyama   return 0;
1422708019c4SRui Ueyama }
1423708019c4SRui Ueyama 
1424626e0b08SRui Ueyama // Parses Tok as an integer. Returns true if successful.
1425626e0b08SRui Ueyama // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1426626e0b08SRui Ueyama // and decimal numbers. Decimal numbers may have "K" (kilo) or
1427626e0b08SRui Ueyama // "M" (mega) prefixes.
14289f2f7ad9SGeorge Rimar static bool readInteger(StringRef Tok, uint64_t &Result) {
1429eaeafb2bSSimon Atanasyan   if (Tok.startswith("-")) {
1430eaeafb2bSSimon Atanasyan     if (!readInteger(Tok.substr(1), Result))
1431eaeafb2bSSimon Atanasyan       return false;
1432eaeafb2bSSimon Atanasyan     Result = -Result;
1433eaeafb2bSSimon Atanasyan     return true;
1434eaeafb2bSSimon Atanasyan   }
14359f2f7ad9SGeorge Rimar   if (Tok.startswith_lower("0x"))
14369f2f7ad9SGeorge Rimar     return !Tok.substr(2).getAsInteger(16, Result);
14379f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("H"))
14389f2f7ad9SGeorge Rimar     return !Tok.drop_back().getAsInteger(16, Result);
14399f2f7ad9SGeorge Rimar 
14409f2f7ad9SGeorge Rimar   int Suffix = 1;
14419f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("K")) {
14429f2f7ad9SGeorge Rimar     Suffix = 1024;
14439f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
14449f2f7ad9SGeorge Rimar   } else if (Tok.endswith_lower("M")) {
14459f2f7ad9SGeorge Rimar     Suffix = 1024 * 1024;
14469f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
14479f2f7ad9SGeorge Rimar   }
14489f2f7ad9SGeorge Rimar   if (Tok.getAsInteger(10, Result))
14499f2f7ad9SGeorge Rimar     return false;
14509f2f7ad9SGeorge Rimar   Result *= Suffix;
14519f2f7ad9SGeorge Rimar   return true;
14529f2f7ad9SGeorge Rimar }
14539f2f7ad9SGeorge Rimar 
1454708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
14556ad7dfccSRui Ueyama   if (peek() == "(")
14566ad7dfccSRui Ueyama     return readParenExpr();
1457708019c4SRui Ueyama 
14586ad7dfccSRui Ueyama   StringRef Tok = next();
1459708019c4SRui Ueyama 
1460eaeafb2bSSimon Atanasyan   if (Tok == "~") {
1461eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1462eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return ~E(Dot); };
1463eaeafb2bSSimon Atanasyan   }
1464eaeafb2bSSimon Atanasyan   if (Tok == "-") {
1465eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1466eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return -E(Dot); };
1467eaeafb2bSSimon Atanasyan   }
1468eaeafb2bSSimon Atanasyan 
1469708019c4SRui Ueyama   // Built-in functions are parsed here.
1470708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
147196659df0SGeorge Rimar   if (Tok == "ADDR") {
147296659df0SGeorge Rimar     expect("(");
147396659df0SGeorge Rimar     StringRef Name = next();
147496659df0SGeorge Rimar     expect(")");
1475884e786dSGeorge Rimar     return
1476884e786dSGeorge Rimar         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
147796659df0SGeorge Rimar   }
1478eefa758eSGeorge Rimar   if (Tok == "ASSERT")
1479eefa758eSGeorge Rimar     return readAssert();
1480708019c4SRui Ueyama   if (Tok == "ALIGN") {
14816ad7dfccSRui Ueyama     Expr E = readParenExpr();
1482708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1483708019c4SRui Ueyama   }
1484708019c4SRui Ueyama   if (Tok == "CONSTANT") {
1485708019c4SRui Ueyama     expect("(");
1486708019c4SRui Ueyama     StringRef Tok = next();
1487708019c4SRui Ueyama     expect(")");
1488708019c4SRui Ueyama     return [=](uint64_t Dot) { return getConstant(Tok); };
1489708019c4SRui Ueyama   }
1490f34f45fdSGeorge Rimar   if (Tok == "DEFINED") {
1491f34f45fdSGeorge Rimar     expect("(");
1492f34f45fdSGeorge Rimar     StringRef Tok = next();
1493f34f45fdSGeorge Rimar     expect(")");
1494*f2821028SGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
1495f34f45fdSGeorge Rimar   }
149654c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
149754c145ceSRafael Espindola     expect("(");
149854c145ceSRafael Espindola     next();
149954c145ceSRafael Espindola     expect(",");
15008c658bf8SGeorge Rimar     Expr E = readExpr();
150154c145ceSRafael Espindola     expect(")");
15028c658bf8SGeorge Rimar     return [=](uint64_t Dot) { return E(Dot); };
150354c145ceSRafael Espindola   }
1504708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
1505708019c4SRui Ueyama     expect("(");
1506708019c4SRui Ueyama     Expr E = readExpr();
1507708019c4SRui Ueyama     expect(",");
1508708019c4SRui Ueyama     readExpr();
1509708019c4SRui Ueyama     expect(")");
1510f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1511708019c4SRui Ueyama   }
1512708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
1513708019c4SRui Ueyama     expect("(");
1514708019c4SRui Ueyama     expect(".");
1515708019c4SRui Ueyama     expect(")");
1516708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
1517708019c4SRui Ueyama   }
1518276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
1519276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1520276b4e64SGeorge Rimar   // the next page boundary for simplicity.
1521276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
1522276b4e64SGeorge Rimar     expect("(");
152397bdc722SRafael Espindola     readExpr();
1524276b4e64SGeorge Rimar     expect(",");
1525276b4e64SGeorge Rimar     readExpr();
1526276b4e64SGeorge Rimar     expect(")");
1527276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1528276b4e64SGeorge Rimar   }
15299e69450eSGeorge Rimar   if (Tok == "SIZEOF") {
15309e69450eSGeorge Rimar     expect("(");
15319e69450eSGeorge Rimar     StringRef Name = next();
15329e69450eSGeorge Rimar     expect(")");
1533884e786dSGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
15349e69450eSGeorge Rimar   }
153536fac7f0SEugene Leviant   if (Tok == "ALIGNOF") {
153636fac7f0SEugene Leviant     expect("(");
153736fac7f0SEugene Leviant     StringRef Name = next();
153836fac7f0SEugene Leviant     expect(")");
153936fac7f0SEugene Leviant     return
154036fac7f0SEugene Leviant         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
154136fac7f0SEugene Leviant   }
1542e32a3598SGeorge Rimar   if (Tok == "SIZEOF_HEADERS")
1543884e786dSGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1544708019c4SRui Ueyama 
15459f2f7ad9SGeorge Rimar   // Tok is a literal number.
15469f2f7ad9SGeorge Rimar   uint64_t V;
15479f2f7ad9SGeorge Rimar   if (readInteger(Tok, V))
15489f2f7ad9SGeorge Rimar     return [=](uint64_t Dot) { return V; };
15499f2f7ad9SGeorge Rimar 
15509f2f7ad9SGeorge Rimar   // Tok is a symbol name.
155130835ea4SGeorge Rimar   if (Tok != "." && !isValidCIdentifier(Tok))
1552708019c4SRui Ueyama     setError("malformed number: " + Tok);
155330835ea4SGeorge Rimar   return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
1554a9c5a528SGeorge Rimar }
1555708019c4SRui Ueyama 
1556708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
1557708019c4SRui Ueyama   next();
1558708019c4SRui Ueyama   Expr L = readExpr();
1559708019c4SRui Ueyama   expect(":");
1560708019c4SRui Ueyama   Expr R = readExpr();
1561708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1562708019c4SRui Ueyama }
1563708019c4SRui Ueyama 
15646ad7dfccSRui Ueyama Expr ScriptParser::readParenExpr() {
15656ad7dfccSRui Ueyama   expect("(");
15666ad7dfccSRui Ueyama   Expr E = readExpr();
15676ad7dfccSRui Ueyama   expect(")");
15686ad7dfccSRui Ueyama   return E;
15696ad7dfccSRui Ueyama }
15706ad7dfccSRui Ueyama 
1571bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1572bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
1573bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
1574bbe38602SEugene Leviant     StringRef Tok = next();
1575bbe38602SEugene Leviant     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1576bbe38602SEugene Leviant     if (Tok.empty()) {
1577bbe38602SEugene Leviant       setError("section header name is empty");
1578bbe38602SEugene Leviant       break;
1579bbe38602SEugene Leviant     }
1580bbe38602SEugene Leviant     Phdrs.push_back(Tok);
1581bbe38602SEugene Leviant   }
1582bbe38602SEugene Leviant   return Phdrs;
1583bbe38602SEugene Leviant }
1584bbe38602SEugene Leviant 
1585bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
1586bbe38602SEugene Leviant   StringRef Tok = next();
1587b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
1588b0f6c590SRui Ueyama                      .Case("PT_NULL", PT_NULL)
1589b0f6c590SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
1590b0f6c590SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1591b0f6c590SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
1592b0f6c590SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
1593b0f6c590SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
1594b0f6c590SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
1595b0f6c590SRui Ueyama                      .Case("PT_TLS", PT_TLS)
1596b0f6c590SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1597b0f6c590SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1598b0f6c590SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1599b0f6c590SRui Ueyama                      .Default(-1);
1600bbe38602SEugene Leviant 
1601b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1602b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1603b0f6c590SRui Ueyama     return PT_NULL;
1604b0f6c590SRui Ueyama   }
1605b0f6c590SRui Ueyama   return Ret;
1606bbe38602SEugene Leviant }
1607bbe38602SEugene Leviant 
160895769b4aSRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
160920b6598cSGeorge Rimar   // Identifiers start at 2 because 0 and 1 are reserved
161020b6598cSGeorge Rimar   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
161120b6598cSGeorge Rimar   size_t VersionId = Config->VersionDefinitions.size() + 2;
161220b6598cSGeorge Rimar   Config->VersionDefinitions.push_back({VerStr, VersionId});
161320b6598cSGeorge Rimar 
161420b6598cSGeorge Rimar   if (skip("global:") || peek() != "local:")
161520b6598cSGeorge Rimar     readGlobal(VerStr);
161620b6598cSGeorge Rimar   if (skip("local:"))
161720b6598cSGeorge Rimar     readLocal();
161820b6598cSGeorge Rimar   expect("}");
161920b6598cSGeorge Rimar 
162020b6598cSGeorge Rimar   // Each version may have a parent version. For example, "Ver2" defined as
162120b6598cSGeorge Rimar   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
162220b6598cSGeorge Rimar   // version hierarchy is, probably against your instinct, purely for human; the
162320b6598cSGeorge Rimar   // runtime doesn't care about them at all. In LLD, we simply skip the token.
162420b6598cSGeorge Rimar   if (!VerStr.empty() && peek() != ";")
162520b6598cSGeorge Rimar     next();
162620b6598cSGeorge Rimar   expect(";");
162720b6598cSGeorge Rimar }
162820b6598cSGeorge Rimar 
162920b6598cSGeorge Rimar void ScriptParser::readLocal() {
163020b6598cSGeorge Rimar   Config->DefaultSymbolVersion = VER_NDX_LOCAL;
163120b6598cSGeorge Rimar   expect("*");
163220b6598cSGeorge Rimar   expect(";");
163320b6598cSGeorge Rimar }
163420b6598cSGeorge Rimar 
163520b6598cSGeorge Rimar void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1636cd574a5eSGeorge Rimar   expect("\"C++\"");
163720b6598cSGeorge Rimar   expect("{");
163820b6598cSGeorge Rimar 
163920b6598cSGeorge Rimar   for (;;) {
164020b6598cSGeorge Rimar     if (peek() == "}" || Error)
164120b6598cSGeorge Rimar       break;
1642cd574a5eSGeorge Rimar     bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1643cd574a5eSGeorge Rimar     Globals->push_back({unquote(next()), true, HasWildcard});
164420b6598cSGeorge Rimar     expect(";");
164520b6598cSGeorge Rimar   }
164620b6598cSGeorge Rimar 
164720b6598cSGeorge Rimar   expect("}");
164820b6598cSGeorge Rimar   expect(";");
164920b6598cSGeorge Rimar }
165020b6598cSGeorge Rimar 
165120b6598cSGeorge Rimar void ScriptParser::readGlobal(StringRef VerStr) {
165220b6598cSGeorge Rimar   std::vector<SymbolVersion> *Globals;
165320b6598cSGeorge Rimar   if (VerStr.empty())
165420b6598cSGeorge Rimar     Globals = &Config->VersionScriptGlobals;
165520b6598cSGeorge Rimar   else
165620b6598cSGeorge Rimar     Globals = &Config->VersionDefinitions.back().Globals;
165720b6598cSGeorge Rimar 
165820b6598cSGeorge Rimar   for (;;) {
165920b6598cSGeorge Rimar     if (skip("extern"))
166020b6598cSGeorge Rimar       readExtern(Globals);
166120b6598cSGeorge Rimar 
166220b6598cSGeorge Rimar     StringRef Cur = peek();
166320b6598cSGeorge Rimar     if (Cur == "}" || Cur == "local:" || Error)
166420b6598cSGeorge Rimar       return;
166520b6598cSGeorge Rimar     next();
1666cd574a5eSGeorge Rimar     Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
166720b6598cSGeorge Rimar     expect(";");
166820b6598cSGeorge Rimar   }
166920b6598cSGeorge Rimar }
167020b6598cSGeorge Rimar 
167116b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
167216b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
167316b0cc9eSSimon Atanasyan     return false;
167416b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
167516b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
167616b0cc9eSSimon Atanasyan       return true;
167716b0cc9eSSimon Atanasyan   return false;
167816b0cc9eSSimon Atanasyan }
167916b0cc9eSSimon Atanasyan 
168007320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
168116b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
168220b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
168320b6598cSGeorge Rimar }
168420b6598cSGeorge Rimar 
168520b6598cSGeorge Rimar void elf::readVersionScript(MemoryBufferRef MB) {
168620b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), false).readVersionScript();
1687f7c5fbb1SRui Ueyama }
16881ebc8ed7SRui Ueyama 
168907320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
169007320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
169107320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
169207320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1693