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 
1418f66df92SGeorge Rimar static bool checkConstraint(uint64_t Flags, ConstraintKind Kind) {
1428f66df92SGeorge Rimar   bool RO = (Kind == ConstraintKind::ReadOnly);
1438f66df92SGeorge Rimar   bool RW = (Kind == ConstraintKind::ReadWrite);
1448f66df92SGeorge Rimar   bool Writable = Flags & SHF_WRITE;
145adcdb664SRui Ueyama   return !(RO && Writable) && !(RW && !Writable);
1468f66df92SGeorge Rimar }
1478f66df92SGeorge Rimar 
14848c3f1ceSRui Ueyama template <class ELFT>
149e71a3f8aSRafael Espindola static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
15006ae6836SGeorge Rimar                              ConstraintKind Kind) {
1518f66df92SGeorge Rimar   if (Kind == ConstraintKind::NoConstraint)
1528f66df92SGeorge Rimar     return true;
153d3190795SRafael Espindola   return llvm::all_of(Sections, [=](InputSectionData *Sec2) {
154d3190795SRafael Espindola     auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
1558f66df92SGeorge Rimar     return checkConstraint(Sec->getSectionHdr()->sh_flags, Kind);
15606ae6836SGeorge Rimar   });
15706ae6836SGeorge Rimar }
15806ae6836SGeorge Rimar 
159d3190795SRafael Espindola // Compute and remember which sections the InputSectionDescription matches.
160be94e1b6SRafael Espindola template <class ELFT>
161e71a3f8aSRafael Espindola void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
1624dc07becSRui Ueyama   // Collects all sections that satisfy constraints of I
1634dc07becSRui Ueyama   // and attach them to I.
1644dc07becSRui Ueyama   for (SectionPattern &Pat : I->SectionPatterns) {
165395281cfSGeorge Rimar     for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
1663ff27f49SRui Ueyama       StringRef Filename = sys::path::filename(F->getName());
167*f135f0ecSRafael Espindola       if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
1683ff27f49SRui Ueyama         continue;
1694dc07becSRui Ueyama 
170be94e1b6SRafael Espindola       for (InputSectionBase<ELFT> *S : F->getSections())
171*f135f0ecSRafael Espindola         if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
172d3190795SRafael Espindola           I->Sections.push_back(S);
173*f135f0ecSRafael Espindola       if (Pat.SectionRe.match("COMMON"))
174d3190795SRafael Espindola         I->Sections.push_back(CommonInputSection<ELFT>::X);
175395281cfSGeorge Rimar     }
176395281cfSGeorge Rimar   }
177d3190795SRafael Espindola 
1784dc07becSRui Ueyama   // Sort for SORT() commands.
179b2a0abdfSRui Ueyama   if (I->SortInner != SortSectionPolicy::Default)
180d3190795SRafael Espindola     std::stable_sort(I->Sections.begin(), I->Sections.end(),
181d3190795SRafael Espindola                      getComparator(I->SortInner));
182b2a0abdfSRui Ueyama   if (I->SortOuter != SortSectionPolicy::Default)
183d3190795SRafael Espindola     std::stable_sort(I->Sections.begin(), I->Sections.end(),
184d3190795SRafael Espindola                      getComparator(I->SortOuter));
185d3190795SRafael Espindola 
186d3190795SRafael Espindola   // We do not add duplicate input sections, so mark them with a dummy output
187d3190795SRafael Espindola   // section for now.
188d3190795SRafael Espindola   for (InputSectionData *S : I->Sections) {
189d3190795SRafael Espindola     auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
190d3190795SRafael Espindola     S2->OutSec = (OutputSectionBase<ELFT> *)-1;
191d3190795SRafael Espindola   }
192be94e1b6SRafael Espindola }
193be94e1b6SRafael Espindola 
194be94e1b6SRafael Espindola template <class ELFT>
195be94e1b6SRafael Espindola void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
196be94e1b6SRafael Espindola   for (InputSectionBase<ELFT> *S : V) {
197be94e1b6SRafael Espindola     S->Live = false;
198be94e1b6SRafael Espindola     reportDiscarded(S);
199be94e1b6SRafael Espindola   }
200be94e1b6SRafael Espindola }
201be94e1b6SRafael Espindola 
20206ae6836SGeorge Rimar template <class ELFT>
2030b9ce6a4SRui Ueyama std::vector<InputSectionBase<ELFT> *>
20406ae6836SGeorge Rimar LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
2050b9ce6a4SRui Ueyama   std::vector<InputSectionBase<ELFT> *> Ret;
206e7f912cdSRui Ueyama 
20706ae6836SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
2087c3ff2ebSRafael Espindola     auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
2097c3ff2ebSRafael Espindola     if (!Cmd)
2100b9ce6a4SRui Ueyama       continue;
211e71a3f8aSRafael Espindola     computeInputSections(Cmd);
212d3190795SRafael Espindola     for (InputSectionData *S : Cmd->Sections)
213d3190795SRafael Espindola       Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
2140b9ce6a4SRui Ueyama   }
215e71a3f8aSRafael Espindola 
2160b9ce6a4SRui Ueyama   return Ret;
2170b9ce6a4SRui Ueyama }
2180b9ce6a4SRui Ueyama 
219e5d3ca50SPetr Hosek template <class ELFT>
22010897f18SRafael Espindola static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
22110897f18SRafael Espindola                                             StringRef OutsecName) {
22210897f18SRafael Espindola   // When using linker script the merge rules are different.
22310897f18SRafael Espindola   // Unfortunately, linker scripts are name based. This means that expressions
22410897f18SRafael Espindola   // like *(.foo*) can refer to multiple input sections that would normally be
22510897f18SRafael Espindola   // placed in different output sections. We cannot put them in different
22610897f18SRafael Espindola   // output sections or we would produce wrong results for
22710897f18SRafael Espindola   // start = .; *(.foo.*) end = .; *(.bar)
22810897f18SRafael Espindola   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
22910897f18SRafael Espindola   // another. The problem is that there is no way to layout those output
23010897f18SRafael Espindola   // sections such that the .foo sections are the only thing between the
23110897f18SRafael Espindola   // start and end symbols.
23210897f18SRafael Espindola 
23310897f18SRafael Espindola   // An extra annoyance is that we cannot simply disable merging of the contents
23410897f18SRafael Espindola   // of SHF_MERGE sections, but our implementation requires one output section
23510897f18SRafael Espindola   // per "kind" (string or not, which size/aligment).
23610897f18SRafael Espindola   // Fortunately, creating symbols in the middle of a merge section is not
23710897f18SRafael Espindola   // supported by bfd or gold, so we can just create multiple section in that
23810897f18SRafael Espindola   // case.
23910897f18SRafael Espindola   const typename ELFT::Shdr *H = C->getSectionHdr();
24010897f18SRafael Espindola   typedef typename ELFT::uint uintX_t;
24110897f18SRafael Espindola   uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
24210897f18SRafael Espindola 
24310897f18SRafael Espindola   uintX_t Alignment = 0;
24410897f18SRafael Espindola   if (isa<MergeInputSection<ELFT>>(C))
24510897f18SRafael Espindola     Alignment = std::max(H->sh_addralign, H->sh_entsize);
24610897f18SRafael Espindola 
24710897f18SRafael Espindola   return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
24810897f18SRafael Espindola }
24910897f18SRafael Espindola 
25010897f18SRafael Espindola template <class ELFT>
25120d03194SEugene Leviant void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
25220d03194SEugene Leviant                                     InputSectionBase<ELFT> *Sec,
25320d03194SEugene Leviant                                     StringRef Name) {
25428c1597aSRafael Espindola   OutputSectionBase<ELFT> *OutSec;
25528c1597aSRafael Espindola   bool IsNew;
25610897f18SRafael Espindola   std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
25728c1597aSRafael Espindola   if (IsNew)
25828c1597aSRafael Espindola     OutputSections->push_back(OutSec);
25920d03194SEugene Leviant   OutSec->addSection(Sec);
26020d03194SEugene Leviant }
26120d03194SEugene Leviant 
26220d03194SEugene Leviant template <class ELFT>
26320d03194SEugene Leviant void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
26428c1597aSRafael Espindola 
2657c3ff2ebSRafael Espindola   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
2667c3ff2ebSRafael Espindola     auto Iter = Opt.Commands.begin() + I;
2677c3ff2ebSRafael Espindola     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
2682ab5f73dSRui Ueyama     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
2692ab5f73dSRui Ueyama       if (shouldDefine<ELFT>(Cmd))
2702ab5f73dSRui Ueyama         addRegular<ELFT>(Cmd);
2712ab5f73dSRui Ueyama       continue;
2722ab5f73dSRui Ueyama     }
27320d03194SEugene Leviant     if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
27420d03194SEugene Leviant       // If we don't have SECTIONS then output sections have already been
275194470cdSGeorge Rimar       // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
27620d03194SEugene Leviant       // will not be called, so ASSERT should be evaluated now.
27720d03194SEugene Leviant       if (!Opt.HasSections)
27820d03194SEugene Leviant         Cmd->Expression(0);
27920d03194SEugene Leviant       continue;
28020d03194SEugene Leviant     }
2812ab5f73dSRui Ueyama 
282ceabe80eSEugene Leviant     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
2837bd37870SRafael Espindola       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
2847bd37870SRafael Espindola 
28548c3f1ceSRui Ueyama       if (Cmd->Name == "/DISCARD/") {
2867bd37870SRafael Espindola         discard(V);
28748c3f1ceSRui Ueyama         continue;
28848c3f1ceSRui Ueyama       }
2890b9ce6a4SRui Ueyama 
2907c3ff2ebSRafael Espindola       if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
2917c3ff2ebSRafael Espindola         for (InputSectionBase<ELFT> *S : V)
2927c3ff2ebSRafael Espindola           S->OutSec = nullptr;
2937c3ff2ebSRafael Espindola         Opt.Commands.erase(Iter);
294dfbbbc86SGeorge Rimar         --I;
2957c3ff2ebSRafael Espindola         continue;
2967c3ff2ebSRafael Espindola       }
2977c3ff2ebSRafael Espindola 
2987c3ff2ebSRafael Espindola       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
2997c3ff2ebSRafael Espindola         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
3007c3ff2ebSRafael Espindola           if (shouldDefine<ELFT>(OutCmd))
3017c3ff2ebSRafael Espindola             addSymbol<ELFT>(OutCmd);
3027c3ff2ebSRafael Espindola 
30397403d15SEugene Leviant       if (V.empty())
3040b9ce6a4SRui Ueyama         continue;
3050b9ce6a4SRui Ueyama 
306a14b13d8SGeorge Rimar       for (InputSectionBase<ELFT> *Sec : V) {
30720d03194SEugene Leviant         addSection(Factory, Sec, Cmd->Name);
30820d03194SEugene Leviant         if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
309db24d9c3SGeorge Rimar           Sec->Alignment = Subalign;
31020d03194SEugene Leviant       }
311eea3114fSGeorge Rimar     }
31248c3f1ceSRui Ueyama   }
313db24d9c3SGeorge Rimar }
314e63d81bdSEugene Leviant 
31520d03194SEugene Leviant template <class ELFT>
31620d03194SEugene Leviant void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
31720d03194SEugene Leviant   processCommands(Factory);
3180b9ce6a4SRui Ueyama   // Add orphan sections.
31920d03194SEugene Leviant   for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
32020d03194SEugene Leviant     for (InputSectionBase<ELFT> *S : F->getSections())
32120d03194SEugene Leviant       if (!isDiscarded(S) && !S->OutSec)
32220d03194SEugene Leviant         addSection(Factory, S, getOutputSectionName(S));
323e63d81bdSEugene Leviant }
324e63d81bdSEugene Leviant 
325db741e72SEugene Leviant // Sets value of a section-defined symbol. Two kinds of
326db741e72SEugene Leviant // symbols are processed: synthetic symbols, whose value
327db741e72SEugene Leviant // is an offset from beginning of section and regular
328db741e72SEugene Leviant // symbols whose value is absolute.
329db741e72SEugene Leviant template <class ELFT>
330db741e72SEugene Leviant static void assignSectionSymbol(SymbolAssignment *Cmd,
331db741e72SEugene Leviant                                 OutputSectionBase<ELFT> *Sec,
332db741e72SEugene Leviant                                 typename ELFT::uint Off) {
333db741e72SEugene Leviant   if (!Cmd->Sym)
334db741e72SEugene Leviant     return;
335db741e72SEugene Leviant 
336db741e72SEugene Leviant   if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
337db741e72SEugene Leviant     Body->Section = Sec;
338db741e72SEugene Leviant     Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
339db741e72SEugene Leviant     return;
340db741e72SEugene Leviant   }
341db741e72SEugene Leviant   auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
342db741e72SEugene Leviant   Body->Value = Cmd->Expression(Sec->getVA() + Off);
343db741e72SEugene Leviant }
344db741e72SEugene Leviant 
345d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
346d3190795SRafael Espindola   if (!AlreadyOutputIS.insert(S).second)
347ceabe80eSEugene Leviant     return;
348d3190795SRafael Espindola   bool IsTbss =
349d3190795SRafael Espindola       (CurOutSec->getFlags() & SHF_TLS) && CurOutSec->getType() == SHT_NOBITS;
350d3190795SRafael Espindola 
351d3190795SRafael Espindola   uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
352d3190795SRafael Espindola   Pos = alignTo(Pos, S->Alignment);
353d3190795SRafael Espindola   S->OutSecOff = Pos - CurOutSec->getVA();
354d3190795SRafael Espindola   Pos += S->getSize();
355d3190795SRafael Espindola 
356d3190795SRafael Espindola   // Update output section size after adding each section. This is so that
357d3190795SRafael Espindola   // SIZEOF works correctly in the case below:
358d3190795SRafael Espindola   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
359d3190795SRafael Espindola   CurOutSec->setSize(Pos - CurOutSec->getVA());
360d3190795SRafael Espindola 
361d3190795SRafael Espindola   if (!IsTbss)
362d3190795SRafael Espindola     Dot = Pos;
3632de509c3SRui Ueyama }
364ceabe80eSEugene Leviant 
365d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::flush() {
366d3190795SRafael Espindola   if (auto *OutSec = dyn_cast_or_null<OutputSection<ELFT>>(CurOutSec)) {
367d3190795SRafael Espindola     for (InputSection<ELFT> *I : OutSec->Sections)
368d3190795SRafael Espindola       output(I);
369d3190795SRafael Espindola     AlreadyOutputOS.insert(CurOutSec);
370d3190795SRafael Espindola   }
371d3190795SRafael Espindola }
37297403d15SEugene Leviant 
373d3190795SRafael Espindola template <class ELFT>
374d3190795SRafael Espindola void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
375d3190795SRafael Espindola   if (CurOutSec == Sec)
376d3190795SRafael Espindola     return;
377d3190795SRafael Espindola   if (AlreadyOutputOS.count(Sec))
378d3190795SRafael Espindola     return;
379d3190795SRafael Espindola 
380d3190795SRafael Espindola   flush();
381d3190795SRafael Espindola   CurOutSec = Sec;
382d3190795SRafael Espindola 
383d3190795SRafael Espindola   Dot = alignTo(Dot, CurOutSec->getAlignment());
384d3190795SRafael Espindola   CurOutSec->setVA(Dot);
385d3190795SRafael Espindola }
386d3190795SRafael Espindola 
387d3190795SRafael Espindola template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
388d3190795SRafael Espindola   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
38997403d15SEugene Leviant     if (AssignCmd->Name == ".") {
39097403d15SEugene Leviant       // Update to location counter means update to section size.
391d3190795SRafael Espindola       Dot = AssignCmd->Expression(Dot);
392d3190795SRafael Espindola       CurOutSec->setSize(Dot - CurOutSec->getVA());
393d3190795SRafael Espindola       return;
39497403d15SEugene Leviant     }
395d3190795SRafael Espindola     assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
396d3190795SRafael Espindola     return;
39797403d15SEugene Leviant   }
398d3190795SRafael Espindola   auto &ICmd = cast<InputSectionDescription>(Base);
399d3190795SRafael Espindola   for (InputSectionData *ID : ICmd.Sections) {
400d3190795SRafael Espindola     auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
401d3190795SRafael Espindola     switchTo(IB->OutSec);
402d3190795SRafael Espindola     if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
403d3190795SRafael Espindola       output(I);
404d3190795SRafael Espindola     else if (AlreadyOutputOS.insert(CurOutSec).second)
405d3190795SRafael Espindola       Dot += CurOutSec->getSize();
406ceabe80eSEugene Leviant   }
407ceabe80eSEugene Leviant }
408ceabe80eSEugene Leviant 
4098f66df92SGeorge Rimar template <class ELFT>
410a14b13d8SGeorge Rimar static std::vector<OutputSectionBase<ELFT> *>
411a14b13d8SGeorge Rimar findSections(OutputSectionCommand &Cmd,
412d3190795SRafael Espindola              const std::vector<OutputSectionBase<ELFT> *> &Sections) {
413a14b13d8SGeorge Rimar   std::vector<OutputSectionBase<ELFT> *> Ret;
414a14b13d8SGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : Sections)
4157c3ff2ebSRafael Espindola     if (Sec->getName() == Cmd.Name)
416a14b13d8SGeorge Rimar       Ret.push_back(Sec);
417a14b13d8SGeorge Rimar   return Ret;
4188f66df92SGeorge Rimar }
4198f66df92SGeorge Rimar 
420d3190795SRafael Espindola template <class ELFT>
421d3190795SRafael Espindola void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
422d3190795SRafael Espindola   std::vector<OutputSectionBase<ELFT> *> Sections =
423d3190795SRafael Espindola       findSections(*Cmd, *OutputSections);
424d3190795SRafael Espindola   if (Sections.empty())
425d3190795SRafael Espindola     return;
426d3190795SRafael Espindola   switchTo(Sections[0]);
427d3190795SRafael Espindola 
428d3190795SRafael Espindola   // Find the last section output location. We will output orphan sections
429d3190795SRafael Espindola   // there so that end symbols point to the correct location.
430d3190795SRafael Espindola   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
431d3190795SRafael Espindola                         [](const std::unique_ptr<BaseCommand> &Cmd) {
432d3190795SRafael Espindola                           return !isa<SymbolAssignment>(*Cmd);
433d3190795SRafael Espindola                         })
434d3190795SRafael Espindola                .base();
435d3190795SRafael Espindola   for (auto I = Cmd->Commands.begin(); I != E; ++I)
436d3190795SRafael Espindola     process(**I);
437d3190795SRafael Espindola   flush();
438d3190795SRafael Espindola   for (OutputSectionBase<ELFT> *Base : Sections) {
439d3190795SRafael Espindola     if (!AlreadyOutputOS.insert(Base).second)
440d3190795SRafael Espindola       continue;
441d3190795SRafael Espindola     switchTo(Base);
442d3190795SRafael Espindola     Dot += CurOutSec->getSize();
443d3190795SRafael Espindola   }
444b31dd370SGeorge Rimar   std::for_each(E, Cmd->Commands.end(),
445b31dd370SGeorge Rimar                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
446d3190795SRafael Espindola }
447d3190795SRafael Espindola 
448a4b41dcaSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
449652852c5SGeorge Rimar   // Orphan sections are sections present in the input files which
4507c18c28cSRui Ueyama   // are not explicitly placed into the output file by the linker script.
4517c18c28cSRui Ueyama   // We place orphan sections at end of file.
4527c18c28cSRui Ueyama   // Other linkers places them using some heuristics as described in
453652852c5SGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
454aab6d5c5SRafael Espindola 
455aab6d5c5SRafael Espindola   // The OutputSections are already in the correct order.
456aab6d5c5SRafael Espindola   // This loops creates or moves commands as needed so that they are in the
457aab6d5c5SRafael Espindola   // correct order.
458aab6d5c5SRafael Espindola   int CmdIndex = 0;
459e5cc668eSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
460652852c5SGeorge Rimar     StringRef Name = Sec->getName();
461aab6d5c5SRafael Espindola 
462aab6d5c5SRafael Espindola     // Find the last spot where we can insert a command and still get the
463aab6d5c5SRafael Espindola     // correct order.
464aab6d5c5SRafael Espindola     auto CmdIter = Opt.Commands.begin() + CmdIndex;
465aab6d5c5SRafael Espindola     auto E = Opt.Commands.end();
466aab6d5c5SRafael Espindola     while (CmdIter != E && !isa<OutputSectionCommand>(**CmdIter)) {
467aab6d5c5SRafael Espindola       ++CmdIter;
468aab6d5c5SRafael Espindola       ++CmdIndex;
469aab6d5c5SRafael Espindola     }
470aab6d5c5SRafael Espindola 
471aab6d5c5SRafael Espindola     auto Pos =
472aab6d5c5SRafael Espindola         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
473aab6d5c5SRafael Espindola           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
474aab6d5c5SRafael Espindola           return Cmd && Cmd->Name == Name;
475aab6d5c5SRafael Espindola         });
476aab6d5c5SRafael Espindola     if (Pos == E) {
477aab6d5c5SRafael Espindola       Opt.Commands.insert(CmdIter,
478aab6d5c5SRafael Espindola                           llvm::make_unique<OutputSectionCommand>(Name));
479aab6d5c5SRafael Espindola     } else {
480aab6d5c5SRafael Espindola       // If linker script lists alloc/non-alloc sections is the wrong order,
481aab6d5c5SRafael Espindola       // this does a right rotate to bring the desired command in place.
482373343bdSRafael Espindola       auto RPos = llvm::make_reverse_iterator(Pos + 1);
483373343bdSRafael Espindola       std::rotate(RPos, RPos + 1, llvm::make_reverse_iterator(CmdIter));
484aab6d5c5SRafael Espindola     }
485aab6d5c5SRafael Espindola     ++CmdIndex;
486652852c5SGeorge Rimar   }
487652852c5SGeorge Rimar 
4887c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
4894f7500bfSRui Ueyama   Dot = getHeaderSize();
490652852c5SGeorge Rimar 
491076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
492076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
4938d083e6aSRui Ueyama       if (Cmd->Name == ".") {
4948d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
4958d083e6aSRui Ueyama       } else if (Cmd->Sym) {
4968d083e6aSRui Ueyama         cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
4978d083e6aSRui Ueyama       }
49805ef4cffSRui Ueyama       continue;
499652852c5SGeorge Rimar     }
500652852c5SGeorge Rimar 
501eefa758eSGeorge Rimar     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
502eefa758eSGeorge Rimar       Cmd->Expression(Dot);
503eefa758eSGeorge Rimar       continue;
504eefa758eSGeorge Rimar     }
505eefa758eSGeorge Rimar 
506076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
507652852c5SGeorge Rimar 
50858e5c4dcSGeorge Rimar     if (Cmd->AddrExpr)
50958e5c4dcSGeorge Rimar       Dot = Cmd->AddrExpr(Dot);
51058e5c4dcSGeorge Rimar 
511d3190795SRafael Espindola     assignOffsets(Cmd);
512a14b13d8SGeorge Rimar   }
513467c4d55SEugene Leviant 
514aab6d5c5SRafael Espindola   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
515aab6d5c5SRafael Espindola   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
516aab6d5c5SRafael Espindola     if (Sec->getFlags() & SHF_ALLOC)
517aab6d5c5SRafael Espindola       MinVA = std::min(MinVA, Sec->getVA());
518aab6d5c5SRafael Espindola     else
519d3190795SRafael Espindola       Sec->setVA(0);
520aab6d5c5SRafael Espindola   }
521aab6d5c5SRafael Espindola 
5224ec013acSRafael Espindola   uintX_t HeaderSize =
5234ec013acSRafael Espindola       Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
5244ec013acSRafael Espindola   if (HeaderSize > MinVA)
5254ec013acSRafael Espindola     fatal("Not enough space for ELF and program headers");
5264ec013acSRafael Espindola 
52764c32d6fSRafael Espindola   // ELF and Program headers need to be right before the first section in
528b91e7118SGeorge Rimar   // memory. Set their addresses accordingly.
5294ec013acSRafael Espindola   MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
530467c4d55SEugene Leviant   Out<ELFT>::ElfHeader->setVA(MinVA);
531467c4d55SEugene Leviant   Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
532fb8978fcSDima Stepanov }
533652852c5SGeorge Rimar 
534464daadcSRui Ueyama // Creates program headers as instructed by PHDRS linker script command.
53507320e40SRui Ueyama template <class ELFT>
536a4b41dcaSRafael Espindola std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
537edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
538bbe38602SEugene Leviant 
539464daadcSRui Ueyama   // Process PHDRS and FILEHDR keywords because they are not
540464daadcSRui Ueyama   // real output sections and cannot be added in the following loop.
541bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
542edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
543edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
544bbe38602SEugene Leviant 
545bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
546adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
547bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
548adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
54956b21c86SEugene Leviant 
55056b21c86SEugene Leviant     if (Cmd.LMAExpr) {
55156b21c86SEugene Leviant       Phdr.H.p_paddr = Cmd.LMAExpr(0);
55256b21c86SEugene Leviant       Phdr.HasLMA = true;
55356b21c86SEugene Leviant     }
554bbe38602SEugene Leviant   }
555bbe38602SEugene Leviant 
556464daadcSRui Ueyama   // Add output sections to program headers.
557edebbdf1SRui Ueyama   PhdrEntry<ELFT> *Load = nullptr;
558edebbdf1SRui Ueyama   uintX_t Flags = PF_R;
559464daadcSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
560bbe38602SEugene Leviant     if (!(Sec->getFlags() & SHF_ALLOC))
561bbe38602SEugene Leviant       break;
562bbe38602SEugene Leviant 
563edebbdf1SRui Ueyama     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
564bbe38602SEugene Leviant     if (!PhdrIds.empty()) {
565bbe38602SEugene Leviant       // Assign headers specified by linker script
566bbe38602SEugene Leviant       for (size_t Id : PhdrIds) {
567edebbdf1SRui Ueyama         Ret[Id].add(Sec);
568865bf863SEugene Leviant         if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
5690b113671SRafael Espindola           Ret[Id].H.p_flags |= Sec->getPhdrFlags();
570bbe38602SEugene Leviant       }
571bbe38602SEugene Leviant     } else {
572bbe38602SEugene Leviant       // If we have no load segment or flags've changed then we want new load
573bbe38602SEugene Leviant       // segment.
5740b113671SRafael Espindola       uintX_t NewFlags = Sec->getPhdrFlags();
575bbe38602SEugene Leviant       if (Load == nullptr || Flags != NewFlags) {
576edebbdf1SRui Ueyama         Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
577bbe38602SEugene Leviant         Flags = NewFlags;
578bbe38602SEugene Leviant       }
57918f084ffSRui Ueyama       Load->add(Sec);
580bbe38602SEugene Leviant     }
581bbe38602SEugene Leviant   }
582edebbdf1SRui Ueyama   return Ret;
583bbe38602SEugene Leviant }
584bbe38602SEugene Leviant 
585f9bc3bd2SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
586f9bc3bd2SEugene Leviant   // Ignore .interp section in case we have PHDRS specification
587f9bc3bd2SEugene Leviant   // and PT_INTERP isn't listed.
588f9bc3bd2SEugene Leviant   return !Opt.PhdrsCommands.empty() &&
589f9bc3bd2SEugene Leviant          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
590f9bc3bd2SEugene Leviant            return Cmd.Type == PT_INTERP;
591f9bc3bd2SEugene Leviant          }) == Opt.PhdrsCommands.end();
592f9bc3bd2SEugene Leviant }
593f9bc3bd2SEugene Leviant 
594bbe38602SEugene Leviant template <class ELFT>
59507320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
596f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
597f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
598f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
599f6c3ccefSGeorge Rimar         return Cmd->Filler;
600e2ee72b5SGeorge Rimar   return {};
601e2ee72b5SGeorge Rimar }
602e2ee72b5SGeorge Rimar 
603206fffa1SGeorge Rimar template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
6048ceadb38SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
6058ceadb38SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
6068ceadb38SGeorge Rimar       if (Cmd->LmaExpr && Cmd->Name == Name)
6078ceadb38SGeorge Rimar         return Cmd->LmaExpr;
6088ceadb38SGeorge Rimar   return {};
6098ceadb38SGeorge Rimar }
6108ceadb38SGeorge Rimar 
611c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
612c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
613c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
614c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
615076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
616f510fa6bSRui Ueyama   int I = 0;
617f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
618076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
619076fe157SGeorge Rimar       if (Cmd->Name == Name)
620f510fa6bSRui Ueyama         return I;
621f510fa6bSRui Ueyama     ++I;
622f510fa6bSRui Ueyama   }
623f510fa6bSRui Ueyama   return INT_MAX;
62471b26e94SGeorge Rimar }
62571b26e94SGeorge Rimar 
62671b26e94SGeorge Rimar // A compartor to sort output sections. Returns -1 or 1 if
62771b26e94SGeorge Rimar // A or B are mentioned in linker script. Otherwise, returns 0.
62807320e40SRui Ueyama template <class ELFT>
62907320e40SRui Ueyama int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
630c3e2a4b0SRui Ueyama   int I = getSectionIndex(A);
631c3e2a4b0SRui Ueyama   int J = getSectionIndex(B);
632c3e2a4b0SRui Ueyama   if (I == INT_MAX && J == INT_MAX)
633717677afSRui Ueyama     return 0;
634717677afSRui Ueyama   return I < J ? -1 : 1;
635717677afSRui Ueyama }
636717677afSRui Ueyama 
637bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
638bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
639bbe38602SEugene Leviant }
640bbe38602SEugene Leviant 
6419e69450eSGeorge Rimar template <class ELFT>
642884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
64396659df0SGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
64496659df0SGeorge Rimar     if (Sec->getName() == Name)
64596659df0SGeorge Rimar       return Sec->getVA();
64696659df0SGeorge Rimar   error("undefined section " + Name);
64796659df0SGeorge Rimar   return 0;
64896659df0SGeorge Rimar }
64996659df0SGeorge Rimar 
65096659df0SGeorge Rimar template <class ELFT>
651884e786dSGeorge Rimar uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
6529e69450eSGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
6539e69450eSGeorge Rimar     if (Sec->getName() == Name)
6549e69450eSGeorge Rimar       return Sec->getSize();
6559e69450eSGeorge Rimar   error("undefined section " + Name);
6569e69450eSGeorge Rimar   return 0;
6579e69450eSGeorge Rimar }
6589e69450eSGeorge Rimar 
65936fac7f0SEugene Leviant template <class ELFT>
66036fac7f0SEugene Leviant uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
66136fac7f0SEugene Leviant   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
66236fac7f0SEugene Leviant     if (Sec->getName() == Name)
66336fac7f0SEugene Leviant       return Sec->getAlignment();
66436fac7f0SEugene Leviant   error("undefined section " + Name);
66536fac7f0SEugene Leviant   return 0;
66636fac7f0SEugene Leviant }
66736fac7f0SEugene Leviant 
668884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
669e32a3598SGeorge Rimar   return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
670e32a3598SGeorge Rimar }
671e32a3598SGeorge Rimar 
672884e786dSGeorge Rimar template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
673884e786dSGeorge Rimar   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
674884e786dSGeorge Rimar     return B->getVA<ELFT>();
675884e786dSGeorge Rimar   error("symbol not found: " + S);
676884e786dSGeorge Rimar   return 0;
677884e786dSGeorge Rimar }
678884e786dSGeorge Rimar 
679bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
680bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
681bbe38602SEugene Leviant // PHDRS {} script block.
682bbe38602SEugene Leviant template <class ELFT>
683edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
684076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
685076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
686edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
68731d842f5SGeorge Rimar       continue;
68831d842f5SGeorge Rimar 
68929c5a2a9SRui Ueyama     std::vector<size_t> Ret;
69029c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
69129c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
69229c5a2a9SRui Ueyama     return Ret;
693bbe38602SEugene Leviant   }
69431d842f5SGeorge Rimar   return {};
69531d842f5SGeorge Rimar }
696bbe38602SEugene Leviant 
69729c5a2a9SRui Ueyama template <class ELFT>
69829c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
69929c5a2a9SRui Ueyama   size_t I = 0;
70029c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
70129c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
70229c5a2a9SRui Ueyama       return I;
70329c5a2a9SRui Ueyama     ++I;
70429c5a2a9SRui Ueyama   }
70529c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
70629c5a2a9SRui Ueyama   return 0;
70729c5a2a9SRui Ueyama }
70829c5a2a9SRui Ueyama 
70907320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
710c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
711c3794e58SGeorge Rimar 
712f7c5fbb1SRui Ueyama public:
71307320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
714f23b2320SGeorge Rimar 
71520b6598cSGeorge Rimar   void readLinkerScript();
71620b6598cSGeorge Rimar   void readVersionScript();
717f7c5fbb1SRui Ueyama 
718f7c5fbb1SRui Ueyama private:
71952a1509eSRui Ueyama   void addFile(StringRef Path);
72052a1509eSRui Ueyama 
721f7c5fbb1SRui Ueyama   void readAsNeeded();
72290c5099eSDenis Protivensky   void readEntry();
72383f406cfSGeorge Rimar   void readExtern();
724f7c5fbb1SRui Ueyama   void readGroup();
72531aa1f83SRui Ueyama   void readInclude();
726ee59282bSRui Ueyama   void readOutput();
7279159ce93SDavide Italiano   void readOutputArch();
728f7c5fbb1SRui Ueyama   void readOutputFormat();
729bbe38602SEugene Leviant   void readPhdrs();
73068a39a65SDavide Italiano   void readSearchDir();
7318e3b38abSDenis Protivensky   void readSections();
73295769b4aSRui Ueyama   void readVersion();
73395769b4aSRui Ueyama   void readVersionScriptCommand();
7348e3b38abSDenis Protivensky 
735113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
736ff1f29e0SGeorge Rimar   std::vector<uint8_t> readFill();
73710416564SRui Ueyama   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
738ff1f29e0SGeorge Rimar   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
739bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
740a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionDescription(StringRef Tok);
741c91930a1SGeorge Rimar   Regex readFilePatterns();
742395281cfSGeorge Rimar   void readSectionExcludes(InputSectionDescription *Cmd);
743a2496cbeSGeorge Rimar   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
744bbe38602SEugene Leviant   unsigned readPhdrType();
745be394db3SGeorge Rimar   SortSectionPolicy readSortKind();
746a35e39caSPetr Hosek   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
747db741e72SEugene Leviant   SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
74803fc010eSGeorge Rimar   void readSort();
749eefa758eSGeorge Rimar   Expr readAssert();
750708019c4SRui Ueyama 
751708019c4SRui Ueyama   Expr readExpr();
752708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
753708019c4SRui Ueyama   Expr readPrimary();
754708019c4SRui Ueyama   Expr readTernary(Expr Cond);
7556ad7dfccSRui Ueyama   Expr readParenExpr();
756f7c5fbb1SRui Ueyama 
75720b6598cSGeorge Rimar   // For parsing version script.
75820b6598cSGeorge Rimar   void readExtern(std::vector<SymbolVersion> *Globals);
75995769b4aSRui Ueyama   void readVersionDeclaration(StringRef VerStr);
76020b6598cSGeorge Rimar   void readGlobal(StringRef VerStr);
76120b6598cSGeorge Rimar   void readLocal();
76220b6598cSGeorge Rimar 
76307320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
76407320e40SRui Ueyama   StringSaver Saver = {ScriptConfig->Alloc};
76516b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
766f7c5fbb1SRui Ueyama };
767f7c5fbb1SRui Ueyama 
76820b6598cSGeorge Rimar void ScriptParser::readVersionScript() {
76995769b4aSRui Ueyama   readVersionScriptCommand();
77020b6598cSGeorge Rimar   if (!atEOF())
77195769b4aSRui Ueyama     setError("EOF expected, but got " + next());
77295769b4aSRui Ueyama }
77395769b4aSRui Ueyama 
77495769b4aSRui Ueyama void ScriptParser::readVersionScriptCommand() {
77595769b4aSRui Ueyama   if (skip("{")) {
77695769b4aSRui Ueyama     readVersionDeclaration("");
77720b6598cSGeorge Rimar     return;
77820b6598cSGeorge Rimar   }
77920b6598cSGeorge Rimar 
78095769b4aSRui Ueyama   while (!atEOF() && !Error && peek() != "}") {
78120b6598cSGeorge Rimar     StringRef VerStr = next();
78220b6598cSGeorge Rimar     if (VerStr == "{") {
78395769b4aSRui Ueyama       setError("anonymous version definition is used in "
78495769b4aSRui Ueyama                "combination with other version definitions");
78520b6598cSGeorge Rimar       return;
78620b6598cSGeorge Rimar     }
78720b6598cSGeorge Rimar     expect("{");
78895769b4aSRui Ueyama     readVersionDeclaration(VerStr);
78920b6598cSGeorge Rimar   }
79020b6598cSGeorge Rimar }
79120b6598cSGeorge Rimar 
79295769b4aSRui Ueyama void ScriptParser::readVersion() {
79395769b4aSRui Ueyama   expect("{");
79495769b4aSRui Ueyama   readVersionScriptCommand();
79595769b4aSRui Ueyama   expect("}");
79695769b4aSRui Ueyama }
79795769b4aSRui Ueyama 
79820b6598cSGeorge Rimar void ScriptParser::readLinkerScript() {
799f7c5fbb1SRui Ueyama   while (!atEOF()) {
800f7c5fbb1SRui Ueyama     StringRef Tok = next();
801a27eeccaSRui Ueyama     if (Tok == ";")
802a27eeccaSRui Ueyama       continue;
803a27eeccaSRui Ueyama 
80420d03194SEugene Leviant     if (Tok == "ASSERT") {
80520d03194SEugene Leviant       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
80620d03194SEugene Leviant     } else if (Tok == "ENTRY") {
807a27eeccaSRui Ueyama       readEntry();
808a27eeccaSRui Ueyama     } else if (Tok == "EXTERN") {
809a27eeccaSRui Ueyama       readExtern();
810a27eeccaSRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
811a27eeccaSRui Ueyama       readGroup();
812a27eeccaSRui Ueyama     } else if (Tok == "INCLUDE") {
813a27eeccaSRui Ueyama       readInclude();
814a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT") {
815a27eeccaSRui Ueyama       readOutput();
816a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
817a27eeccaSRui Ueyama       readOutputArch();
818a27eeccaSRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
819a27eeccaSRui Ueyama       readOutputFormat();
820a27eeccaSRui Ueyama     } else if (Tok == "PHDRS") {
821a27eeccaSRui Ueyama       readPhdrs();
822a27eeccaSRui Ueyama     } else if (Tok == "SEARCH_DIR") {
823a27eeccaSRui Ueyama       readSearchDir();
824a27eeccaSRui Ueyama     } else if (Tok == "SECTIONS") {
825a27eeccaSRui Ueyama       readSections();
826a27eeccaSRui Ueyama     } else if (Tok == "VERSION") {
827a27eeccaSRui Ueyama       readVersion();
828db741e72SEugene Leviant     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
8290df80befSPetr Hosek       Opt.Commands.emplace_back(Cmd);
830e5d3ca50SPetr Hosek     } else {
8315761042dSGeorge Rimar       setError("unknown directive: " + Tok);
832f7c5fbb1SRui Ueyama     }
833f7c5fbb1SRui Ueyama   }
834e5d3ca50SPetr Hosek }
835f7c5fbb1SRui Ueyama 
836717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
83716b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
83816b0cc9eSSimon Atanasyan     SmallString<128> Path;
83916b0cc9eSSimon Atanasyan     (Config->Sysroot + S).toStringRef(Path);
84016b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
84116b0cc9eSSimon Atanasyan       Driver->addFile(Saver.save(Path.str()));
84216b0cc9eSSimon Atanasyan       return;
84316b0cc9eSSimon Atanasyan     }
84416b0cc9eSSimon Atanasyan   }
84516b0cc9eSSimon Atanasyan 
846f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
84752a1509eSRui Ueyama     Driver->addFile(S);
84852a1509eSRui Ueyama   } else if (S.startswith("=")) {
84952a1509eSRui Ueyama     if (Config->Sysroot.empty())
85052a1509eSRui Ueyama       Driver->addFile(S.substr(1));
85152a1509eSRui Ueyama     else
85252a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
85352a1509eSRui Ueyama   } else if (S.startswith("-l")) {
85421eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
855a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
856a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
85752a1509eSRui Ueyama   } else {
85852a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
85952a1509eSRui Ueyama     if (Path.empty())
860777f9630SGeorge Rimar       setError("unable to find " + S);
861025d59b1SRui Ueyama     else
86252a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
86352a1509eSRui Ueyama   }
86452a1509eSRui Ueyama }
86552a1509eSRui Ueyama 
866717677afSRui Ueyama void ScriptParser::readAsNeeded() {
867f7c5fbb1SRui Ueyama   expect("(");
86835da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
86935da9b6eSRui Ueyama   Config->AsNeeded = true;
870a2acc931SRui Ueyama   while (!Error && !skip(")"))
871cd574a5eSGeorge Rimar     addFile(unquote(next()));
87235da9b6eSRui Ueyama   Config->AsNeeded = Orig;
873f7c5fbb1SRui Ueyama }
874f7c5fbb1SRui Ueyama 
875717677afSRui Ueyama void ScriptParser::readEntry() {
87690c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
87790c5099eSDenis Protivensky   expect("(");
87890c5099eSDenis Protivensky   StringRef Tok = next();
87990c5099eSDenis Protivensky   if (Config->Entry.empty())
88090c5099eSDenis Protivensky     Config->Entry = Tok;
88190c5099eSDenis Protivensky   expect(")");
88290c5099eSDenis Protivensky }
88390c5099eSDenis Protivensky 
884717677afSRui Ueyama void ScriptParser::readExtern() {
88583f406cfSGeorge Rimar   expect("(");
886a2acc931SRui Ueyama   while (!Error && !skip(")"))
887a2acc931SRui Ueyama     Config->Undefined.push_back(next());
88883f406cfSGeorge Rimar }
88983f406cfSGeorge Rimar 
890717677afSRui Ueyama void ScriptParser::readGroup() {
891f7c5fbb1SRui Ueyama   expect("(");
892a2acc931SRui Ueyama   while (!Error && !skip(")")) {
893f7c5fbb1SRui Ueyama     StringRef Tok = next();
894a2acc931SRui Ueyama     if (Tok == "AS_NEEDED")
895f7c5fbb1SRui Ueyama       readAsNeeded();
896a2acc931SRui Ueyama     else
897cd574a5eSGeorge Rimar       addFile(unquote(Tok));
898f7c5fbb1SRui Ueyama   }
899f7c5fbb1SRui Ueyama }
900f7c5fbb1SRui Ueyama 
901717677afSRui Ueyama void ScriptParser::readInclude() {
90231aa1f83SRui Ueyama   StringRef Tok = next();
903cd574a5eSGeorge Rimar   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
904025d59b1SRui Ueyama   if (!MBOrErr) {
9055761042dSGeorge Rimar     setError("cannot open " + Tok);
906025d59b1SRui Ueyama     return;
907025d59b1SRui Ueyama   }
90831aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
909a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
910a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
91131aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
91231aa1f83SRui Ueyama }
91331aa1f83SRui Ueyama 
914717677afSRui Ueyama void ScriptParser::readOutput() {
915ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
916ee59282bSRui Ueyama   expect("(");
917ee59282bSRui Ueyama   StringRef Tok = next();
918ee59282bSRui Ueyama   if (Config->OutputFile.empty())
919cd574a5eSGeorge Rimar     Config->OutputFile = unquote(Tok);
920ee59282bSRui Ueyama   expect(")");
921ee59282bSRui Ueyama }
922ee59282bSRui Ueyama 
923717677afSRui Ueyama void ScriptParser::readOutputArch() {
9249159ce93SDavide Italiano   // Error checking only for now.
9259159ce93SDavide Italiano   expect("(");
9269159ce93SDavide Italiano   next();
9279159ce93SDavide Italiano   expect(")");
9289159ce93SDavide Italiano }
9299159ce93SDavide Italiano 
930717677afSRui Ueyama void ScriptParser::readOutputFormat() {
931f7c5fbb1SRui Ueyama   // Error checking only for now.
932f7c5fbb1SRui Ueyama   expect("(");
933f7c5fbb1SRui Ueyama   next();
9346836c618SDavide Italiano   StringRef Tok = next();
9356836c618SDavide Italiano   if (Tok == ")")
9366836c618SDavide Italiano     return;
937025d59b1SRui Ueyama   if (Tok != ",") {
9385761042dSGeorge Rimar     setError("unexpected token: " + Tok);
939025d59b1SRui Ueyama     return;
940025d59b1SRui Ueyama   }
9416836c618SDavide Italiano   next();
9426836c618SDavide Italiano   expect(",");
9436836c618SDavide Italiano   next();
944f7c5fbb1SRui Ueyama   expect(")");
945f7c5fbb1SRui Ueyama }
946f7c5fbb1SRui Ueyama 
947bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
948bbe38602SEugene Leviant   expect("{");
949bbe38602SEugene Leviant   while (!Error && !skip("}")) {
950bbe38602SEugene Leviant     StringRef Tok = next();
95156b21c86SEugene Leviant     Opt.PhdrsCommands.push_back(
95256b21c86SEugene Leviant         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
953bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
954bbe38602SEugene Leviant 
955bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
956bbe38602SEugene Leviant     do {
957bbe38602SEugene Leviant       Tok = next();
958bbe38602SEugene Leviant       if (Tok == ";")
959bbe38602SEugene Leviant         break;
960bbe38602SEugene Leviant       if (Tok == "FILEHDR")
961bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
962bbe38602SEugene Leviant       else if (Tok == "PHDRS")
963bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
96456b21c86SEugene Leviant       else if (Tok == "AT")
96556b21c86SEugene Leviant         PhdrCmd.LMAExpr = readParenExpr();
966865bf863SEugene Leviant       else if (Tok == "FLAGS") {
967865bf863SEugene Leviant         expect("(");
968eb685cd7SRafael Espindola         // Passing 0 for the value of dot is a bit of a hack. It means that
969eb685cd7SRafael Espindola         // we accept expressions like ".|1".
970eb685cd7SRafael Espindola         PhdrCmd.Flags = readExpr()(0);
971865bf863SEugene Leviant         expect(")");
972865bf863SEugene Leviant       } else
973bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
974bbe38602SEugene Leviant     } while (!Error);
975bbe38602SEugene Leviant   }
976bbe38602SEugene Leviant }
977bbe38602SEugene Leviant 
978717677afSRui Ueyama void ScriptParser::readSearchDir() {
97968a39a65SDavide Italiano   expect("(");
98086c5fb82SRui Ueyama   StringRef Tok = next();
9816c7ad13fSRui Ueyama   if (!Config->Nostdlib)
982cd574a5eSGeorge Rimar     Config->SearchPaths.push_back(unquote(Tok));
98368a39a65SDavide Italiano   expect(")");
98468a39a65SDavide Italiano }
98568a39a65SDavide Italiano 
986717677afSRui Ueyama void ScriptParser::readSections() {
987e05336ffSEugene Leviant   Opt.HasSections = true;
9888e3b38abSDenis Protivensky   expect("{");
989652852c5SGeorge Rimar   while (!Error && !skip("}")) {
990113cdec9SRui Ueyama     StringRef Tok = next();
991db741e72SEugene Leviant     BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
992ceabe80eSEugene Leviant     if (!Cmd) {
993ceabe80eSEugene Leviant       if (Tok == "ASSERT")
994eefa758eSGeorge Rimar         Cmd = new AssertCommand(readAssert());
995ceabe80eSEugene Leviant       else
99610416564SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
9978e3b38abSDenis Protivensky     }
99810416564SRui Ueyama     Opt.Commands.emplace_back(Cmd);
999652852c5SGeorge Rimar   }
1000708019c4SRui Ueyama }
10018e3b38abSDenis Protivensky 
1002708019c4SRui Ueyama static int precedence(StringRef Op) {
1003708019c4SRui Ueyama   return StringSwitch<int>(Op)
1004708019c4SRui Ueyama       .Case("*", 4)
1005708019c4SRui Ueyama       .Case("/", 4)
1006708019c4SRui Ueyama       .Case("+", 3)
1007708019c4SRui Ueyama       .Case("-", 3)
1008708019c4SRui Ueyama       .Case("<", 2)
1009708019c4SRui Ueyama       .Case(">", 2)
1010708019c4SRui Ueyama       .Case(">=", 2)
1011708019c4SRui Ueyama       .Case("<=", 2)
1012708019c4SRui Ueyama       .Case("==", 2)
1013708019c4SRui Ueyama       .Case("!=", 2)
1014708019c4SRui Ueyama       .Case("&", 1)
1015cc3dd629SRafael Espindola       .Case("|", 1)
1016708019c4SRui Ueyama       .Default(-1);
1017708019c4SRui Ueyama }
1018708019c4SRui Ueyama 
1019c91930a1SGeorge Rimar Regex ScriptParser::readFilePatterns() {
102010416564SRui Ueyama   std::vector<StringRef> V;
102110416564SRui Ueyama   while (!Error && !skip(")"))
102210416564SRui Ueyama     V.push_back(next());
1023c91930a1SGeorge Rimar   return compileGlobPatterns(V);
10240702c4e8SGeorge Rimar }
10250702c4e8SGeorge Rimar 
1026be394db3SGeorge Rimar SortSectionPolicy ScriptParser::readSortKind() {
1027742c3836SRui Ueyama   if (skip("SORT") || skip("SORT_BY_NAME"))
1028be394db3SGeorge Rimar     return SortSectionPolicy::Name;
1029742c3836SRui Ueyama   if (skip("SORT_BY_ALIGNMENT"))
1030be394db3SGeorge Rimar     return SortSectionPolicy::Alignment;
1031575208caSGeorge Rimar   if (skip("SORT_BY_INIT_PRIORITY"))
1032be394db3SGeorge Rimar     return SortSectionPolicy::Priority;
1033be394db3SGeorge Rimar   if (skip("SORT_NONE"))
1034be394db3SGeorge Rimar     return SortSectionPolicy::None;
1035b2a0abdfSRui Ueyama   return SortSectionPolicy::Default;
1036be394db3SGeorge Rimar }
1037be394db3SGeorge Rimar 
1038be394db3SGeorge Rimar static void selectSortKind(InputSectionDescription *Cmd) {
1039b2a0abdfSRui Ueyama   if (Cmd->SortOuter == SortSectionPolicy::None) {
1040b2a0abdfSRui Ueyama     Cmd->SortOuter = SortSectionPolicy::Default;
1041be394db3SGeorge Rimar     return;
1042be394db3SGeorge Rimar   }
1043be394db3SGeorge Rimar 
1044b2a0abdfSRui Ueyama   if (Cmd->SortOuter != SortSectionPolicy::Default) {
1045be394db3SGeorge Rimar     // If the section sorting command in linker script is nested, the command
1046be394db3SGeorge Rimar     // line option will be ignored.
1047b2a0abdfSRui Ueyama     if (Cmd->SortInner != SortSectionPolicy::Default)
1048be394db3SGeorge Rimar       return;
1049be394db3SGeorge Rimar     // If the section sorting command in linker script isn't nested, the
1050be394db3SGeorge Rimar     // command line option will make the section sorting command to be treated
1051be394db3SGeorge Rimar     // as nested sorting command.
1052be394db3SGeorge Rimar     Cmd->SortInner = Config->SortSection;
1053be394db3SGeorge Rimar     return;
1054be394db3SGeorge Rimar   }
1055be394db3SGeorge Rimar   // If sorting rule not specified, use command line option.
1056be394db3SGeorge Rimar   Cmd->SortOuter = Config->SortSection;
1057742c3836SRui Ueyama }
1058742c3836SRui Ueyama 
1059395281cfSGeorge Rimar // Method reads a list of sequence of excluded files and section globs given in
1060395281cfSGeorge Rimar // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1061395281cfSGeorge Rimar // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1062af03be19SGeorge Rimar // The semantics of that is next:
1063af03be19SGeorge Rimar // * Include .foo.1 from every file.
1064af03be19SGeorge Rimar // * Include .foo.2 from every file but a.o
1065af03be19SGeorge Rimar // * Include .foo.3 from every file but b.o
1066395281cfSGeorge Rimar void ScriptParser::readSectionExcludes(InputSectionDescription *Cmd) {
1067027a9e87SRui Ueyama   Regex ExcludeFileRe;
1068395281cfSGeorge Rimar   std::vector<StringRef> V;
1069395281cfSGeorge Rimar 
1070395281cfSGeorge Rimar   while (!Error) {
1071395281cfSGeorge Rimar     if (skip(")")) {
10724dc07becSRui Ueyama       Cmd->SectionPatterns.push_back(
1073395281cfSGeorge Rimar           {std::move(ExcludeFileRe), compileGlobPatterns(V)});
1074395281cfSGeorge Rimar       return;
1075395281cfSGeorge Rimar     }
1076395281cfSGeorge Rimar 
1077395281cfSGeorge Rimar     if (skip("EXCLUDE_FILE")) {
1078395281cfSGeorge Rimar       if (!V.empty()) {
10794dc07becSRui Ueyama         Cmd->SectionPatterns.push_back(
1080395281cfSGeorge Rimar             {std::move(ExcludeFileRe), compileGlobPatterns(V)});
1081395281cfSGeorge Rimar         V.clear();
1082395281cfSGeorge Rimar       }
1083395281cfSGeorge Rimar 
1084395281cfSGeorge Rimar       expect("(");
1085395281cfSGeorge Rimar       ExcludeFileRe = readFilePatterns();
1086395281cfSGeorge Rimar       continue;
1087395281cfSGeorge Rimar     }
1088395281cfSGeorge Rimar 
1089395281cfSGeorge Rimar     V.push_back(next());
1090395281cfSGeorge Rimar   }
1091395281cfSGeorge Rimar }
1092395281cfSGeorge Rimar 
1093a2496cbeSGeorge Rimar InputSectionDescription *
1094a2496cbeSGeorge Rimar ScriptParser::readInputSectionRules(StringRef FilePattern) {
1095c91930a1SGeorge Rimar   auto *Cmd = new InputSectionDescription(FilePattern);
10960ed42b0cSDavide Italiano   expect("(");
1097e7282797SDavide Italiano 
1098742c3836SRui Ueyama   // Read SORT().
1099be394db3SGeorge Rimar   SortSectionPolicy K1 = readSortKind();
1100b2a0abdfSRui Ueyama   if (K1 != SortSectionPolicy::Default) {
1101742c3836SRui Ueyama     Cmd->SortOuter = K1;
11020702c4e8SGeorge Rimar     expect("(");
1103be394db3SGeorge Rimar     SortSectionPolicy K2 = readSortKind();
1104b2a0abdfSRui Ueyama     if (K2 != SortSectionPolicy::Default) {
1105742c3836SRui Ueyama       Cmd->SortInner = K2;
1106350ece4eSGeorge Rimar       expect("(");
11074dc07becSRui Ueyama       Cmd->SectionPatterns.push_back({Regex(), readFilePatterns()});
11080702c4e8SGeorge Rimar       expect(")");
1109350ece4eSGeorge Rimar     } else {
11104dc07becSRui Ueyama       Cmd->SectionPatterns.push_back({Regex(), readFilePatterns()});
1111350ece4eSGeorge Rimar     }
1112350ece4eSGeorge Rimar     expect(")");
1113be394db3SGeorge Rimar     selectSortKind(Cmd);
111410416564SRui Ueyama     return Cmd;
11150659800eSGeorge Rimar   }
11160702c4e8SGeorge Rimar 
1117be394db3SGeorge Rimar   selectSortKind(Cmd);
1118395281cfSGeorge Rimar   readSectionExcludes(Cmd);
111910416564SRui Ueyama   return Cmd;
11200659800eSGeorge Rimar }
11210659800eSGeorge Rimar 
1122a2496cbeSGeorge Rimar InputSectionDescription *
1123a2496cbeSGeorge Rimar ScriptParser::readInputSectionDescription(StringRef Tok) {
11240659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
11250659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1126a2496cbeSGeorge Rimar   if (Tok == "KEEP") {
1127e7282797SDavide Italiano     expect("(");
1128a2496cbeSGeorge Rimar     StringRef FilePattern = next();
1129a2496cbeSGeorge Rimar     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
11300ed42b0cSDavide Italiano     expect(")");
11314dc07becSRui Ueyama     for (SectionPattern &Pat : Cmd->SectionPatterns)
11324dc07becSRui Ueyama       Opt.KeptSections.push_back(&Pat.SectionRe);
113310416564SRui Ueyama     return Cmd;
113410416564SRui Ueyama   }
1135a2496cbeSGeorge Rimar   return readInputSectionRules(Tok);
11360659800eSGeorge Rimar }
11370659800eSGeorge Rimar 
113803fc010eSGeorge Rimar void ScriptParser::readSort() {
113903fc010eSGeorge Rimar   expect("(");
114003fc010eSGeorge Rimar   expect("CONSTRUCTORS");
114103fc010eSGeorge Rimar   expect(")");
114203fc010eSGeorge Rimar }
114303fc010eSGeorge Rimar 
1144eefa758eSGeorge Rimar Expr ScriptParser::readAssert() {
1145eefa758eSGeorge Rimar   expect("(");
1146eefa758eSGeorge Rimar   Expr E = readExpr();
1147eefa758eSGeorge Rimar   expect(",");
1148cd574a5eSGeorge Rimar   StringRef Msg = unquote(next());
1149eefa758eSGeorge Rimar   expect(")");
1150eefa758eSGeorge Rimar   return [=](uint64_t Dot) {
1151eefa758eSGeorge Rimar     uint64_t V = E(Dot);
1152eefa758eSGeorge Rimar     if (!V)
1153eefa758eSGeorge Rimar       error(Msg);
1154eefa758eSGeorge Rimar     return V;
1155eefa758eSGeorge Rimar   };
1156eefa758eSGeorge Rimar }
1157eefa758eSGeorge Rimar 
115825150e8bSRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
115925150e8bSRui Ueyama // alias for =fillexp section attribute, which is different from
116025150e8bSRui Ueyama // what GNU linkers do.
116125150e8bSRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1162ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readFill() {
1163ff1f29e0SGeorge Rimar   expect("(");
1164ff1f29e0SGeorge Rimar   std::vector<uint8_t> V = readOutputSectionFiller(next());
1165ff1f29e0SGeorge Rimar   expect(")");
1166ff1f29e0SGeorge Rimar   expect(";");
1167ff1f29e0SGeorge Rimar   return V;
1168ff1f29e0SGeorge Rimar }
1169ff1f29e0SGeorge Rimar 
117010416564SRui Ueyama OutputSectionCommand *
117110416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1172076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
117358e5c4dcSGeorge Rimar 
117458e5c4dcSGeorge Rimar   // Read an address expression.
117558e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
117658e5c4dcSGeorge Rimar   if (peek() != ":")
117758e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
117858e5c4dcSGeorge Rimar 
11798e3b38abSDenis Protivensky   expect(":");
1180246f681eSDavide Italiano 
11818ceadb38SGeorge Rimar   if (skip("AT"))
11826ad7dfccSRui Ueyama     Cmd->LmaExpr = readParenExpr();
1183630c6179SGeorge Rimar   if (skip("ALIGN"))
11846ad7dfccSRui Ueyama     Cmd->AlignExpr = readParenExpr();
1185db24d9c3SGeorge Rimar   if (skip("SUBALIGN"))
1186db24d9c3SGeorge Rimar     Cmd->SubalignExpr = readParenExpr();
1187630c6179SGeorge Rimar 
1188246f681eSDavide Italiano   // Parse constraints.
1189246f681eSDavide Italiano   if (skip("ONLY_IF_RO"))
1190efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
1191246f681eSDavide Italiano   if (skip("ONLY_IF_RW"))
1192efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
11938e3b38abSDenis Protivensky   expect("{");
11948ec77e64SRui Ueyama 
1195025d59b1SRui Ueyama   while (!Error && !skip("}")) {
1196ceabe80eSEugene Leviant     StringRef Tok = next();
1197db741e72SEugene Leviant     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
1198ceabe80eSEugene Leviant       Cmd->Commands.emplace_back(Assignment);
1199ff1f29e0SGeorge Rimar     else if (Tok == "FILL")
1200ff1f29e0SGeorge Rimar       Cmd->Filler = readFill();
1201ceabe80eSEugene Leviant     else if (Tok == "SORT")
120203fc010eSGeorge Rimar       readSort();
1203a2496cbeSGeorge Rimar     else if (peek() == "(")
1204a2496cbeSGeorge Rimar       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1205ceabe80eSEugene Leviant     else
1206ceabe80eSEugene Leviant       setError("unknown command " + Tok);
12078e3b38abSDenis Protivensky   }
1208076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
1209ff1f29e0SGeorge Rimar   if (peek().startswith("="))
1210ff1f29e0SGeorge Rimar     Cmd->Filler = readOutputSectionFiller(next().drop_front());
121110416564SRui Ueyama   return Cmd;
1212f71caa2bSRui Ueyama }
12138ec77e64SRui Ueyama 
12142c8f1f04SRui Ueyama // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
12152c8f1f04SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
12162c8f1f04SRui Ueyama //
12172c8f1f04SRui Ueyama // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
12182c8f1f04SRui Ueyama // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
12192c8f1f04SRui Ueyama // as 32-bit big-endian values. We will do the same as ld.gold does
12202c8f1f04SRui Ueyama // because it's simpler than what ld.bfd does.
1221ff1f29e0SGeorge Rimar std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1222965827d6SRui Ueyama   uint32_t V;
1223ff1f29e0SGeorge Rimar   if (Tok.getAsInteger(0, V)) {
1224965827d6SRui Ueyama     setError("invalid filler expression: " + Tok);
1225f71caa2bSRui Ueyama     return {};
1226e2ee72b5SGeorge Rimar   }
1227965827d6SRui Ueyama   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
12288e3b38abSDenis Protivensky }
12298e3b38abSDenis Protivensky 
1230a35e39caSPetr Hosek SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1231a31c91b1SEugene Leviant   expect("(");
1232174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
1233a35e39caSPetr Hosek   Cmd->Provide = Provide;
1234174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
1235a31c91b1SEugene Leviant   expect(")");
1236a31c91b1SEugene Leviant   expect(";");
123710416564SRui Ueyama   return Cmd;
1238eda81a1bSEugene Leviant }
1239eda81a1bSEugene Leviant 
1240db741e72SEugene Leviant SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1241db741e72SEugene Leviant                                                         bool MakeAbsolute) {
1242ceabe80eSEugene Leviant   SymbolAssignment *Cmd = nullptr;
1243ceabe80eSEugene Leviant   if (peek() == "=" || peek() == "+=") {
1244ceabe80eSEugene Leviant     Cmd = readAssignment(Tok);
1245ceabe80eSEugene Leviant     expect(";");
1246ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE") {
1247a35e39caSPetr Hosek     Cmd = readProvideHidden(true, false);
1248a35e39caSPetr Hosek   } else if (Tok == "HIDDEN") {
1249a35e39caSPetr Hosek     Cmd = readProvideHidden(false, true);
1250ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE_HIDDEN") {
1251a35e39caSPetr Hosek     Cmd = readProvideHidden(true, true);
1252ceabe80eSEugene Leviant   }
1253db741e72SEugene Leviant   if (Cmd && MakeAbsolute)
1254db741e72SEugene Leviant     Cmd->IsAbsolute = true;
1255ceabe80eSEugene Leviant   return Cmd;
1256ceabe80eSEugene Leviant }
1257ceabe80eSEugene Leviant 
125830835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
125930835ea4SGeorge Rimar   if (S == ".")
126030835ea4SGeorge Rimar     return Dot;
1261884e786dSGeorge Rimar   return ScriptBase->getSymbolValue(S);
1262e32a3598SGeorge Rimar }
1263e32a3598SGeorge Rimar 
126430835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
126530835ea4SGeorge Rimar   StringRef Op = next();
1266db741e72SEugene Leviant   bool IsAbsolute = false;
1267db741e72SEugene Leviant   Expr E;
126830835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
1269db741e72SEugene Leviant   if (skip("ABSOLUTE")) {
1270db741e72SEugene Leviant     E = readParenExpr();
1271db741e72SEugene Leviant     IsAbsolute = true;
1272db741e72SEugene Leviant   } else {
1273db741e72SEugene Leviant     E = readExpr();
1274db741e72SEugene Leviant   }
127530835ea4SGeorge Rimar   if (Op == "+=")
127630835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1277db741e72SEugene Leviant   return new SymbolAssignment(Name, E, IsAbsolute);
127830835ea4SGeorge Rimar }
127930835ea4SGeorge Rimar 
128030835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
128130835ea4SGeorge Rimar // script expression.
128230835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
128330835ea4SGeorge Rimar 
128436c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
128536c1cd23SRui Ueyama   if (Op == "*")
128636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
128736c1cd23SRui Ueyama   if (Op == "/") {
128836c1cd23SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
128936c1cd23SRui Ueyama       uint64_t RHS = R(Dot);
129036c1cd23SRui Ueyama       if (RHS == 0) {
129136c1cd23SRui Ueyama         error("division by zero");
129236c1cd23SRui Ueyama         return 0;
129336c1cd23SRui Ueyama       }
129436c1cd23SRui Ueyama       return L(Dot) / RHS;
129536c1cd23SRui Ueyama     };
129636c1cd23SRui Ueyama   }
129736c1cd23SRui Ueyama   if (Op == "+")
129836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
129936c1cd23SRui Ueyama   if (Op == "-")
130036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
130136c1cd23SRui Ueyama   if (Op == "<")
130236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
130336c1cd23SRui Ueyama   if (Op == ">")
130436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
130536c1cd23SRui Ueyama   if (Op == ">=")
130636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
130736c1cd23SRui Ueyama   if (Op == "<=")
130836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
130936c1cd23SRui Ueyama   if (Op == "==")
131036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
131136c1cd23SRui Ueyama   if (Op == "!=")
131236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
131336c1cd23SRui Ueyama   if (Op == "&")
131436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1315cc3dd629SRafael Espindola   if (Op == "|")
1316cc3dd629SRafael Espindola     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
131736c1cd23SRui Ueyama   llvm_unreachable("invalid operator");
131836c1cd23SRui Ueyama }
131936c1cd23SRui Ueyama 
1320708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
1321708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
1322708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1323708019c4SRui Ueyama   while (!atEOF() && !Error) {
1324708019c4SRui Ueyama     // Read an operator and an expression.
1325708019c4SRui Ueyama     StringRef Op1 = peek();
1326708019c4SRui Ueyama     if (Op1 == "?")
1327708019c4SRui Ueyama       return readTernary(Lhs);
1328708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
1329a31c91b1SEugene Leviant       break;
1330a31c91b1SEugene Leviant     next();
1331708019c4SRui Ueyama     Expr Rhs = readPrimary();
1332708019c4SRui Ueyama 
1333708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
1334708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
1335708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
1336708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
1337708019c4SRui Ueyama     while (!atEOF()) {
1338708019c4SRui Ueyama       StringRef Op2 = peek();
1339708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
1340eda81a1bSEugene Leviant         break;
1341708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
1342eda81a1bSEugene Leviant     }
1343708019c4SRui Ueyama 
1344708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
1345708019c4SRui Ueyama   }
1346708019c4SRui Ueyama   return Lhs;
1347708019c4SRui Ueyama }
1348708019c4SRui Ueyama 
1349708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
1350e2cc07bcSMichael J. Spencer   if (S == "COMMONPAGESIZE")
1351708019c4SRui Ueyama     return Target->PageSize;
1352e2cc07bcSMichael J. Spencer   if (S == "MAXPAGESIZE")
1353e2cc07bcSMichael J. Spencer     return Target->MaxPageSize;
1354708019c4SRui Ueyama   error("unknown constant: " + S);
1355708019c4SRui Ueyama   return 0;
1356708019c4SRui Ueyama }
1357708019c4SRui Ueyama 
1358626e0b08SRui Ueyama // Parses Tok as an integer. Returns true if successful.
1359626e0b08SRui Ueyama // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1360626e0b08SRui Ueyama // and decimal numbers. Decimal numbers may have "K" (kilo) or
1361626e0b08SRui Ueyama // "M" (mega) prefixes.
13629f2f7ad9SGeorge Rimar static bool readInteger(StringRef Tok, uint64_t &Result) {
1363eaeafb2bSSimon Atanasyan   if (Tok.startswith("-")) {
1364eaeafb2bSSimon Atanasyan     if (!readInteger(Tok.substr(1), Result))
1365eaeafb2bSSimon Atanasyan       return false;
1366eaeafb2bSSimon Atanasyan     Result = -Result;
1367eaeafb2bSSimon Atanasyan     return true;
1368eaeafb2bSSimon Atanasyan   }
13699f2f7ad9SGeorge Rimar   if (Tok.startswith_lower("0x"))
13709f2f7ad9SGeorge Rimar     return !Tok.substr(2).getAsInteger(16, Result);
13719f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("H"))
13729f2f7ad9SGeorge Rimar     return !Tok.drop_back().getAsInteger(16, Result);
13739f2f7ad9SGeorge Rimar 
13749f2f7ad9SGeorge Rimar   int Suffix = 1;
13759f2f7ad9SGeorge Rimar   if (Tok.endswith_lower("K")) {
13769f2f7ad9SGeorge Rimar     Suffix = 1024;
13779f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
13789f2f7ad9SGeorge Rimar   } else if (Tok.endswith_lower("M")) {
13799f2f7ad9SGeorge Rimar     Suffix = 1024 * 1024;
13809f2f7ad9SGeorge Rimar     Tok = Tok.drop_back();
13819f2f7ad9SGeorge Rimar   }
13829f2f7ad9SGeorge Rimar   if (Tok.getAsInteger(10, Result))
13839f2f7ad9SGeorge Rimar     return false;
13849f2f7ad9SGeorge Rimar   Result *= Suffix;
13859f2f7ad9SGeorge Rimar   return true;
13869f2f7ad9SGeorge Rimar }
13879f2f7ad9SGeorge Rimar 
1388708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
13896ad7dfccSRui Ueyama   if (peek() == "(")
13906ad7dfccSRui Ueyama     return readParenExpr();
1391708019c4SRui Ueyama 
13926ad7dfccSRui Ueyama   StringRef Tok = next();
1393708019c4SRui Ueyama 
1394eaeafb2bSSimon Atanasyan   if (Tok == "~") {
1395eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1396eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return ~E(Dot); };
1397eaeafb2bSSimon Atanasyan   }
1398eaeafb2bSSimon Atanasyan   if (Tok == "-") {
1399eaeafb2bSSimon Atanasyan     Expr E = readPrimary();
1400eaeafb2bSSimon Atanasyan     return [=](uint64_t Dot) { return -E(Dot); };
1401eaeafb2bSSimon Atanasyan   }
1402eaeafb2bSSimon Atanasyan 
1403708019c4SRui Ueyama   // Built-in functions are parsed here.
1404708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
140596659df0SGeorge Rimar   if (Tok == "ADDR") {
140696659df0SGeorge Rimar     expect("(");
140796659df0SGeorge Rimar     StringRef Name = next();
140896659df0SGeorge Rimar     expect(")");
1409884e786dSGeorge Rimar     return
1410884e786dSGeorge Rimar         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
141196659df0SGeorge Rimar   }
1412eefa758eSGeorge Rimar   if (Tok == "ASSERT")
1413eefa758eSGeorge Rimar     return readAssert();
1414708019c4SRui Ueyama   if (Tok == "ALIGN") {
14156ad7dfccSRui Ueyama     Expr E = readParenExpr();
1416708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1417708019c4SRui Ueyama   }
1418708019c4SRui Ueyama   if (Tok == "CONSTANT") {
1419708019c4SRui Ueyama     expect("(");
1420708019c4SRui Ueyama     StringRef Tok = next();
1421708019c4SRui Ueyama     expect(")");
1422708019c4SRui Ueyama     return [=](uint64_t Dot) { return getConstant(Tok); };
1423708019c4SRui Ueyama   }
142454c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
142554c145ceSRafael Espindola     expect("(");
142654c145ceSRafael Espindola     next();
142754c145ceSRafael Espindola     expect(",");
14288c658bf8SGeorge Rimar     Expr E = readExpr();
142954c145ceSRafael Espindola     expect(")");
14308c658bf8SGeorge Rimar     return [=](uint64_t Dot) { return E(Dot); };
143154c145ceSRafael Espindola   }
1432708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
1433708019c4SRui Ueyama     expect("(");
1434708019c4SRui Ueyama     Expr E = readExpr();
1435708019c4SRui Ueyama     expect(",");
1436708019c4SRui Ueyama     readExpr();
1437708019c4SRui Ueyama     expect(")");
1438f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1439708019c4SRui Ueyama   }
1440708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
1441708019c4SRui Ueyama     expect("(");
1442708019c4SRui Ueyama     expect(".");
1443708019c4SRui Ueyama     expect(")");
1444708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
1445708019c4SRui Ueyama   }
1446276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
1447276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1448276b4e64SGeorge Rimar   // the next page boundary for simplicity.
1449276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
1450276b4e64SGeorge Rimar     expect("(");
145197bdc722SRafael Espindola     readExpr();
1452276b4e64SGeorge Rimar     expect(",");
1453276b4e64SGeorge Rimar     readExpr();
1454276b4e64SGeorge Rimar     expect(")");
1455276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1456276b4e64SGeorge Rimar   }
14579e69450eSGeorge Rimar   if (Tok == "SIZEOF") {
14589e69450eSGeorge Rimar     expect("(");
14599e69450eSGeorge Rimar     StringRef Name = next();
14609e69450eSGeorge Rimar     expect(")");
1461884e786dSGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
14629e69450eSGeorge Rimar   }
146336fac7f0SEugene Leviant   if (Tok == "ALIGNOF") {
146436fac7f0SEugene Leviant     expect("(");
146536fac7f0SEugene Leviant     StringRef Name = next();
146636fac7f0SEugene Leviant     expect(")");
146736fac7f0SEugene Leviant     return
146836fac7f0SEugene Leviant         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
146936fac7f0SEugene Leviant   }
1470e32a3598SGeorge Rimar   if (Tok == "SIZEOF_HEADERS")
1471884e786dSGeorge Rimar     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1472708019c4SRui Ueyama 
14739f2f7ad9SGeorge Rimar   // Tok is a literal number.
14749f2f7ad9SGeorge Rimar   uint64_t V;
14759f2f7ad9SGeorge Rimar   if (readInteger(Tok, V))
14769f2f7ad9SGeorge Rimar     return [=](uint64_t Dot) { return V; };
14779f2f7ad9SGeorge Rimar 
14789f2f7ad9SGeorge Rimar   // Tok is a symbol name.
147930835ea4SGeorge Rimar   if (Tok != "." && !isValidCIdentifier(Tok))
1480708019c4SRui Ueyama     setError("malformed number: " + Tok);
148130835ea4SGeorge Rimar   return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
1482a9c5a528SGeorge Rimar }
1483708019c4SRui Ueyama 
1484708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
1485708019c4SRui Ueyama   next();
1486708019c4SRui Ueyama   Expr L = readExpr();
1487708019c4SRui Ueyama   expect(":");
1488708019c4SRui Ueyama   Expr R = readExpr();
1489708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1490708019c4SRui Ueyama }
1491708019c4SRui Ueyama 
14926ad7dfccSRui Ueyama Expr ScriptParser::readParenExpr() {
14936ad7dfccSRui Ueyama   expect("(");
14946ad7dfccSRui Ueyama   Expr E = readExpr();
14956ad7dfccSRui Ueyama   expect(")");
14966ad7dfccSRui Ueyama   return E;
14976ad7dfccSRui Ueyama }
14986ad7dfccSRui Ueyama 
1499bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1500bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
1501bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
1502bbe38602SEugene Leviant     StringRef Tok = next();
1503bbe38602SEugene Leviant     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1504bbe38602SEugene Leviant     if (Tok.empty()) {
1505bbe38602SEugene Leviant       setError("section header name is empty");
1506bbe38602SEugene Leviant       break;
1507bbe38602SEugene Leviant     }
1508bbe38602SEugene Leviant     Phdrs.push_back(Tok);
1509bbe38602SEugene Leviant   }
1510bbe38602SEugene Leviant   return Phdrs;
1511bbe38602SEugene Leviant }
1512bbe38602SEugene Leviant 
1513bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
1514bbe38602SEugene Leviant   StringRef Tok = next();
1515b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
1516b0f6c590SRui Ueyama                      .Case("PT_NULL", PT_NULL)
1517b0f6c590SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
1518b0f6c590SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1519b0f6c590SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
1520b0f6c590SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
1521b0f6c590SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
1522b0f6c590SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
1523b0f6c590SRui Ueyama                      .Case("PT_TLS", PT_TLS)
1524b0f6c590SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1525b0f6c590SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1526b0f6c590SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1527b0f6c590SRui Ueyama                      .Default(-1);
1528bbe38602SEugene Leviant 
1529b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1530b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1531b0f6c590SRui Ueyama     return PT_NULL;
1532b0f6c590SRui Ueyama   }
1533b0f6c590SRui Ueyama   return Ret;
1534bbe38602SEugene Leviant }
1535bbe38602SEugene Leviant 
153695769b4aSRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
153720b6598cSGeorge Rimar   // Identifiers start at 2 because 0 and 1 are reserved
153820b6598cSGeorge Rimar   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
153920b6598cSGeorge Rimar   size_t VersionId = Config->VersionDefinitions.size() + 2;
154020b6598cSGeorge Rimar   Config->VersionDefinitions.push_back({VerStr, VersionId});
154120b6598cSGeorge Rimar 
154220b6598cSGeorge Rimar   if (skip("global:") || peek() != "local:")
154320b6598cSGeorge Rimar     readGlobal(VerStr);
154420b6598cSGeorge Rimar   if (skip("local:"))
154520b6598cSGeorge Rimar     readLocal();
154620b6598cSGeorge Rimar   expect("}");
154720b6598cSGeorge Rimar 
154820b6598cSGeorge Rimar   // Each version may have a parent version. For example, "Ver2" defined as
154920b6598cSGeorge Rimar   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
155020b6598cSGeorge Rimar   // version hierarchy is, probably against your instinct, purely for human; the
155120b6598cSGeorge Rimar   // runtime doesn't care about them at all. In LLD, we simply skip the token.
155220b6598cSGeorge Rimar   if (!VerStr.empty() && peek() != ";")
155320b6598cSGeorge Rimar     next();
155420b6598cSGeorge Rimar   expect(";");
155520b6598cSGeorge Rimar }
155620b6598cSGeorge Rimar 
155720b6598cSGeorge Rimar void ScriptParser::readLocal() {
155820b6598cSGeorge Rimar   Config->DefaultSymbolVersion = VER_NDX_LOCAL;
155920b6598cSGeorge Rimar   expect("*");
156020b6598cSGeorge Rimar   expect(";");
156120b6598cSGeorge Rimar }
156220b6598cSGeorge Rimar 
156320b6598cSGeorge Rimar void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1564cd574a5eSGeorge Rimar   expect("\"C++\"");
156520b6598cSGeorge Rimar   expect("{");
156620b6598cSGeorge Rimar 
156720b6598cSGeorge Rimar   for (;;) {
156820b6598cSGeorge Rimar     if (peek() == "}" || Error)
156920b6598cSGeorge Rimar       break;
1570cd574a5eSGeorge Rimar     bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1571cd574a5eSGeorge Rimar     Globals->push_back({unquote(next()), true, HasWildcard});
157220b6598cSGeorge Rimar     expect(";");
157320b6598cSGeorge Rimar   }
157420b6598cSGeorge Rimar 
157520b6598cSGeorge Rimar   expect("}");
157620b6598cSGeorge Rimar   expect(";");
157720b6598cSGeorge Rimar }
157820b6598cSGeorge Rimar 
157920b6598cSGeorge Rimar void ScriptParser::readGlobal(StringRef VerStr) {
158020b6598cSGeorge Rimar   std::vector<SymbolVersion> *Globals;
158120b6598cSGeorge Rimar   if (VerStr.empty())
158220b6598cSGeorge Rimar     Globals = &Config->VersionScriptGlobals;
158320b6598cSGeorge Rimar   else
158420b6598cSGeorge Rimar     Globals = &Config->VersionDefinitions.back().Globals;
158520b6598cSGeorge Rimar 
158620b6598cSGeorge Rimar   for (;;) {
158720b6598cSGeorge Rimar     if (skip("extern"))
158820b6598cSGeorge Rimar       readExtern(Globals);
158920b6598cSGeorge Rimar 
159020b6598cSGeorge Rimar     StringRef Cur = peek();
159120b6598cSGeorge Rimar     if (Cur == "}" || Cur == "local:" || Error)
159220b6598cSGeorge Rimar       return;
159320b6598cSGeorge Rimar     next();
1594cd574a5eSGeorge Rimar     Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
159520b6598cSGeorge Rimar     expect(";");
159620b6598cSGeorge Rimar   }
159720b6598cSGeorge Rimar }
159820b6598cSGeorge Rimar 
159916b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
160016b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
160116b0cc9eSSimon Atanasyan     return false;
160216b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
160316b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
160416b0cc9eSSimon Atanasyan       return true;
160516b0cc9eSSimon Atanasyan   return false;
160616b0cc9eSSimon Atanasyan }
160716b0cc9eSSimon Atanasyan 
160807320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
160916b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
161020b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
161120b6598cSGeorge Rimar }
161220b6598cSGeorge Rimar 
161320b6598cSGeorge Rimar void elf::readVersionScript(MemoryBufferRef MB) {
161420b6598cSGeorge Rimar   ScriptParser(MB.getBuffer(), false).readVersionScript();
1615f7c5fbb1SRui Ueyama }
16161ebc8ed7SRui Ueyama 
161707320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
161807320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
161907320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
162007320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1621