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 
4407320e40SRui Ueyama ScriptConfiguration *elf::ScriptConfig;
45717677afSRui Ueyama 
46ceabe80eSEugene Leviant template <class ELFT>
471602421cSRui Ueyama 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();
51ceabe80eSEugene Leviant }
52ceabe80eSEugene Leviant 
53ceabe80eSEugene Leviant template <class ELFT>
541602421cSRui Ueyama static void addSynthetic(SymbolAssignment *Cmd,
55ceabe80eSEugene Leviant                          OutputSectionBase<ELFT> *Section) {
561602421cSRui Ueyama   Symbol *Sym = Symtab<ELFT>::X->addSynthetic(Cmd->Name, Section, 0);
571602421cSRui Ueyama   Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
581602421cSRui Ueyama   Cmd->Sym = Sym->body();
59ceabe80eSEugene Leviant }
60ceabe80eSEugene Leviant 
611602421cSRui Ueyama // If a symbol was in PROVIDE(), we need to define it only when
621602421cSRui Ueyama // it is an undefined symbol.
631602421cSRui Ueyama template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
641602421cSRui Ueyama   if (Cmd->Name == ".")
65ceabe80eSEugene Leviant     return false;
661602421cSRui Ueyama   if (!Cmd->Provide)
67ceabe80eSEugene Leviant     return true;
681602421cSRui Ueyama   SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
691602421cSRui Ueyama   return B && B->isUndefined();
70ceabe80eSEugene Leviant }
71ceabe80eSEugene Leviant 
72076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
73076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
74076fe157SGeorge Rimar }
75076fe157SGeorge Rimar 
76076fe157SGeorge Rimar bool OutputSectionCommand::classof(const BaseCommand *C) {
77076fe157SGeorge Rimar   return C->Kind == OutputSectionKind;
78076fe157SGeorge Rimar }
79076fe157SGeorge Rimar 
80eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
81eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
82eea3114fSGeorge Rimar }
83eea3114fSGeorge Rimar 
84eefa758eSGeorge Rimar bool AssertCommand::classof(const BaseCommand *C) {
85eefa758eSGeorge Rimar   return C->Kind == AssertKind;
86eefa758eSGeorge Rimar }
87eefa758eSGeorge Rimar 
8836a153cdSRui Ueyama template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
89eea3114fSGeorge Rimar   return !S || !S->Live;
90717677afSRui Ueyama }
91717677afSRui Ueyama 
9207320e40SRui Ueyama template <class ELFT>
9307320e40SRui Ueyama bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
948ec77e64SRui Ueyama   for (StringRef Pat : Opt.KeptSections)
95722830a5SRui Ueyama     if (globMatch(Pat, S->getSectionName()))
968ec77e64SRui Ueyama       return true;
978ec77e64SRui Ueyama   return false;
98481c2ce6SGeorge Rimar }
99481c2ce6SGeorge Rimar 
10063dc6509SRui Ueyama static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
10163dc6509SRui Ueyama   for (StringRef Pat : Patterns)
10263dc6509SRui Ueyama     if (globMatch(Pat, S))
103eea3114fSGeorge Rimar       return true;
104eea3114fSGeorge Rimar   return false;
105eea3114fSGeorge Rimar }
106eea3114fSGeorge Rimar 
1070659800eSGeorge Rimar static bool fileMatches(const InputSectionDescription *Desc,
1080659800eSGeorge Rimar                         StringRef Filename) {
1090659800eSGeorge Rimar   if (!globMatch(Desc->FilePattern, Filename))
1100659800eSGeorge Rimar     return false;
1110659800eSGeorge Rimar   return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
1120659800eSGeorge Rimar }
1130659800eSGeorge Rimar 
1146b274810SRui Ueyama // Returns input sections filtered by given glob patterns.
1156b274810SRui Ueyama template <class ELFT>
1166b274810SRui Ueyama std::vector<InputSectionBase<ELFT> *>
117ad10c3d8SRui Ueyama LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
1180659800eSGeorge Rimar   ArrayRef<StringRef> Patterns = I->SectionPatterns;
1196b274810SRui Ueyama   std::vector<InputSectionBase<ELFT> *> Ret;
1206b274810SRui Ueyama   for (const std::unique_ptr<ObjectFile<ELFT>> &F :
1210659800eSGeorge Rimar        Symtab<ELFT>::X->getObjectFiles()) {
1220659800eSGeorge Rimar     if (fileMatches(I, sys::path::filename(F->getName())))
1236b274810SRui Ueyama       for (InputSectionBase<ELFT> *S : F->getSections())
1240659800eSGeorge Rimar         if (!isDiscarded(S) && !S->OutSec &&
1250659800eSGeorge Rimar             match(Patterns, S->getSectionName()))
1266b274810SRui Ueyama           Ret.push_back(S);
1270659800eSGeorge Rimar   }
1283e6b0277SEugene Leviant 
1293e6b0277SEugene Leviant   if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
130ad10c3d8SRui Ueyama     Ret.push_back(CommonInputSection<ELFT>::X);
1313e6b0277SEugene Leviant 
1326b274810SRui Ueyama   return Ret;
1336b274810SRui Ueyama }
1346b274810SRui Ueyama 
135ceabe80eSEugene Leviant namespace {
136dd81fe31SRui Ueyama 
137dd81fe31SRui Ueyama // You can define new symbols using linker scripts. For example,
138dd81fe31SRui Ueyama // ".text { abc.o(.text); foo = .; def.o(.text); }" defines symbol
139dd81fe31SRui Ueyama // foo just after abc.o's text section contents. This class is to
140dd81fe31SRui Ueyama // handle such symbol definitions.
141dd81fe31SRui Ueyama //
142dd81fe31SRui Ueyama // In order to handle scripts like the above one, we want to
143dd81fe31SRui Ueyama // keep symbol definitions in output sections. Because output sections
144dd81fe31SRui Ueyama // can contain only input sections, we wrap symbol definitions
145dd81fe31SRui Ueyama // with dummy input sections. This class serves that purpose.
1462c3f5010SRui Ueyama template <class ELFT> class LayoutInputSection : public InputSectionBase<ELFT> {
147ceabe80eSEugene Leviant public:
148ceabe80eSEugene Leviant   LayoutInputSection(SymbolAssignment *Cmd);
149ceabe80eSEugene Leviant   static bool classof(const InputSectionBase<ELFT> *S);
150ceabe80eSEugene Leviant   SymbolAssignment *Cmd;
151ceabe80eSEugene Leviant 
152ceabe80eSEugene Leviant private:
153ceabe80eSEugene Leviant   typename ELFT::Shdr Hdr;
154ceabe80eSEugene Leviant };
155ceabe80eSEugene Leviant 
156ceabe80eSEugene Leviant // Helper class, which builds output section list, also
157ceabe80eSEugene Leviant // creating symbol sections, when needed
158ceabe80eSEugene Leviant template <class ELFT> class OutputSectionBuilder {
159ceabe80eSEugene Leviant public:
160ceabe80eSEugene Leviant   OutputSectionBuilder(OutputSectionFactory<ELFT> &F,
161ceabe80eSEugene Leviant                        std::vector<OutputSectionBase<ELFT> *> *Out)
162ceabe80eSEugene Leviant       : Factory(F), OutputSections(Out) {}
163ceabe80eSEugene Leviant 
164ceabe80eSEugene Leviant   void addSection(StringRef OutputName, InputSectionBase<ELFT> *I);
165ceabe80eSEugene Leviant   void addSymbol(SymbolAssignment *Cmd) {
166ceabe80eSEugene Leviant     PendingSymbols.emplace_back(new LayoutInputSection<ELFT>(Cmd));
167ceabe80eSEugene Leviant   }
168ceabe80eSEugene Leviant   void flushSymbols();
169ceabe80eSEugene Leviant   void flushSection();
170ceabe80eSEugene Leviant   void finalize();
171ceabe80eSEugene Leviant 
172ceabe80eSEugene Leviant private:
173ceabe80eSEugene Leviant   OutputSectionFactory<ELFT> &Factory;
174ceabe80eSEugene Leviant   std::vector<OutputSectionBase<ELFT> *> *OutputSections;
175ceabe80eSEugene Leviant   OutputSectionBase<ELFT> *Current = nullptr;
176ceabe80eSEugene Leviant   std::vector<std::unique_ptr<LayoutInputSection<ELFT>>> PendingSymbols;
177ceabe80eSEugene Leviant   static std::vector<std::unique_ptr<LayoutInputSection<ELFT>>> OwningSections;
178ceabe80eSEugene Leviant };
179ceabe80eSEugene Leviant 
180c3cb884cSGeorge Rimar template <class ELFT>
181ceabe80eSEugene Leviant std::vector<std::unique_ptr<LayoutInputSection<ELFT>>>
182ceabe80eSEugene Leviant     OutputSectionBuilder<ELFT>::OwningSections;
183dd81fe31SRui Ueyama 
184dd81fe31SRui Ueyama } // anonymous namespace
185ceabe80eSEugene Leviant 
186ceabe80eSEugene Leviant template <class T> static T *zero(T *Val) {
187ceabe80eSEugene Leviant   memset(Val, 0, sizeof(*Val));
188ceabe80eSEugene Leviant   return Val;
189ceabe80eSEugene Leviant }
190ceabe80eSEugene Leviant 
191ceabe80eSEugene Leviant template <class ELFT>
192ceabe80eSEugene Leviant LayoutInputSection<ELFT>::LayoutInputSection(SymbolAssignment *Cmd)
1932c3f5010SRui Ueyama     : InputSectionBase<ELFT>(nullptr, zero(&Hdr),
1942c3f5010SRui Ueyama                              InputSectionBase<ELFT>::Layout),
1952c3f5010SRui Ueyama       Cmd(Cmd) {
196ceabe80eSEugene Leviant   this->Live = true;
197ceabe80eSEugene Leviant   Hdr.sh_type = SHT_NOBITS;
198ceabe80eSEugene Leviant }
199ceabe80eSEugene Leviant 
200ceabe80eSEugene Leviant template <class ELFT>
201ceabe80eSEugene Leviant bool LayoutInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
202ceabe80eSEugene Leviant   return S->SectionKind == InputSectionBase<ELFT>::Layout;
203ceabe80eSEugene Leviant }
204ceabe80eSEugene Leviant 
205ceabe80eSEugene Leviant template <class ELFT>
206ceabe80eSEugene Leviant void OutputSectionBuilder<ELFT>::addSection(StringRef OutputName,
207ceabe80eSEugene Leviant                                             InputSectionBase<ELFT> *C) {
208e63d81bdSEugene Leviant   bool IsNew;
209ceabe80eSEugene Leviant   std::tie(Current, IsNew) = Factory.create(C, OutputName);
210e63d81bdSEugene Leviant   if (IsNew)
211ceabe80eSEugene Leviant     OutputSections->push_back(Current);
212ceabe80eSEugene Leviant   flushSymbols();
213ceabe80eSEugene Leviant   Current->addSection(C);
214ceabe80eSEugene Leviant }
215ceabe80eSEugene Leviant 
216ceabe80eSEugene Leviant template <class ELFT> void OutputSectionBuilder<ELFT>::flushSymbols() {
217ceabe80eSEugene Leviant   // Only regular output sections are supported.
218ceabe80eSEugene Leviant   if (dyn_cast_or_null<OutputSection<ELFT>>(Current)) {
2191602421cSRui Ueyama     for (std::unique_ptr<LayoutInputSection<ELFT>> &I : PendingSymbols) {
2201602421cSRui Ueyama       if (I->Cmd->Name == ".") {
221ceabe80eSEugene Leviant         Current->addSection(I.get());
222ceabe80eSEugene Leviant         OwningSections.push_back(std::move(I));
2231602421cSRui Ueyama       } else if (shouldDefine<ELFT>(I->Cmd)) {
2241602421cSRui Ueyama         addSynthetic<ELFT>(I->Cmd, Current);
2251602421cSRui Ueyama         Current->addSection(I.get());
2261602421cSRui Ueyama         OwningSections.push_back(std::move(I));
2271602421cSRui Ueyama       }
228ceabe80eSEugene Leviant     }
229ceabe80eSEugene Leviant   }
230ceabe80eSEugene Leviant 
231ceabe80eSEugene Leviant   PendingSymbols.clear();
232ceabe80eSEugene Leviant }
233ceabe80eSEugene Leviant 
234ceabe80eSEugene Leviant template <class ELFT> void OutputSectionBuilder<ELFT>::flushSection() {
235ceabe80eSEugene Leviant   flushSymbols();
236ceabe80eSEugene Leviant   Current = nullptr;
237ceabe80eSEugene Leviant }
238ceabe80eSEugene Leviant 
239ceabe80eSEugene Leviant template <class ELFT> void OutputSectionBuilder<ELFT>::finalize() {
240ceabe80eSEugene Leviant   // Assign offsets to all sections which don't contain symbols
241ceabe80eSEugene Leviant   for (OutputSectionBase<ELFT> *S : *OutputSections)
242ceabe80eSEugene Leviant     if (llvm::find_if(OwningSections,
243ceabe80eSEugene Leviant                       [&](std::unique_ptr<LayoutInputSection<ELFT>> &L) {
244ceabe80eSEugene Leviant                         return L->OutSec == S;
245ceabe80eSEugene Leviant                       }) == OwningSections.end())
246ceabe80eSEugene Leviant       S->assignOffsets();
247c3cb884cSGeorge Rimar }
248c3cb884cSGeorge Rimar 
249742c3836SRui Ueyama template <class ELFT>
250742c3836SRui Ueyama static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
251742c3836SRui Ueyama   return A->getSectionName() < B->getSectionName();
2520702c4e8SGeorge Rimar }
253742c3836SRui Ueyama 
254742c3836SRui Ueyama template <class ELFT>
255742c3836SRui Ueyama static bool compareAlignment(InputSectionBase<ELFT> *A,
256742c3836SRui Ueyama                              InputSectionBase<ELFT> *B) {
257742c3836SRui Ueyama   // ">" is not a mistake. Larger alignments are placed before smaller
258742c3836SRui Ueyama   // alignments in order to reduce the amount of padding necessary.
259742c3836SRui Ueyama   // This is compatible with GNU.
260742c3836SRui Ueyama   return A->Alignment > B->Alignment;
261742c3836SRui Ueyama }
262742c3836SRui Ueyama 
263742c3836SRui Ueyama template <class ELFT>
264742c3836SRui Ueyama static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
265742c3836SRui Ueyama getComparator(SortKind K) {
266742c3836SRui Ueyama   if (K == SortByName)
267742c3836SRui Ueyama     return compareName<ELFT>;
268742c3836SRui Ueyama   return compareAlignment<ELFT>;
269742c3836SRui Ueyama }
2700702c4e8SGeorge Rimar 
2710702c4e8SGeorge Rimar template <class ELFT>
27248c3f1ceSRui Ueyama void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
27348c3f1ceSRui Ueyama   for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
27448c3f1ceSRui Ueyama     if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
27548c3f1ceSRui Ueyama       for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
27648c3f1ceSRui Ueyama         S->Live = false;
27748c3f1ceSRui Ueyama         reportDiscarded(S);
27848c3f1ceSRui Ueyama       }
27948c3f1ceSRui Ueyama     }
28048c3f1ceSRui Ueyama   }
28148c3f1ceSRui Ueyama }
28248c3f1ceSRui Ueyama 
28348c3f1ceSRui Ueyama template <class ELFT>
2849e69450eSGeorge Rimar void LinkerScript<ELFT>::createSections(
2859e69450eSGeorge Rimar     OutputSectionFactory<ELFT> &Factory) {
286ceabe80eSEugene Leviant   OutputSectionBuilder<ELFT> Builder(Factory, OutputSections);
287e7f912cdSRui Ueyama 
28848c3f1ceSRui Ueyama   for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
289ceabe80eSEugene Leviant     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
29048c3f1ceSRui Ueyama       if (Cmd->Name == "/DISCARD/") {
29148c3f1ceSRui Ueyama         discard(*Cmd);
29248c3f1ceSRui Ueyama         continue;
29348c3f1ceSRui Ueyama       }
29448c3f1ceSRui Ueyama       for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands) {
29548c3f1ceSRui Ueyama         if (auto *Cmd2 = dyn_cast<SymbolAssignment>(Base2.get())) {
29648c3f1ceSRui Ueyama           Builder.addSymbol(Cmd2);
29748c3f1ceSRui Ueyama           continue;
29848c3f1ceSRui Ueyama         }
29948c3f1ceSRui Ueyama         auto *Cmd2 = cast<InputSectionDescription>(Base2.get());
30048c3f1ceSRui Ueyama         std::vector<InputSectionBase<ELFT> *> Sections = getInputSections(Cmd2);
30148c3f1ceSRui Ueyama         if (Cmd2->SortInner)
30248c3f1ceSRui Ueyama           std::stable_sort(Sections.begin(), Sections.end(),
30348c3f1ceSRui Ueyama                            getComparator<ELFT>(Cmd2->SortInner));
30448c3f1ceSRui Ueyama         if (Cmd2->SortOuter)
30548c3f1ceSRui Ueyama           std::stable_sort(Sections.begin(), Sections.end(),
30648c3f1ceSRui Ueyama                            getComparator<ELFT>(Cmd2->SortOuter));
30748c3f1ceSRui Ueyama         for (InputSectionBase<ELFT> *S : Sections)
30848c3f1ceSRui Ueyama           Builder.addSection(Cmd->Name, S);
30948c3f1ceSRui Ueyama       }
310ceabe80eSEugene Leviant 
311ceabe80eSEugene Leviant       Builder.flushSection();
312ceabe80eSEugene Leviant     } else if (auto *Cmd2 = dyn_cast<SymbolAssignment>(Base1.get())) {
3131602421cSRui Ueyama       if (shouldDefine<ELFT>(Cmd2))
3141602421cSRui Ueyama         addRegular<ELFT>(Cmd2);
315eea3114fSGeorge Rimar     }
31648c3f1ceSRui Ueyama   }
317e63d81bdSEugene Leviant 
318e63d81bdSEugene Leviant   // Add all other input sections, which are not listed in script.
3196b274810SRui Ueyama   for (const std::unique_ptr<ObjectFile<ELFT>> &F :
3206b274810SRui Ueyama        Symtab<ELFT>::X->getObjectFiles())
3216b274810SRui Ueyama     for (InputSectionBase<ELFT> *S : F->getSections())
3226b274810SRui Ueyama       if (!isDiscarded(S) && !S->OutSec)
323ceabe80eSEugene Leviant         Builder.addSection(getOutputSectionName(S), S);
324e63d81bdSEugene Leviant 
3253c291e1aSRui Ueyama   // Remove from the output all the sections which did not meet
3263c291e1aSRui Ueyama   // the optional constraints.
3279e69450eSGeorge Rimar   filter();
328ceabe80eSEugene Leviant   Builder.finalize();
3293c291e1aSRui Ueyama }
3303c291e1aSRui Ueyama 
331c7611fc5SEugene Leviant template <class R, class T>
332c7611fc5SEugene Leviant static inline void removeElementsIf(R &Range, const T &Pred) {
333c7611fc5SEugene Leviant   Range.erase(std::remove_if(Range.begin(), Range.end(), Pred), Range.end());
334c7611fc5SEugene Leviant }
335c7611fc5SEugene Leviant 
3363c291e1aSRui Ueyama // Process ONLY_IF_RO and ONLY_IF_RW.
3379e69450eSGeorge Rimar template <class ELFT> void LinkerScript<ELFT>::filter() {
3383c291e1aSRui Ueyama   // In this loop, we remove output sections if they don't satisfy
3393c291e1aSRui Ueyama   // requested properties.
3403c291e1aSRui Ueyama   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
3413c291e1aSRui Ueyama     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
3423c291e1aSRui Ueyama     if (!Cmd || Cmd->Name == "/DISCARD/")
3433c291e1aSRui Ueyama       continue;
3443c291e1aSRui Ueyama 
345bfc4a4b7SGeorge Rimar     if (Cmd->Constraint == ConstraintKind::NoConstraint)
3463c291e1aSRui Ueyama       continue;
347bfc4a4b7SGeorge Rimar 
3483c291e1aSRui Ueyama     bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
3493c291e1aSRui Ueyama     bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
3503c291e1aSRui Ueyama 
351808d13eaSRui Ueyama     removeElementsIf(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
352808d13eaSRui Ueyama       bool Writable = (S->getFlags() & SHF_WRITE);
353c7611fc5SEugene Leviant       return S->getName() == Cmd->Name &&
354c7611fc5SEugene Leviant              ((RO && Writable) || (RW && !Writable));
355c7611fc5SEugene Leviant     });
3563c291e1aSRui Ueyama   }
357e63d81bdSEugene Leviant }
358e63d81bdSEugene Leviant 
359ceabe80eSEugene Leviant template <class ELFT> void assignOffsets(OutputSectionBase<ELFT> *Sec) {
360ceabe80eSEugene Leviant   // Non-zero size means we have assigned offsets earlier in
361ceabe80eSEugene Leviant   // OutputSectionBuilder<ELFT>::finalize
362ceabe80eSEugene Leviant   auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
363ceabe80eSEugene Leviant   if (Sec->getSize() || !OutSec)
364ceabe80eSEugene Leviant     return;
365ceabe80eSEugene Leviant 
366ceabe80eSEugene Leviant   typedef typename ELFT::uint uintX_t;
367ceabe80eSEugene Leviant   uintX_t Off = 0;
368ceabe80eSEugene Leviant 
369ceabe80eSEugene Leviant   for (InputSection<ELFT> *I : OutSec->Sections) {
370ceabe80eSEugene Leviant     if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(I)) {
371ceabe80eSEugene Leviant       uintX_t Value = L->Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
372ceabe80eSEugene Leviant       if (L->Cmd->Name == ".")
373ceabe80eSEugene Leviant         Off = Value;
374ceabe80eSEugene Leviant       else
375ceabe80eSEugene Leviant         cast<DefinedSynthetic<ELFT>>(L->Cmd->Sym)->Value = Value;
376ceabe80eSEugene Leviant     } else {
377ceabe80eSEugene Leviant       Off = alignTo(Off, I->Alignment);
378ceabe80eSEugene Leviant       I->OutSecOff = Off;
379ceabe80eSEugene Leviant       Off += I->getSize();
380ceabe80eSEugene Leviant     }
381ceabe80eSEugene Leviant     // Update section size inside for-loop, so that SIZEOF
382ceabe80eSEugene Leviant     // works correctly in the case below:
383ceabe80eSEugene Leviant     // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
384ceabe80eSEugene Leviant     Sec->setSize(Off);
385ceabe80eSEugene Leviant   }
386ceabe80eSEugene Leviant }
387ceabe80eSEugene Leviant 
388a4b41dcaSRafael Espindola template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
389652852c5SGeorge Rimar   // Orphan sections are sections present in the input files which
3907c18c28cSRui Ueyama   // are not explicitly placed into the output file by the linker script.
3917c18c28cSRui Ueyama   // We place orphan sections at end of file.
3927c18c28cSRui Ueyama   // Other linkers places them using some heuristics as described in
393652852c5SGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
394*e5cc668eSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
395652852c5SGeorge Rimar     StringRef Name = Sec->getName();
396c3e2a4b0SRui Ueyama     if (getSectionIndex(Name) == INT_MAX)
397076fe157SGeorge Rimar       Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
398652852c5SGeorge Rimar   }
399652852c5SGeorge Rimar 
4007c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
401e32a3598SGeorge Rimar   Dot = getSizeOfHeaders();
402467c4d55SEugene Leviant   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
403652852c5SGeorge Rimar   uintX_t ThreadBssOffset = 0;
404652852c5SGeorge Rimar 
405076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
406076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
4078d083e6aSRui Ueyama       if (Cmd->Name == ".") {
4088d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
4098d083e6aSRui Ueyama       } else if (Cmd->Sym) {
4108d083e6aSRui Ueyama         cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
4118d083e6aSRui Ueyama       }
41205ef4cffSRui Ueyama       continue;
413652852c5SGeorge Rimar     }
414652852c5SGeorge Rimar 
415eefa758eSGeorge Rimar     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
416eefa758eSGeorge Rimar       Cmd->Expression(Dot);
417eefa758eSGeorge Rimar       continue;
418eefa758eSGeorge Rimar     }
419eefa758eSGeorge Rimar 
420fb8978fcSDima Stepanov     // Find all the sections with required name. There can be more than
4216ad330acSGeorge Rimar     // one section with such name, if the alignment, flags or type
422fb8978fcSDima Stepanov     // attribute differs.
423076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
424*e5cc668eSRui Ueyama     for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
425076fe157SGeorge Rimar       if (Sec->getName() != Cmd->Name)
426652852c5SGeorge Rimar         continue;
427652852c5SGeorge Rimar 
42858e5c4dcSGeorge Rimar       if (Cmd->AddrExpr)
42958e5c4dcSGeorge Rimar         Dot = Cmd->AddrExpr(Dot);
43058e5c4dcSGeorge Rimar 
431630c6179SGeorge Rimar       if (Cmd->AlignExpr)
432630c6179SGeorge Rimar         Sec->updateAlignment(Cmd->AlignExpr(Dot));
433630c6179SGeorge Rimar 
434652852c5SGeorge Rimar       if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
435c998a8c0SRui Ueyama         uintX_t TVA = Dot + ThreadBssOffset;
436424b4081SRui Ueyama         TVA = alignTo(TVA, Sec->getAlignment());
437652852c5SGeorge Rimar         Sec->setVA(TVA);
438ceabe80eSEugene Leviant         assignOffsets(Sec);
439c998a8c0SRui Ueyama         ThreadBssOffset = TVA - Dot + Sec->getSize();
440652852c5SGeorge Rimar         continue;
441652852c5SGeorge Rimar       }
442652852c5SGeorge Rimar 
443652852c5SGeorge Rimar       if (Sec->getFlags() & SHF_ALLOC) {
444424b4081SRui Ueyama         Dot = alignTo(Dot, Sec->getAlignment());
445c998a8c0SRui Ueyama         Sec->setVA(Dot);
446ceabe80eSEugene Leviant         assignOffsets(Sec);
447467c4d55SEugene Leviant         MinVA = std::min(MinVA, Dot);
448c998a8c0SRui Ueyama         Dot += Sec->getSize();
449652852c5SGeorge Rimar         continue;
450652852c5SGeorge Rimar       }
451652852c5SGeorge Rimar     }
452652852c5SGeorge Rimar   }
453467c4d55SEugene Leviant 
45464c32d6fSRafael Espindola   // ELF and Program headers need to be right before the first section in
455b91e7118SGeorge Rimar   // memory. Set their addresses accordingly.
456467c4d55SEugene Leviant   MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
457467c4d55SEugene Leviant                         Out<ELFT>::ProgramHeaders->getSize(),
458467c4d55SEugene Leviant                     Target->PageSize);
459467c4d55SEugene Leviant   Out<ELFT>::ElfHeader->setVA(MinVA);
460467c4d55SEugene Leviant   Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
461fb8978fcSDima Stepanov }
462652852c5SGeorge Rimar 
46307320e40SRui Ueyama template <class ELFT>
464a4b41dcaSRafael Espindola std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
465a4b41dcaSRafael Espindola   ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
466edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
467bbe38602SEugene Leviant 
468bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
469edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
470edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
471bbe38602SEugene Leviant 
472bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
473adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
474bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
475adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
476bbe38602SEugene Leviant 
477bbe38602SEugene Leviant     switch (Cmd.Type) {
478bbe38602SEugene Leviant     case PT_INTERP:
479fd03cfd2SRui Ueyama       if (Out<ELFT>::Interp)
480adca245fSRui Ueyama         Phdr.add(Out<ELFT>::Interp);
481bbe38602SEugene Leviant       break;
482bbe38602SEugene Leviant     case PT_DYNAMIC:
4831034c9e3SRui Ueyama       if (Out<ELFT>::DynSymTab) {
4840b113671SRafael Espindola         Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
485adca245fSRui Ueyama         Phdr.add(Out<ELFT>::Dynamic);
486bbe38602SEugene Leviant       }
487bbe38602SEugene Leviant       break;
488bbe38602SEugene Leviant     case PT_GNU_EH_FRAME:
489bbe38602SEugene Leviant       if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
4900b113671SRafael Espindola         Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
491adca245fSRui Ueyama         Phdr.add(Out<ELFT>::EhFrameHdr);
492bbe38602SEugene Leviant       }
493bbe38602SEugene Leviant       break;
494bbe38602SEugene Leviant     }
495bbe38602SEugene Leviant   }
496bbe38602SEugene Leviant 
497edebbdf1SRui Ueyama   PhdrEntry<ELFT> *Load = nullptr;
498edebbdf1SRui Ueyama   uintX_t Flags = PF_R;
499bbe38602SEugene Leviant   for (OutputSectionBase<ELFT> *Sec : Sections) {
500bbe38602SEugene Leviant     if (!(Sec->getFlags() & SHF_ALLOC))
501bbe38602SEugene Leviant       break;
502bbe38602SEugene Leviant 
503edebbdf1SRui Ueyama     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
504bbe38602SEugene Leviant     if (!PhdrIds.empty()) {
505bbe38602SEugene Leviant       // Assign headers specified by linker script
506bbe38602SEugene Leviant       for (size_t Id : PhdrIds) {
507edebbdf1SRui Ueyama         Ret[Id].add(Sec);
508865bf863SEugene Leviant         if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
5090b113671SRafael Espindola           Ret[Id].H.p_flags |= Sec->getPhdrFlags();
510bbe38602SEugene Leviant       }
511bbe38602SEugene Leviant     } else {
512bbe38602SEugene Leviant       // If we have no load segment or flags've changed then we want new load
513bbe38602SEugene Leviant       // segment.
5140b113671SRafael Espindola       uintX_t NewFlags = Sec->getPhdrFlags();
515bbe38602SEugene Leviant       if (Load == nullptr || Flags != NewFlags) {
516edebbdf1SRui Ueyama         Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
517bbe38602SEugene Leviant         Flags = NewFlags;
518bbe38602SEugene Leviant       }
51918f084ffSRui Ueyama       Load->add(Sec);
520bbe38602SEugene Leviant     }
521bbe38602SEugene Leviant   }
522edebbdf1SRui Ueyama   return Ret;
523bbe38602SEugene Leviant }
524bbe38602SEugene Leviant 
525bbe38602SEugene Leviant template <class ELFT>
52607320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
527f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
528f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
529f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
530f6c3ccefSGeorge Rimar         return Cmd->Filler;
531e2ee72b5SGeorge Rimar   return {};
532e2ee72b5SGeorge Rimar }
533e2ee72b5SGeorge Rimar 
534c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
535c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
536c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
537c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
538076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
539f510fa6bSRui Ueyama   int I = 0;
540f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
541076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
542076fe157SGeorge Rimar       if (Cmd->Name == Name)
543f510fa6bSRui Ueyama         return I;
544f510fa6bSRui Ueyama     ++I;
545f510fa6bSRui Ueyama   }
546f510fa6bSRui Ueyama   return INT_MAX;
54771b26e94SGeorge Rimar }
54871b26e94SGeorge Rimar 
54971b26e94SGeorge Rimar // A compartor to sort output sections. Returns -1 or 1 if
55071b26e94SGeorge Rimar // A or B are mentioned in linker script. Otherwise, returns 0.
55107320e40SRui Ueyama template <class ELFT>
55207320e40SRui Ueyama int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
553c3e2a4b0SRui Ueyama   int I = getSectionIndex(A);
554c3e2a4b0SRui Ueyama   int J = getSectionIndex(B);
555c3e2a4b0SRui Ueyama   if (I == INT_MAX && J == INT_MAX)
556717677afSRui Ueyama     return 0;
557717677afSRui Ueyama   return I < J ? -1 : 1;
558717677afSRui Ueyama }
559717677afSRui Ueyama 
560bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
561bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
562bbe38602SEugene Leviant }
563bbe38602SEugene Leviant 
5649e69450eSGeorge Rimar template <class ELFT>
5659e69450eSGeorge Rimar typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
5669e69450eSGeorge Rimar   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
5679e69450eSGeorge Rimar     if (Sec->getName() == Name)
5689e69450eSGeorge Rimar       return Sec->getSize();
5699e69450eSGeorge Rimar   error("undefined section " + Name);
5709e69450eSGeorge Rimar   return 0;
5719e69450eSGeorge Rimar }
5729e69450eSGeorge Rimar 
573e32a3598SGeorge Rimar template <class ELFT>
574e32a3598SGeorge Rimar typename ELFT::uint LinkerScript<ELFT>::getSizeOfHeaders() {
575e32a3598SGeorge Rimar   return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
576e32a3598SGeorge Rimar }
577e32a3598SGeorge Rimar 
578bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
579bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
580bbe38602SEugene Leviant // PHDRS {} script block.
581bbe38602SEugene Leviant template <class ELFT>
582edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
583076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
584076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
585edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
58631d842f5SGeorge Rimar       continue;
58731d842f5SGeorge Rimar 
58829c5a2a9SRui Ueyama     std::vector<size_t> Ret;
58929c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
59029c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
59129c5a2a9SRui Ueyama     return Ret;
592bbe38602SEugene Leviant   }
59331d842f5SGeorge Rimar   return {};
59431d842f5SGeorge Rimar }
595bbe38602SEugene Leviant 
59629c5a2a9SRui Ueyama template <class ELFT>
59729c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
59829c5a2a9SRui Ueyama   size_t I = 0;
59929c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
60029c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
60129c5a2a9SRui Ueyama       return I;
60229c5a2a9SRui Ueyama     ++I;
60329c5a2a9SRui Ueyama   }
60429c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
60529c5a2a9SRui Ueyama   return 0;
60629c5a2a9SRui Ueyama }
60729c5a2a9SRui Ueyama 
60807320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
609c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
610c3794e58SGeorge Rimar 
611f7c5fbb1SRui Ueyama public:
61207320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
613f23b2320SGeorge Rimar 
6144a46539cSRui Ueyama   void run();
615f7c5fbb1SRui Ueyama 
616f7c5fbb1SRui Ueyama private:
61752a1509eSRui Ueyama   void addFile(StringRef Path);
61852a1509eSRui Ueyama 
619f7c5fbb1SRui Ueyama   void readAsNeeded();
62090c5099eSDenis Protivensky   void readEntry();
62183f406cfSGeorge Rimar   void readExtern();
622f7c5fbb1SRui Ueyama   void readGroup();
62331aa1f83SRui Ueyama   void readInclude();
624c3794e58SGeorge Rimar   void readNothing() {}
625ee59282bSRui Ueyama   void readOutput();
6269159ce93SDavide Italiano   void readOutputArch();
627f7c5fbb1SRui Ueyama   void readOutputFormat();
628bbe38602SEugene Leviant   void readPhdrs();
62968a39a65SDavide Italiano   void readSearchDir();
6308e3b38abSDenis Protivensky   void readSections();
6318e3b38abSDenis Protivensky 
632113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
63310416564SRui Ueyama   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
634f71caa2bSRui Ueyama   std::vector<uint8_t> readOutputSectionFiller();
635bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
63610416564SRui Ueyama   InputSectionDescription *readInputSectionDescription();
63710416564SRui Ueyama   std::vector<StringRef> readInputFilePatterns();
63810416564SRui Ueyama   InputSectionDescription *readInputSectionRules();
639bbe38602SEugene Leviant   unsigned readPhdrType();
640742c3836SRui Ueyama   SortKind readSortKind();
64110416564SRui Ueyama   SymbolAssignment *readProvide(bool Hidden);
642ceabe80eSEugene Leviant   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
64310416564SRui Ueyama   Expr readAlign();
64403fc010eSGeorge Rimar   void readSort();
645eefa758eSGeorge Rimar   Expr readAssert();
646708019c4SRui Ueyama 
647708019c4SRui Ueyama   Expr readExpr();
648708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
649708019c4SRui Ueyama   Expr readPrimary();
650708019c4SRui Ueyama   Expr readTernary(Expr Cond);
651f7c5fbb1SRui Ueyama 
652c3794e58SGeorge Rimar   const static StringMap<Handler> Cmd;
65307320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
65407320e40SRui Ueyama   StringSaver Saver = {ScriptConfig->Alloc};
65516b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
656f7c5fbb1SRui Ueyama };
657f7c5fbb1SRui Ueyama 
658e0df00b9SRafael Espindola const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
659c3794e58SGeorge Rimar     {"ENTRY", &ScriptParser::readEntry},
660c3794e58SGeorge Rimar     {"EXTERN", &ScriptParser::readExtern},
661c3794e58SGeorge Rimar     {"GROUP", &ScriptParser::readGroup},
662c3794e58SGeorge Rimar     {"INCLUDE", &ScriptParser::readInclude},
663c3794e58SGeorge Rimar     {"INPUT", &ScriptParser::readGroup},
664c3794e58SGeorge Rimar     {"OUTPUT", &ScriptParser::readOutput},
665c3794e58SGeorge Rimar     {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
666c3794e58SGeorge Rimar     {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
667bbe38602SEugene Leviant     {"PHDRS", &ScriptParser::readPhdrs},
668c3794e58SGeorge Rimar     {"SEARCH_DIR", &ScriptParser::readSearchDir},
669c3794e58SGeorge Rimar     {"SECTIONS", &ScriptParser::readSections},
670c3794e58SGeorge Rimar     {";", &ScriptParser::readNothing}};
671c3794e58SGeorge Rimar 
672717677afSRui Ueyama void ScriptParser::run() {
673f7c5fbb1SRui Ueyama   while (!atEOF()) {
674f7c5fbb1SRui Ueyama     StringRef Tok = next();
675c3794e58SGeorge Rimar     if (Handler Fn = Cmd.lookup(Tok))
676c3794e58SGeorge Rimar       (this->*Fn)();
677c3794e58SGeorge Rimar     else
6785761042dSGeorge Rimar       setError("unknown directive: " + Tok);
679f7c5fbb1SRui Ueyama   }
680f7c5fbb1SRui Ueyama }
681f7c5fbb1SRui Ueyama 
682717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
68316b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
68416b0cc9eSSimon Atanasyan     SmallString<128> Path;
68516b0cc9eSSimon Atanasyan     (Config->Sysroot + S).toStringRef(Path);
68616b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
68716b0cc9eSSimon Atanasyan       Driver->addFile(Saver.save(Path.str()));
68816b0cc9eSSimon Atanasyan       return;
68916b0cc9eSSimon Atanasyan     }
69016b0cc9eSSimon Atanasyan   }
69116b0cc9eSSimon Atanasyan 
692f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
69352a1509eSRui Ueyama     Driver->addFile(S);
69452a1509eSRui Ueyama   } else if (S.startswith("=")) {
69552a1509eSRui Ueyama     if (Config->Sysroot.empty())
69652a1509eSRui Ueyama       Driver->addFile(S.substr(1));
69752a1509eSRui Ueyama     else
69852a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
69952a1509eSRui Ueyama   } else if (S.startswith("-l")) {
70021eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
701a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
702a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
70352a1509eSRui Ueyama   } else {
70452a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
70552a1509eSRui Ueyama     if (Path.empty())
706777f9630SGeorge Rimar       setError("unable to find " + S);
707025d59b1SRui Ueyama     else
70852a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
70952a1509eSRui Ueyama   }
71052a1509eSRui Ueyama }
71152a1509eSRui Ueyama 
712717677afSRui Ueyama void ScriptParser::readAsNeeded() {
713f7c5fbb1SRui Ueyama   expect("(");
71435da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
71535da9b6eSRui Ueyama   Config->AsNeeded = true;
716a2acc931SRui Ueyama   while (!Error && !skip(")"))
717a2acc931SRui Ueyama     addFile(next());
71835da9b6eSRui Ueyama   Config->AsNeeded = Orig;
719f7c5fbb1SRui Ueyama }
720f7c5fbb1SRui Ueyama 
721717677afSRui Ueyama void ScriptParser::readEntry() {
72290c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
72390c5099eSDenis Protivensky   expect("(");
72490c5099eSDenis Protivensky   StringRef Tok = next();
72590c5099eSDenis Protivensky   if (Config->Entry.empty())
72690c5099eSDenis Protivensky     Config->Entry = Tok;
72790c5099eSDenis Protivensky   expect(")");
72890c5099eSDenis Protivensky }
72990c5099eSDenis Protivensky 
730717677afSRui Ueyama void ScriptParser::readExtern() {
73183f406cfSGeorge Rimar   expect("(");
732a2acc931SRui Ueyama   while (!Error && !skip(")"))
733a2acc931SRui Ueyama     Config->Undefined.push_back(next());
73483f406cfSGeorge Rimar }
73583f406cfSGeorge Rimar 
736717677afSRui Ueyama void ScriptParser::readGroup() {
737f7c5fbb1SRui Ueyama   expect("(");
738a2acc931SRui Ueyama   while (!Error && !skip(")")) {
739f7c5fbb1SRui Ueyama     StringRef Tok = next();
740a2acc931SRui Ueyama     if (Tok == "AS_NEEDED")
741f7c5fbb1SRui Ueyama       readAsNeeded();
742a2acc931SRui Ueyama     else
74352a1509eSRui Ueyama       addFile(Tok);
744f7c5fbb1SRui Ueyama   }
745f7c5fbb1SRui Ueyama }
746f7c5fbb1SRui Ueyama 
747717677afSRui Ueyama void ScriptParser::readInclude() {
74831aa1f83SRui Ueyama   StringRef Tok = next();
74931aa1f83SRui Ueyama   auto MBOrErr = MemoryBuffer::getFile(Tok);
750025d59b1SRui Ueyama   if (!MBOrErr) {
7515761042dSGeorge Rimar     setError("cannot open " + Tok);
752025d59b1SRui Ueyama     return;
753025d59b1SRui Ueyama   }
75431aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
755a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
756a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
75731aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
75831aa1f83SRui Ueyama }
75931aa1f83SRui Ueyama 
760717677afSRui Ueyama void ScriptParser::readOutput() {
761ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
762ee59282bSRui Ueyama   expect("(");
763ee59282bSRui Ueyama   StringRef Tok = next();
764ee59282bSRui Ueyama   if (Config->OutputFile.empty())
765ee59282bSRui Ueyama     Config->OutputFile = Tok;
766ee59282bSRui Ueyama   expect(")");
767ee59282bSRui Ueyama }
768ee59282bSRui Ueyama 
769717677afSRui Ueyama void ScriptParser::readOutputArch() {
7709159ce93SDavide Italiano   // Error checking only for now.
7719159ce93SDavide Italiano   expect("(");
7729159ce93SDavide Italiano   next();
7739159ce93SDavide Italiano   expect(")");
7749159ce93SDavide Italiano }
7759159ce93SDavide Italiano 
776717677afSRui Ueyama void ScriptParser::readOutputFormat() {
777f7c5fbb1SRui Ueyama   // Error checking only for now.
778f7c5fbb1SRui Ueyama   expect("(");
779f7c5fbb1SRui Ueyama   next();
7806836c618SDavide Italiano   StringRef Tok = next();
7816836c618SDavide Italiano   if (Tok == ")")
7826836c618SDavide Italiano    return;
783025d59b1SRui Ueyama   if (Tok != ",") {
7845761042dSGeorge Rimar     setError("unexpected token: " + Tok);
785025d59b1SRui Ueyama     return;
786025d59b1SRui Ueyama   }
7876836c618SDavide Italiano   next();
7886836c618SDavide Italiano   expect(",");
7896836c618SDavide Italiano   next();
790f7c5fbb1SRui Ueyama   expect(")");
791f7c5fbb1SRui Ueyama }
792f7c5fbb1SRui Ueyama 
793bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
794bbe38602SEugene Leviant   expect("{");
795bbe38602SEugene Leviant   while (!Error && !skip("}")) {
796bbe38602SEugene Leviant     StringRef Tok = next();
797865bf863SEugene Leviant     Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
798bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
799bbe38602SEugene Leviant 
800bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
801bbe38602SEugene Leviant     do {
802bbe38602SEugene Leviant       Tok = next();
803bbe38602SEugene Leviant       if (Tok == ";")
804bbe38602SEugene Leviant         break;
805bbe38602SEugene Leviant       if (Tok == "FILEHDR")
806bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
807bbe38602SEugene Leviant       else if (Tok == "PHDRS")
808bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
809865bf863SEugene Leviant       else if (Tok == "FLAGS") {
810865bf863SEugene Leviant         expect("(");
811eb685cd7SRafael Espindola         // Passing 0 for the value of dot is a bit of a hack. It means that
812eb685cd7SRafael Espindola         // we accept expressions like ".|1".
813eb685cd7SRafael Espindola         PhdrCmd.Flags = readExpr()(0);
814865bf863SEugene Leviant         expect(")");
815865bf863SEugene Leviant       } else
816bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
817bbe38602SEugene Leviant     } while (!Error);
818bbe38602SEugene Leviant   }
819bbe38602SEugene Leviant }
820bbe38602SEugene Leviant 
821717677afSRui Ueyama void ScriptParser::readSearchDir() {
82268a39a65SDavide Italiano   expect("(");
82306501920SRafael Espindola   Config->SearchPaths.push_back(next());
82468a39a65SDavide Italiano   expect(")");
82568a39a65SDavide Italiano }
82668a39a65SDavide Italiano 
827717677afSRui Ueyama void ScriptParser::readSections() {
8283de0a330SRui Ueyama   Opt.HasContents = true;
8298e3b38abSDenis Protivensky   expect("{");
830652852c5SGeorge Rimar   while (!Error && !skip("}")) {
831113cdec9SRui Ueyama     StringRef Tok = next();
832ceabe80eSEugene Leviant     BaseCommand *Cmd = readProvideOrAssignment(Tok);
833ceabe80eSEugene Leviant     if (!Cmd) {
834ceabe80eSEugene Leviant       if (Tok == "ASSERT")
835eefa758eSGeorge Rimar         Cmd = new AssertCommand(readAssert());
836ceabe80eSEugene Leviant       else
83710416564SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
8388e3b38abSDenis Protivensky     }
83910416564SRui Ueyama     Opt.Commands.emplace_back(Cmd);
840652852c5SGeorge Rimar   }
841708019c4SRui Ueyama }
8428e3b38abSDenis Protivensky 
843708019c4SRui Ueyama static int precedence(StringRef Op) {
844708019c4SRui Ueyama   return StringSwitch<int>(Op)
845708019c4SRui Ueyama       .Case("*", 4)
846708019c4SRui Ueyama       .Case("/", 4)
847708019c4SRui Ueyama       .Case("+", 3)
848708019c4SRui Ueyama       .Case("-", 3)
849708019c4SRui Ueyama       .Case("<", 2)
850708019c4SRui Ueyama       .Case(">", 2)
851708019c4SRui Ueyama       .Case(">=", 2)
852708019c4SRui Ueyama       .Case("<=", 2)
853708019c4SRui Ueyama       .Case("==", 2)
854708019c4SRui Ueyama       .Case("!=", 2)
855708019c4SRui Ueyama       .Case("&", 1)
856708019c4SRui Ueyama       .Default(-1);
857708019c4SRui Ueyama }
858708019c4SRui Ueyama 
85910416564SRui Ueyama std::vector<StringRef> ScriptParser::readInputFilePatterns() {
86010416564SRui Ueyama   std::vector<StringRef> V;
86110416564SRui Ueyama   while (!Error && !skip(")"))
86210416564SRui Ueyama     V.push_back(next());
86310416564SRui Ueyama   return V;
8640702c4e8SGeorge Rimar }
8650702c4e8SGeorge Rimar 
866742c3836SRui Ueyama SortKind ScriptParser::readSortKind() {
867742c3836SRui Ueyama   if (skip("SORT") || skip("SORT_BY_NAME"))
868742c3836SRui Ueyama     return SortByName;
869742c3836SRui Ueyama   if (skip("SORT_BY_ALIGNMENT"))
870742c3836SRui Ueyama     return SortByAlignment;
871742c3836SRui Ueyama   return SortNone;
872742c3836SRui Ueyama }
873742c3836SRui Ueyama 
87410416564SRui Ueyama InputSectionDescription *ScriptParser::readInputSectionRules() {
87510416564SRui Ueyama   auto *Cmd = new InputSectionDescription;
87610416564SRui Ueyama   Cmd->FilePattern = next();
8770ed42b0cSDavide Italiano   expect("(");
878e7282797SDavide Italiano 
879742c3836SRui Ueyama   // Read EXCLUDE_FILE().
880e7282797SDavide Italiano   if (skip("EXCLUDE_FILE")) {
881e7282797SDavide Italiano     expect("(");
882e7282797SDavide Italiano     while (!Error && !skip(")"))
88310416564SRui Ueyama       Cmd->ExcludedFiles.push_back(next());
884e7282797SDavide Italiano   }
885e7282797SDavide Italiano 
886742c3836SRui Ueyama   // Read SORT().
887742c3836SRui Ueyama   if (SortKind K1 = readSortKind()) {
888742c3836SRui Ueyama     Cmd->SortOuter = K1;
8890702c4e8SGeorge Rimar     expect("(");
890742c3836SRui Ueyama     if (SortKind K2 = readSortKind()) {
891742c3836SRui Ueyama       Cmd->SortInner = K2;
892350ece4eSGeorge Rimar       expect("(");
89310416564SRui Ueyama       Cmd->SectionPatterns = readInputFilePatterns();
8940702c4e8SGeorge Rimar       expect(")");
895350ece4eSGeorge Rimar     } else {
89610416564SRui Ueyama       Cmd->SectionPatterns = readInputFilePatterns();
897350ece4eSGeorge Rimar     }
898350ece4eSGeorge Rimar     expect(")");
89910416564SRui Ueyama     return Cmd;
9000659800eSGeorge Rimar   }
9010702c4e8SGeorge Rimar 
90210416564SRui Ueyama   Cmd->SectionPatterns = readInputFilePatterns();
90310416564SRui Ueyama   return Cmd;
9040659800eSGeorge Rimar }
9050659800eSGeorge Rimar 
90610416564SRui Ueyama InputSectionDescription *ScriptParser::readInputSectionDescription() {
9070659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
9080659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
9090659800eSGeorge Rimar   if (skip("KEEP")) {
910e7282797SDavide Italiano     expect("(");
91110416564SRui Ueyama     InputSectionDescription *Cmd = readInputSectionRules();
9120ed42b0cSDavide Italiano     expect(")");
91310416564SRui Ueyama     Opt.KeptSections.insert(Opt.KeptSections.end(),
91410416564SRui Ueyama                             Cmd->SectionPatterns.begin(),
91510416564SRui Ueyama                             Cmd->SectionPatterns.end());
91610416564SRui Ueyama     return Cmd;
91710416564SRui Ueyama   }
91810416564SRui Ueyama   return readInputSectionRules();
9190659800eSGeorge Rimar }
9200659800eSGeorge Rimar 
92110416564SRui Ueyama Expr ScriptParser::readAlign() {
922630c6179SGeorge Rimar   expect("(");
92310416564SRui Ueyama   Expr E = readExpr();
924630c6179SGeorge Rimar   expect(")");
92510416564SRui Ueyama   return E;
926630c6179SGeorge Rimar }
927630c6179SGeorge Rimar 
92803fc010eSGeorge Rimar void ScriptParser::readSort() {
92903fc010eSGeorge Rimar   expect("(");
93003fc010eSGeorge Rimar   expect("CONSTRUCTORS");
93103fc010eSGeorge Rimar   expect(")");
93203fc010eSGeorge Rimar }
93303fc010eSGeorge Rimar 
934eefa758eSGeorge Rimar Expr ScriptParser::readAssert() {
935eefa758eSGeorge Rimar   expect("(");
936eefa758eSGeorge Rimar   Expr E = readExpr();
937eefa758eSGeorge Rimar   expect(",");
938eefa758eSGeorge Rimar   StringRef Msg = next();
939eefa758eSGeorge Rimar   expect(")");
940eefa758eSGeorge Rimar   return [=](uint64_t Dot) {
941eefa758eSGeorge Rimar     uint64_t V = E(Dot);
942eefa758eSGeorge Rimar     if (!V)
943eefa758eSGeorge Rimar       error(Msg);
944eefa758eSGeorge Rimar     return V;
945eefa758eSGeorge Rimar   };
946eefa758eSGeorge Rimar }
947eefa758eSGeorge Rimar 
94810416564SRui Ueyama OutputSectionCommand *
94910416564SRui Ueyama ScriptParser::readOutputSectionDescription(StringRef OutSec) {
950076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
95158e5c4dcSGeorge Rimar 
95258e5c4dcSGeorge Rimar   // Read an address expression.
95358e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
95458e5c4dcSGeorge Rimar   if (peek() != ":")
95558e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
95658e5c4dcSGeorge Rimar 
9578e3b38abSDenis Protivensky   expect(":");
958246f681eSDavide Italiano 
959630c6179SGeorge Rimar   if (skip("ALIGN"))
96010416564SRui Ueyama     Cmd->AlignExpr = readAlign();
961630c6179SGeorge Rimar 
962246f681eSDavide Italiano   // Parse constraints.
963246f681eSDavide Italiano   if (skip("ONLY_IF_RO"))
964efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
965246f681eSDavide Italiano   if (skip("ONLY_IF_RW"))
966efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
9678e3b38abSDenis Protivensky   expect("{");
9688ec77e64SRui Ueyama 
969025d59b1SRui Ueyama   while (!Error && !skip("}")) {
970f586ff7eSGeorge Rimar     if (peek().startswith("*") || peek() == "KEEP") {
97110416564SRui Ueyama       Cmd->Commands.emplace_back(readInputSectionDescription());
9720659800eSGeorge Rimar       continue;
9730659800eSGeorge Rimar     }
974ceabe80eSEugene Leviant 
975ceabe80eSEugene Leviant     StringRef Tok = next();
976ceabe80eSEugene Leviant     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
977ceabe80eSEugene Leviant       Cmd->Commands.emplace_back(Assignment);
978ceabe80eSEugene Leviant     else if (Tok == "SORT")
97903fc010eSGeorge Rimar       readSort();
980ceabe80eSEugene Leviant     else
981ceabe80eSEugene Leviant       setError("unknown command " + Tok);
9828e3b38abSDenis Protivensky   }
983076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
984f71caa2bSRui Ueyama   Cmd->Filler = readOutputSectionFiller();
98510416564SRui Ueyama   return Cmd;
986f71caa2bSRui Ueyama }
9878ec77e64SRui Ueyama 
988f71caa2bSRui Ueyama std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
989e2ee72b5SGeorge Rimar   StringRef Tok = peek();
990f71caa2bSRui Ueyama   if (!Tok.startswith("="))
991f71caa2bSRui Ueyama     return {};
9925ac0d7c5SDavide Italiano   next();
993965827d6SRui Ueyama 
994965827d6SRui Ueyama   // Read a hexstring of arbitrary length.
9955ac0d7c5SDavide Italiano   if (Tok.startswith("=0x"))
9965ac0d7c5SDavide Italiano     return parseHex(Tok.substr(3));
9975ac0d7c5SDavide Italiano 
998965827d6SRui Ueyama   // Read a decimal or octal value as a big-endian 32 bit value.
999965827d6SRui Ueyama   // Why do this? I don't know, but that's what gold does.
1000965827d6SRui Ueyama   uint32_t V;
1001965827d6SRui Ueyama   if (Tok.substr(1).getAsInteger(0, V)) {
1002965827d6SRui Ueyama     setError("invalid filler expression: " + Tok);
1003f71caa2bSRui Ueyama     return {};
1004e2ee72b5SGeorge Rimar   }
1005965827d6SRui Ueyama   return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
10068e3b38abSDenis Protivensky }
10078e3b38abSDenis Protivensky 
100810416564SRui Ueyama SymbolAssignment *ScriptParser::readProvide(bool Hidden) {
1009a31c91b1SEugene Leviant   expect("(");
1010174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
1011174e0a16SRui Ueyama   Cmd->Provide = true;
1012174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
1013a31c91b1SEugene Leviant   expect(")");
1014a31c91b1SEugene Leviant   expect(";");
101510416564SRui Ueyama   return Cmd;
1016eda81a1bSEugene Leviant }
1017eda81a1bSEugene Leviant 
1018ceabe80eSEugene Leviant SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1019ceabe80eSEugene Leviant   SymbolAssignment *Cmd = nullptr;
1020ceabe80eSEugene Leviant   if (peek() == "=" || peek() == "+=") {
1021ceabe80eSEugene Leviant     Cmd = readAssignment(Tok);
1022ceabe80eSEugene Leviant     expect(";");
1023ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE") {
1024ceabe80eSEugene Leviant     Cmd = readProvide(false);
1025ceabe80eSEugene Leviant   } else if (Tok == "PROVIDE_HIDDEN") {
1026ceabe80eSEugene Leviant     Cmd = readProvide(true);
1027ceabe80eSEugene Leviant   }
1028ceabe80eSEugene Leviant   return Cmd;
1029ceabe80eSEugene Leviant }
1030ceabe80eSEugene Leviant 
103130835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
103230835ea4SGeorge Rimar   if (S == ".")
103330835ea4SGeorge Rimar     return Dot;
1034a31c91b1SEugene Leviant 
1035a9c5a528SGeorge Rimar   switch (Config->EKind) {
1036a9c5a528SGeorge Rimar   case ELF32LEKind:
1037a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
1038a9c5a528SGeorge Rimar       return B->getVA<ELF32LE>();
1039a9c5a528SGeorge Rimar     break;
1040a9c5a528SGeorge Rimar   case ELF32BEKind:
1041a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
1042a9c5a528SGeorge Rimar       return B->getVA<ELF32BE>();
1043a9c5a528SGeorge Rimar     break;
1044a9c5a528SGeorge Rimar   case ELF64LEKind:
1045a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
1046a9c5a528SGeorge Rimar       return B->getVA<ELF64LE>();
1047a9c5a528SGeorge Rimar     break;
1048a9c5a528SGeorge Rimar   case ELF64BEKind:
1049a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
1050a9c5a528SGeorge Rimar       return B->getVA<ELF64BE>();
1051a9c5a528SGeorge Rimar     break;
10526930a6dcSGeorge Rimar   default:
1053b567b628SGeorge Rimar     llvm_unreachable("unsupported target");
1054a9c5a528SGeorge Rimar   }
1055a9c5a528SGeorge Rimar   error("symbol not found: " + S);
1056a9c5a528SGeorge Rimar   return 0;
1057a9c5a528SGeorge Rimar }
1058a9c5a528SGeorge Rimar 
10599e69450eSGeorge Rimar static uint64_t getSectionSize(StringRef Name) {
10609e69450eSGeorge Rimar   switch (Config->EKind) {
10619e69450eSGeorge Rimar   case ELF32LEKind:
10629e69450eSGeorge Rimar     return Script<ELF32LE>::X->getOutputSectionSize(Name);
10639e69450eSGeorge Rimar   case ELF32BEKind:
10649e69450eSGeorge Rimar     return Script<ELF32BE>::X->getOutputSectionSize(Name);
10659e69450eSGeorge Rimar   case ELF64LEKind:
10669e69450eSGeorge Rimar     return Script<ELF64LE>::X->getOutputSectionSize(Name);
10679e69450eSGeorge Rimar   case ELF64BEKind:
10689e69450eSGeorge Rimar     return Script<ELF64BE>::X->getOutputSectionSize(Name);
10699e69450eSGeorge Rimar   default:
10709e69450eSGeorge Rimar     llvm_unreachable("unsupported target");
10719e69450eSGeorge Rimar   }
10729e69450eSGeorge Rimar }
10739e69450eSGeorge Rimar 
1074e32a3598SGeorge Rimar static uint64_t getSizeOfHeaders() {
1075e32a3598SGeorge Rimar   switch (Config->EKind) {
1076e32a3598SGeorge Rimar   case ELF32LEKind:
1077e32a3598SGeorge Rimar     return Script<ELF32LE>::X->getSizeOfHeaders();
1078e32a3598SGeorge Rimar   case ELF32BEKind:
1079e32a3598SGeorge Rimar     return Script<ELF32BE>::X->getSizeOfHeaders();
1080e32a3598SGeorge Rimar   case ELF64LEKind:
1081e32a3598SGeorge Rimar     return Script<ELF64LE>::X->getSizeOfHeaders();
1082e32a3598SGeorge Rimar   case ELF64BEKind:
1083e32a3598SGeorge Rimar     return Script<ELF64BE>::X->getSizeOfHeaders();
1084e32a3598SGeorge Rimar   default:
1085e32a3598SGeorge Rimar     llvm_unreachable("unsupported target");
1086e32a3598SGeorge Rimar   }
1087e32a3598SGeorge Rimar }
1088e32a3598SGeorge Rimar 
108930835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
109030835ea4SGeorge Rimar   StringRef Op = next();
109130835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
109230835ea4SGeorge Rimar   Expr E = readExpr();
109330835ea4SGeorge Rimar   if (Op == "+=")
109430835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
109510416564SRui Ueyama   return new SymbolAssignment(Name, E);
109630835ea4SGeorge Rimar }
109730835ea4SGeorge Rimar 
109830835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
109930835ea4SGeorge Rimar // script expression.
110030835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
110130835ea4SGeorge Rimar 
110236c1cd23SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
110336c1cd23SRui Ueyama   if (Op == "*")
110436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
110536c1cd23SRui Ueyama   if (Op == "/") {
110636c1cd23SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
110736c1cd23SRui Ueyama       uint64_t RHS = R(Dot);
110836c1cd23SRui Ueyama       if (RHS == 0) {
110936c1cd23SRui Ueyama         error("division by zero");
111036c1cd23SRui Ueyama         return 0;
111136c1cd23SRui Ueyama       }
111236c1cd23SRui Ueyama       return L(Dot) / RHS;
111336c1cd23SRui Ueyama     };
111436c1cd23SRui Ueyama   }
111536c1cd23SRui Ueyama   if (Op == "+")
111636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
111736c1cd23SRui Ueyama   if (Op == "-")
111836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
111936c1cd23SRui Ueyama   if (Op == "<")
112036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
112136c1cd23SRui Ueyama   if (Op == ">")
112236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
112336c1cd23SRui Ueyama   if (Op == ">=")
112436c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
112536c1cd23SRui Ueyama   if (Op == "<=")
112636c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
112736c1cd23SRui Ueyama   if (Op == "==")
112836c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
112936c1cd23SRui Ueyama   if (Op == "!=")
113036c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
113136c1cd23SRui Ueyama   if (Op == "&")
113236c1cd23SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
113336c1cd23SRui Ueyama   llvm_unreachable("invalid operator");
113436c1cd23SRui Ueyama }
113536c1cd23SRui Ueyama 
1136708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
1137708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
1138708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1139708019c4SRui Ueyama   while (!atEOF() && !Error) {
1140708019c4SRui Ueyama     // Read an operator and an expression.
1141708019c4SRui Ueyama     StringRef Op1 = peek();
1142708019c4SRui Ueyama     if (Op1 == "?")
1143708019c4SRui Ueyama       return readTernary(Lhs);
1144708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
1145a31c91b1SEugene Leviant       break;
1146a31c91b1SEugene Leviant     next();
1147708019c4SRui Ueyama     Expr Rhs = readPrimary();
1148708019c4SRui Ueyama 
1149708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
1150708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
1151708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
1152708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
1153708019c4SRui Ueyama     while (!atEOF()) {
1154708019c4SRui Ueyama       StringRef Op2 = peek();
1155708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
1156eda81a1bSEugene Leviant         break;
1157708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
1158eda81a1bSEugene Leviant     }
1159708019c4SRui Ueyama 
1160708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
1161708019c4SRui Ueyama   }
1162708019c4SRui Ueyama   return Lhs;
1163708019c4SRui Ueyama }
1164708019c4SRui Ueyama 
1165708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
1166708019c4SRui Ueyama   if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
1167708019c4SRui Ueyama     return Target->PageSize;
1168708019c4SRui Ueyama   error("unknown constant: " + S);
1169708019c4SRui Ueyama   return 0;
1170708019c4SRui Ueyama }
1171708019c4SRui Ueyama 
1172708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
1173708019c4SRui Ueyama   StringRef Tok = next();
1174708019c4SRui Ueyama 
1175708019c4SRui Ueyama   if (Tok == "(") {
1176708019c4SRui Ueyama     Expr E = readExpr();
1177708019c4SRui Ueyama     expect(")");
1178708019c4SRui Ueyama     return E;
1179708019c4SRui Ueyama   }
1180708019c4SRui Ueyama 
1181708019c4SRui Ueyama   // Built-in functions are parsed here.
1182708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1183eefa758eSGeorge Rimar   if (Tok == "ASSERT")
1184eefa758eSGeorge Rimar     return readAssert();
1185708019c4SRui Ueyama   if (Tok == "ALIGN") {
1186708019c4SRui Ueyama     expect("(");
1187708019c4SRui Ueyama     Expr E = readExpr();
1188708019c4SRui Ueyama     expect(")");
1189708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1190708019c4SRui Ueyama   }
1191708019c4SRui Ueyama   if (Tok == "CONSTANT") {
1192708019c4SRui Ueyama     expect("(");
1193708019c4SRui Ueyama     StringRef Tok = next();
1194708019c4SRui Ueyama     expect(")");
1195708019c4SRui Ueyama     return [=](uint64_t Dot) { return getConstant(Tok); };
1196708019c4SRui Ueyama   }
119754c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
119854c145ceSRafael Espindola     expect("(");
119954c145ceSRafael Espindola     next();
120054c145ceSRafael Espindola     expect(",");
120154c145ceSRafael Espindola     uint64_t Val;
120254c145ceSRafael Espindola     next().getAsInteger(0, Val);
120354c145ceSRafael Espindola     expect(")");
120454c145ceSRafael Espindola     return [=](uint64_t Dot) { return Val; };
120554c145ceSRafael Espindola   }
1206708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
1207708019c4SRui Ueyama     expect("(");
1208708019c4SRui Ueyama     Expr E = readExpr();
1209708019c4SRui Ueyama     expect(",");
1210708019c4SRui Ueyama     readExpr();
1211708019c4SRui Ueyama     expect(")");
1212f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1213708019c4SRui Ueyama   }
1214708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
1215708019c4SRui Ueyama     expect("(");
1216708019c4SRui Ueyama     expect(".");
1217708019c4SRui Ueyama     expect(")");
1218708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
1219708019c4SRui Ueyama   }
1220276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
1221276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1222276b4e64SGeorge Rimar   // the next page boundary for simplicity.
1223276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
1224276b4e64SGeorge Rimar     expect("(");
1225276b4e64SGeorge Rimar     next();
1226276b4e64SGeorge Rimar     expect(",");
1227276b4e64SGeorge Rimar     readExpr();
1228276b4e64SGeorge Rimar     expect(")");
1229276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1230276b4e64SGeorge Rimar   }
12319e69450eSGeorge Rimar   if (Tok == "SIZEOF") {
12329e69450eSGeorge Rimar     expect("(");
12339e69450eSGeorge Rimar     StringRef Name = next();
12349e69450eSGeorge Rimar     expect(")");
12359e69450eSGeorge Rimar     return [=](uint64_t Dot) { return getSectionSize(Name); };
12369e69450eSGeorge Rimar   }
1237e32a3598SGeorge Rimar   if (Tok == "SIZEOF_HEADERS")
1238e32a3598SGeorge Rimar     return [=](uint64_t Dot) { return getSizeOfHeaders(); };
1239708019c4SRui Ueyama 
1240a9c5a528SGeorge Rimar   // Parse a symbol name or a number literal.
1241708019c4SRui Ueyama   uint64_t V = 0;
1242a9c5a528SGeorge Rimar   if (Tok.getAsInteger(0, V)) {
124330835ea4SGeorge Rimar     if (Tok != "." && !isValidCIdentifier(Tok))
1244708019c4SRui Ueyama       setError("malformed number: " + Tok);
124530835ea4SGeorge Rimar     return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
1246a9c5a528SGeorge Rimar   }
1247708019c4SRui Ueyama   return [=](uint64_t Dot) { return V; };
1248708019c4SRui Ueyama }
1249708019c4SRui Ueyama 
1250708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
1251708019c4SRui Ueyama   next();
1252708019c4SRui Ueyama   Expr L = readExpr();
1253708019c4SRui Ueyama   expect(":");
1254708019c4SRui Ueyama   Expr R = readExpr();
1255708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1256708019c4SRui Ueyama }
1257708019c4SRui Ueyama 
1258bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1259bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
1260bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
1261bbe38602SEugene Leviant     StringRef Tok = next();
1262bbe38602SEugene Leviant     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1263bbe38602SEugene Leviant     if (Tok.empty()) {
1264bbe38602SEugene Leviant       setError("section header name is empty");
1265bbe38602SEugene Leviant       break;
1266bbe38602SEugene Leviant     }
1267bbe38602SEugene Leviant     Phdrs.push_back(Tok);
1268bbe38602SEugene Leviant   }
1269bbe38602SEugene Leviant   return Phdrs;
1270bbe38602SEugene Leviant }
1271bbe38602SEugene Leviant 
1272bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
1273bbe38602SEugene Leviant   StringRef Tok = next();
1274b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
1275b0f6c590SRui Ueyama       .Case("PT_NULL", PT_NULL)
1276b0f6c590SRui Ueyama       .Case("PT_LOAD", PT_LOAD)
1277b0f6c590SRui Ueyama       .Case("PT_DYNAMIC", PT_DYNAMIC)
1278b0f6c590SRui Ueyama       .Case("PT_INTERP", PT_INTERP)
1279b0f6c590SRui Ueyama       .Case("PT_NOTE", PT_NOTE)
1280b0f6c590SRui Ueyama       .Case("PT_SHLIB", PT_SHLIB)
1281b0f6c590SRui Ueyama       .Case("PT_PHDR", PT_PHDR)
1282b0f6c590SRui Ueyama       .Case("PT_TLS", PT_TLS)
1283b0f6c590SRui Ueyama       .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1284b0f6c590SRui Ueyama       .Case("PT_GNU_STACK", PT_GNU_STACK)
1285b0f6c590SRui Ueyama       .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1286b0f6c590SRui Ueyama       .Default(-1);
1287bbe38602SEugene Leviant 
1288b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1289b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1290b0f6c590SRui Ueyama     return PT_NULL;
1291b0f6c590SRui Ueyama   }
1292b0f6c590SRui Ueyama   return Ret;
1293bbe38602SEugene Leviant }
1294bbe38602SEugene Leviant 
129516b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
129616b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
129716b0cc9eSSimon Atanasyan     return false;
129816b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
129916b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
130016b0cc9eSSimon Atanasyan       return true;
130116b0cc9eSSimon Atanasyan   return false;
130216b0cc9eSSimon Atanasyan }
130316b0cc9eSSimon Atanasyan 
130407320e40SRui Ueyama // Entry point.
130507320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
130616b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
130707320e40SRui Ueyama   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
1308f7c5fbb1SRui Ueyama }
13091ebc8ed7SRui Ueyama 
131007320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
131107320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
131207320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
131307320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1314