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 
46076fe157SGeorge Rimar bool SymbolAssignment::classof(const BaseCommand *C) {
47076fe157SGeorge Rimar   return C->Kind == AssignmentKind;
48076fe157SGeorge Rimar }
49076fe157SGeorge Rimar 
50076fe157SGeorge Rimar bool OutputSectionCommand::classof(const BaseCommand *C) {
51076fe157SGeorge Rimar   return C->Kind == OutputSectionKind;
52076fe157SGeorge Rimar }
53076fe157SGeorge Rimar 
54eea3114fSGeorge Rimar bool InputSectionDescription::classof(const BaseCommand *C) {
55eea3114fSGeorge Rimar   return C->Kind == InputSectionKind;
56eea3114fSGeorge Rimar }
57eea3114fSGeorge Rimar 
5836a153cdSRui Ueyama template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
59eea3114fSGeorge Rimar   return !S || !S->Live;
60717677afSRui Ueyama }
61717677afSRui Ueyama 
6207320e40SRui Ueyama template <class ELFT>
6307320e40SRui Ueyama bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
648ec77e64SRui Ueyama   for (StringRef Pat : Opt.KeptSections)
65722830a5SRui Ueyama     if (globMatch(Pat, S->getSectionName()))
668ec77e64SRui Ueyama       return true;
678ec77e64SRui Ueyama   return false;
68481c2ce6SGeorge Rimar }
69481c2ce6SGeorge Rimar 
7063dc6509SRui Ueyama static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
7163dc6509SRui Ueyama   for (StringRef Pat : Patterns)
7263dc6509SRui Ueyama     if (globMatch(Pat, S))
73eea3114fSGeorge Rimar       return true;
74eea3114fSGeorge Rimar   return false;
75eea3114fSGeorge Rimar }
76eea3114fSGeorge Rimar 
77eaee2af5SGeorge Rimar // Create a vector of (<output section name>, <input section description>).
786b274810SRui Ueyama template <class ELFT>
79e7282797SDavide Italiano std::vector<std::pair<StringRef, const InputSectionDescription *>>
806b274810SRui Ueyama LinkerScript<ELFT>::getSectionMap() {
81e7282797SDavide Italiano   std::vector<std::pair<StringRef, const InputSectionDescription *>> Ret;
826b274810SRui Ueyama 
836b274810SRui Ueyama   for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands)
846b274810SRui Ueyama     if (auto *Cmd1 = dyn_cast<OutputSectionCommand>(Base1.get()))
856b274810SRui Ueyama       for (const std::unique_ptr<BaseCommand> &Base2 : Cmd1->Commands)
866b274810SRui Ueyama         if (auto *Cmd2 = dyn_cast<InputSectionDescription>(Base2.get()))
87e7282797SDavide Italiano           Ret.emplace_back(Cmd1->Name, Cmd2);
886b274810SRui Ueyama 
896b274810SRui Ueyama   return Ret;
906b274810SRui Ueyama }
916b274810SRui Ueyama 
920659800eSGeorge Rimar static bool fileMatches(const InputSectionDescription *Desc,
930659800eSGeorge Rimar                         StringRef Filename) {
940659800eSGeorge Rimar   if (!globMatch(Desc->FilePattern, Filename))
950659800eSGeorge Rimar     return false;
960659800eSGeorge Rimar   return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
970659800eSGeorge Rimar }
980659800eSGeorge Rimar 
996b274810SRui Ueyama // Returns input sections filtered by given glob patterns.
1006b274810SRui Ueyama template <class ELFT>
1016b274810SRui Ueyama std::vector<InputSectionBase<ELFT> *>
102ad10c3d8SRui Ueyama LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
1030659800eSGeorge Rimar   ArrayRef<StringRef> Patterns = I->SectionPatterns;
1046b274810SRui Ueyama   std::vector<InputSectionBase<ELFT> *> Ret;
1056b274810SRui Ueyama   for (const std::unique_ptr<ObjectFile<ELFT>> &F :
1060659800eSGeorge Rimar        Symtab<ELFT>::X->getObjectFiles()) {
1070659800eSGeorge Rimar     if (fileMatches(I, sys::path::filename(F->getName())))
1086b274810SRui Ueyama       for (InputSectionBase<ELFT> *S : F->getSections())
1090659800eSGeorge Rimar         if (!isDiscarded(S) && !S->OutSec &&
1100659800eSGeorge Rimar             match(Patterns, S->getSectionName()))
1116b274810SRui Ueyama           Ret.push_back(S);
1120659800eSGeorge Rimar   }
1133e6b0277SEugene Leviant 
1143e6b0277SEugene Leviant   if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
115ad10c3d8SRui Ueyama     Ret.push_back(CommonInputSection<ELFT>::X);
1163e6b0277SEugene Leviant 
1176b274810SRui Ueyama   return Ret;
1186b274810SRui Ueyama }
1196b274810SRui Ueyama 
120e63d81bdSEugene Leviant // Add input section to output section. If there is no output section yet,
121e63d81bdSEugene Leviant // then create it and add to output section list.
122c3cb884cSGeorge Rimar template <class ELFT>
123c3cb884cSGeorge Rimar static void addSection(OutputSectionFactory<ELFT> &Factory,
124c3cb884cSGeorge Rimar                        std::vector<OutputSectionBase<ELFT> *> &Out,
125c3cb884cSGeorge Rimar                        InputSectionBase<ELFT> *C, StringRef Name) {
126e63d81bdSEugene Leviant   OutputSectionBase<ELFT> *Sec;
127e63d81bdSEugene Leviant   bool IsNew;
128e63d81bdSEugene Leviant   std::tie(Sec, IsNew) = Factory.create(C, Name);
129e63d81bdSEugene Leviant   if (IsNew)
130c3cb884cSGeorge Rimar     Out.push_back(Sec);
131e63d81bdSEugene Leviant   Sec->addSection(C);
132c3cb884cSGeorge Rimar }
133c3cb884cSGeorge Rimar 
134c3cb884cSGeorge Rimar template <class ELFT>
135*0702c4e8SGeorge Rimar static bool compareByName(InputSectionBase<ELFT> *A,
136*0702c4e8SGeorge Rimar                           InputSectionBase<ELFT> *B) {
137*0702c4e8SGeorge Rimar   return A->getSectionName() < B->getSectionName();
138*0702c4e8SGeorge Rimar }
139*0702c4e8SGeorge Rimar 
140*0702c4e8SGeorge Rimar template <class ELFT>
141c3cb884cSGeorge Rimar std::vector<OutputSectionBase<ELFT> *>
142c3cb884cSGeorge Rimar LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
143c3cb884cSGeorge Rimar   std::vector<OutputSectionBase<ELFT> *> Ret;
144e63d81bdSEugene Leviant 
1456b274810SRui Ueyama   for (auto &P : getSectionMap()) {
146*0702c4e8SGeorge Rimar     std::vector<InputSectionBase<ELFT> *> Sections;
1476b274810SRui Ueyama     StringRef OutputName = P.first;
148e7282797SDavide Italiano     const InputSectionDescription *I = P.second;
149ad10c3d8SRui Ueyama     for (InputSectionBase<ELFT> *S : getInputSections(I)) {
1506b274810SRui Ueyama       if (OutputName == "/DISCARD/") {
151eea3114fSGeorge Rimar         S->Live = false;
1526b274810SRui Ueyama         reportDiscarded(S);
1536b274810SRui Ueyama         continue;
154eea3114fSGeorge Rimar       }
155*0702c4e8SGeorge Rimar       Sections.push_back(S);
156eea3114fSGeorge Rimar     }
157*0702c4e8SGeorge Rimar     if (I->Sort)
158*0702c4e8SGeorge Rimar       std::stable_sort(Sections.begin(), Sections.end(), compareByName<ELFT>);
159*0702c4e8SGeorge Rimar     for (InputSectionBase<ELFT> *S : Sections)
160*0702c4e8SGeorge Rimar       addSection(Factory, Ret, S, OutputName);
161eea3114fSGeorge Rimar   }
162e63d81bdSEugene Leviant 
163e63d81bdSEugene Leviant   // Add all other input sections, which are not listed in script.
1646b274810SRui Ueyama   for (const std::unique_ptr<ObjectFile<ELFT>> &F :
1656b274810SRui Ueyama        Symtab<ELFT>::X->getObjectFiles())
1666b274810SRui Ueyama     for (InputSectionBase<ELFT> *S : F->getSections())
1676b274810SRui Ueyama       if (!isDiscarded(S) && !S->OutSec)
168c3cb884cSGeorge Rimar         addSection(Factory, Ret, S, getOutputSectionName(S));
169e63d81bdSEugene Leviant 
1703c291e1aSRui Ueyama   // Remove from the output all the sections which did not meet
1713c291e1aSRui Ueyama   // the optional constraints.
1726b274810SRui Ueyama   return filter(Ret);
1733c291e1aSRui Ueyama }
1743c291e1aSRui Ueyama 
1753c291e1aSRui Ueyama // Process ONLY_IF_RO and ONLY_IF_RW.
1763c291e1aSRui Ueyama template <class ELFT>
1773c291e1aSRui Ueyama std::vector<OutputSectionBase<ELFT> *>
1783c291e1aSRui Ueyama LinkerScript<ELFT>::filter(std::vector<OutputSectionBase<ELFT> *> &Sections) {
1793c291e1aSRui Ueyama   // In this loop, we remove output sections if they don't satisfy
1803c291e1aSRui Ueyama   // requested properties.
1813c291e1aSRui Ueyama   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
1823c291e1aSRui Ueyama     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
1833c291e1aSRui Ueyama     if (!Cmd || Cmd->Name == "/DISCARD/")
1843c291e1aSRui Ueyama       continue;
1853c291e1aSRui Ueyama 
186bfc4a4b7SGeorge Rimar     if (Cmd->Constraint == ConstraintKind::NoConstraint)
1873c291e1aSRui Ueyama       continue;
188bfc4a4b7SGeorge Rimar 
189bfc4a4b7SGeorge Rimar     auto It = llvm::find_if(Sections, [&](OutputSectionBase<ELFT> *S) {
190bfc4a4b7SGeorge Rimar       return S->getName() == Cmd->Name;
191bfc4a4b7SGeorge Rimar     });
192bfc4a4b7SGeorge Rimar     if (It == Sections.end())
193bfc4a4b7SGeorge Rimar       continue;
1943c291e1aSRui Ueyama 
1953c291e1aSRui Ueyama     OutputSectionBase<ELFT> *Sec = *It;
1963c291e1aSRui Ueyama     bool Writable = (Sec->getFlags() & SHF_WRITE);
1973c291e1aSRui Ueyama     bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
1983c291e1aSRui Ueyama     bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
1993c291e1aSRui Ueyama 
200ed942713SRui Ueyama     if ((RO && Writable) || (RW && !Writable))
2013c291e1aSRui Ueyama       Sections.erase(It);
2023c291e1aSRui Ueyama   }
2033c291e1aSRui Ueyama   return Sections;
204e63d81bdSEugene Leviant }
205e63d81bdSEugene Leviant 
206e63d81bdSEugene Leviant template <class ELFT>
20707320e40SRui Ueyama void LinkerScript<ELFT>::assignAddresses(
208dbbd8b15SGeorge Rimar     ArrayRef<OutputSectionBase<ELFT> *> Sections) {
209652852c5SGeorge Rimar   // Orphan sections are sections present in the input files which
2107c18c28cSRui Ueyama   // are not explicitly placed into the output file by the linker script.
2117c18c28cSRui Ueyama   // We place orphan sections at end of file.
2127c18c28cSRui Ueyama   // Other linkers places them using some heuristics as described in
213652852c5SGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
2147c18c28cSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : Sections) {
215652852c5SGeorge Rimar     StringRef Name = Sec->getName();
216c3e2a4b0SRui Ueyama     if (getSectionIndex(Name) == INT_MAX)
217076fe157SGeorge Rimar       Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
218652852c5SGeorge Rimar   }
219652852c5SGeorge Rimar 
2207c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
221c998a8c0SRui Ueyama   Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
222467c4d55SEugene Leviant   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
223652852c5SGeorge Rimar   uintX_t ThreadBssOffset = 0;
224652852c5SGeorge Rimar 
225076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
226076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
2278d083e6aSRui Ueyama       if (Cmd->Name == ".") {
2288d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
2298d083e6aSRui Ueyama       } else if (Cmd->Sym) {
2308d083e6aSRui Ueyama         cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
2318d083e6aSRui Ueyama       }
23205ef4cffSRui Ueyama       continue;
233652852c5SGeorge Rimar     }
234652852c5SGeorge Rimar 
235fb8978fcSDima Stepanov     // Find all the sections with required name. There can be more than
2366ad330acSGeorge Rimar     // one section with such name, if the alignment, flags or type
237fb8978fcSDima Stepanov     // attribute differs.
238076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
239fb8978fcSDima Stepanov     for (OutputSectionBase<ELFT> *Sec : Sections) {
240076fe157SGeorge Rimar       if (Sec->getName() != Cmd->Name)
241652852c5SGeorge Rimar         continue;
242652852c5SGeorge Rimar 
24358e5c4dcSGeorge Rimar       if (Cmd->AddrExpr)
24458e5c4dcSGeorge Rimar         Dot = Cmd->AddrExpr(Dot);
24558e5c4dcSGeorge Rimar 
246630c6179SGeorge Rimar       if (Cmd->AlignExpr)
247630c6179SGeorge Rimar         Sec->updateAlignment(Cmd->AlignExpr(Dot));
248630c6179SGeorge Rimar 
249652852c5SGeorge Rimar       if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
250c998a8c0SRui Ueyama         uintX_t TVA = Dot + ThreadBssOffset;
251424b4081SRui Ueyama         TVA = alignTo(TVA, Sec->getAlignment());
252652852c5SGeorge Rimar         Sec->setVA(TVA);
253c998a8c0SRui Ueyama         ThreadBssOffset = TVA - Dot + Sec->getSize();
254652852c5SGeorge Rimar         continue;
255652852c5SGeorge Rimar       }
256652852c5SGeorge Rimar 
257652852c5SGeorge Rimar       if (Sec->getFlags() & SHF_ALLOC) {
258424b4081SRui Ueyama         Dot = alignTo(Dot, Sec->getAlignment());
259c998a8c0SRui Ueyama         Sec->setVA(Dot);
260467c4d55SEugene Leviant         MinVA = std::min(MinVA, Dot);
261c998a8c0SRui Ueyama         Dot += Sec->getSize();
262652852c5SGeorge Rimar         continue;
263652852c5SGeorge Rimar       }
264652852c5SGeorge Rimar     }
265652852c5SGeorge Rimar   }
266467c4d55SEugene Leviant 
26764c32d6fSRafael Espindola   // ELF and Program headers need to be right before the first section in
268b91e7118SGeorge Rimar   // memory. Set their addresses accordingly.
269467c4d55SEugene Leviant   MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
270467c4d55SEugene Leviant                         Out<ELFT>::ProgramHeaders->getSize(),
271467c4d55SEugene Leviant                     Target->PageSize);
272467c4d55SEugene Leviant   Out<ELFT>::ElfHeader->setVA(MinVA);
273467c4d55SEugene Leviant   Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
274fb8978fcSDima Stepanov }
275652852c5SGeorge Rimar 
27607320e40SRui Ueyama template <class ELFT>
27774df5c7eSRafael Espindola std::vector<PhdrEntry<ELFT>>
278bbe38602SEugene Leviant LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
279edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
280bbe38602SEugene Leviant 
281bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
282edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
283edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
284bbe38602SEugene Leviant 
285bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
286adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
287bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
288adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
289bbe38602SEugene Leviant 
290bbe38602SEugene Leviant     switch (Cmd.Type) {
291bbe38602SEugene Leviant     case PT_INTERP:
292fd03cfd2SRui Ueyama       if (Out<ELFT>::Interp)
293adca245fSRui Ueyama         Phdr.add(Out<ELFT>::Interp);
294bbe38602SEugene Leviant       break;
295bbe38602SEugene Leviant     case PT_DYNAMIC:
296bbe38602SEugene Leviant       if (isOutputDynamic<ELFT>()) {
2970b113671SRafael Espindola         Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
298adca245fSRui Ueyama         Phdr.add(Out<ELFT>::Dynamic);
299bbe38602SEugene Leviant       }
300bbe38602SEugene Leviant       break;
301bbe38602SEugene Leviant     case PT_GNU_EH_FRAME:
302bbe38602SEugene Leviant       if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
3030b113671SRafael Espindola         Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
304adca245fSRui Ueyama         Phdr.add(Out<ELFT>::EhFrameHdr);
305bbe38602SEugene Leviant       }
306bbe38602SEugene Leviant       break;
307bbe38602SEugene Leviant     }
308bbe38602SEugene Leviant   }
309bbe38602SEugene Leviant 
310edebbdf1SRui Ueyama   PhdrEntry<ELFT> *Load = nullptr;
311edebbdf1SRui Ueyama   uintX_t Flags = PF_R;
312bbe38602SEugene Leviant   for (OutputSectionBase<ELFT> *Sec : Sections) {
313bbe38602SEugene Leviant     if (!(Sec->getFlags() & SHF_ALLOC))
314bbe38602SEugene Leviant       break;
315bbe38602SEugene Leviant 
316edebbdf1SRui Ueyama     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
317bbe38602SEugene Leviant     if (!PhdrIds.empty()) {
318bbe38602SEugene Leviant       // Assign headers specified by linker script
319bbe38602SEugene Leviant       for (size_t Id : PhdrIds) {
320edebbdf1SRui Ueyama         Ret[Id].add(Sec);
321865bf863SEugene Leviant         if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
3220b113671SRafael Espindola           Ret[Id].H.p_flags |= Sec->getPhdrFlags();
323bbe38602SEugene Leviant       }
324bbe38602SEugene Leviant     } else {
325bbe38602SEugene Leviant       // If we have no load segment or flags've changed then we want new load
326bbe38602SEugene Leviant       // segment.
3270b113671SRafael Espindola       uintX_t NewFlags = Sec->getPhdrFlags();
328bbe38602SEugene Leviant       if (Load == nullptr || Flags != NewFlags) {
329edebbdf1SRui Ueyama         Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
330bbe38602SEugene Leviant         Flags = NewFlags;
331bbe38602SEugene Leviant       }
33218f084ffSRui Ueyama       Load->add(Sec);
333bbe38602SEugene Leviant     }
334bbe38602SEugene Leviant   }
335edebbdf1SRui Ueyama   return Ret;
336bbe38602SEugene Leviant }
337bbe38602SEugene Leviant 
338bbe38602SEugene Leviant template <class ELFT>
33907320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
340f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
341f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
342f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
343f6c3ccefSGeorge Rimar         return Cmd->Filler;
344e2ee72b5SGeorge Rimar   return {};
345e2ee72b5SGeorge Rimar }
346e2ee72b5SGeorge Rimar 
347c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
348c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
349c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
350c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
351076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
352f510fa6bSRui Ueyama   int I = 0;
353f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
354076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
355076fe157SGeorge Rimar       if (Cmd->Name == Name)
356f510fa6bSRui Ueyama         return I;
357f510fa6bSRui Ueyama     ++I;
358f510fa6bSRui Ueyama   }
359f510fa6bSRui Ueyama   return INT_MAX;
36071b26e94SGeorge Rimar }
36171b26e94SGeorge Rimar 
36271b26e94SGeorge Rimar // A compartor to sort output sections. Returns -1 or 1 if
36371b26e94SGeorge Rimar // A or B are mentioned in linker script. Otherwise, returns 0.
36407320e40SRui Ueyama template <class ELFT>
36507320e40SRui Ueyama int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
366c3e2a4b0SRui Ueyama   int I = getSectionIndex(A);
367c3e2a4b0SRui Ueyama   int J = getSectionIndex(B);
368c3e2a4b0SRui Ueyama   if (I == INT_MAX && J == INT_MAX)
369717677afSRui Ueyama     return 0;
370717677afSRui Ueyama   return I < J ? -1 : 1;
371717677afSRui Ueyama }
372717677afSRui Ueyama 
3738d083e6aSRui Ueyama // Add symbols defined by linker scripts.
374076fe157SGeorge Rimar template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
375a31c91b1SEugene Leviant   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
376a31c91b1SEugene Leviant     auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
377a31c91b1SEugene Leviant     if (!Cmd || Cmd->Name == ".")
378a31c91b1SEugene Leviant       continue;
379a31c91b1SEugene Leviant 
3808d083e6aSRui Ueyama     // If a symbol was in PROVIDE(), define it only when it is an
3818d083e6aSRui Ueyama     // undefined symbol.
3828ab4108dSDavide Italiano     SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
3838d083e6aSRui Ueyama     if (Cmd->Provide && !(B && B->isUndefined()))
3848d083e6aSRui Ueyama       continue;
3858d083e6aSRui Ueyama 
3868d083e6aSRui Ueyama     // Define an absolute symbol. The symbol value will be assigned later.
3878d083e6aSRui Ueyama     // (At this point, we don't know the final address yet.)
3888d083e6aSRui Ueyama     Symbol *Sym = Symtab<ELFT>::X->addUndefined(Cmd->Name);
3898d083e6aSRui Ueyama     replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, STV_DEFAULT);
3908d083e6aSRui Ueyama     Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
3918d083e6aSRui Ueyama     Cmd->Sym = Sym->body();
392a31c91b1SEugene Leviant   }
393eda81a1bSEugene Leviant }
394eda81a1bSEugene Leviant 
395bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
396bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
397bbe38602SEugene Leviant }
398bbe38602SEugene Leviant 
399bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
400bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
401bbe38602SEugene Leviant // PHDRS {} script block.
402bbe38602SEugene Leviant template <class ELFT>
403edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
404076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
405076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
406edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
40731d842f5SGeorge Rimar       continue;
40831d842f5SGeorge Rimar 
40929c5a2a9SRui Ueyama     std::vector<size_t> Ret;
41029c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
41129c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
41229c5a2a9SRui Ueyama     return Ret;
413bbe38602SEugene Leviant   }
41431d842f5SGeorge Rimar   return {};
41531d842f5SGeorge Rimar }
416bbe38602SEugene Leviant 
41729c5a2a9SRui Ueyama template <class ELFT>
41829c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
41929c5a2a9SRui Ueyama   size_t I = 0;
42029c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
42129c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
42229c5a2a9SRui Ueyama       return I;
42329c5a2a9SRui Ueyama     ++I;
42429c5a2a9SRui Ueyama   }
42529c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
42629c5a2a9SRui Ueyama   return 0;
42729c5a2a9SRui Ueyama }
42829c5a2a9SRui Ueyama 
42907320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
430c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
431c3794e58SGeorge Rimar 
432f7c5fbb1SRui Ueyama public:
43307320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
434f23b2320SGeorge Rimar 
4354a46539cSRui Ueyama   void run();
436f7c5fbb1SRui Ueyama 
437f7c5fbb1SRui Ueyama private:
43852a1509eSRui Ueyama   void addFile(StringRef Path);
43952a1509eSRui Ueyama 
440f7c5fbb1SRui Ueyama   void readAsNeeded();
44190c5099eSDenis Protivensky   void readEntry();
44283f406cfSGeorge Rimar   void readExtern();
443f7c5fbb1SRui Ueyama   void readGroup();
44431aa1f83SRui Ueyama   void readInclude();
445c3794e58SGeorge Rimar   void readNothing() {}
446ee59282bSRui Ueyama   void readOutput();
4479159ce93SDavide Italiano   void readOutputArch();
448f7c5fbb1SRui Ueyama   void readOutputFormat();
449bbe38602SEugene Leviant   void readPhdrs();
45068a39a65SDavide Italiano   void readSearchDir();
4518e3b38abSDenis Protivensky   void readSections();
4528e3b38abSDenis Protivensky 
453113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
454eda81a1bSEugene Leviant   void readOutputSectionDescription(StringRef OutSec);
455f71caa2bSRui Ueyama   std::vector<uint8_t> readOutputSectionFiller();
456bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
4570659800eSGeorge Rimar   std::unique_ptr<InputSectionDescription> readInputSectionDescription();
458*0702c4e8SGeorge Rimar   void readInputFilePattern(InputSectionDescription *InCmd, bool Keep);
4590659800eSGeorge Rimar   void readInputSectionRules(InputSectionDescription *InCmd, bool Keep);
460bbe38602SEugene Leviant   unsigned readPhdrType();
461a31c91b1SEugene Leviant   void readProvide(bool Hidden);
462630c6179SGeorge Rimar   void readAlign(OutputSectionCommand *Cmd);
46303fc010eSGeorge Rimar   void readSort();
464708019c4SRui Ueyama 
465708019c4SRui Ueyama   Expr readExpr();
466708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
467708019c4SRui Ueyama   Expr readPrimary();
468708019c4SRui Ueyama   Expr readTernary(Expr Cond);
469708019c4SRui Ueyama   Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
470f7c5fbb1SRui Ueyama 
471c3794e58SGeorge Rimar   const static StringMap<Handler> Cmd;
47207320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
47307320e40SRui Ueyama   StringSaver Saver = {ScriptConfig->Alloc};
47416b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
475f7c5fbb1SRui Ueyama };
476f7c5fbb1SRui Ueyama 
477e0df00b9SRafael Espindola const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
478c3794e58SGeorge Rimar     {"ENTRY", &ScriptParser::readEntry},
479c3794e58SGeorge Rimar     {"EXTERN", &ScriptParser::readExtern},
480c3794e58SGeorge Rimar     {"GROUP", &ScriptParser::readGroup},
481c3794e58SGeorge Rimar     {"INCLUDE", &ScriptParser::readInclude},
482c3794e58SGeorge Rimar     {"INPUT", &ScriptParser::readGroup},
483c3794e58SGeorge Rimar     {"OUTPUT", &ScriptParser::readOutput},
484c3794e58SGeorge Rimar     {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
485c3794e58SGeorge Rimar     {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
486bbe38602SEugene Leviant     {"PHDRS", &ScriptParser::readPhdrs},
487c3794e58SGeorge Rimar     {"SEARCH_DIR", &ScriptParser::readSearchDir},
488c3794e58SGeorge Rimar     {"SECTIONS", &ScriptParser::readSections},
489c3794e58SGeorge Rimar     {";", &ScriptParser::readNothing}};
490c3794e58SGeorge Rimar 
491717677afSRui Ueyama void ScriptParser::run() {
492f7c5fbb1SRui Ueyama   while (!atEOF()) {
493f7c5fbb1SRui Ueyama     StringRef Tok = next();
494c3794e58SGeorge Rimar     if (Handler Fn = Cmd.lookup(Tok))
495c3794e58SGeorge Rimar       (this->*Fn)();
496c3794e58SGeorge Rimar     else
4975761042dSGeorge Rimar       setError("unknown directive: " + Tok);
498f7c5fbb1SRui Ueyama   }
499f7c5fbb1SRui Ueyama }
500f7c5fbb1SRui Ueyama 
501717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
50216b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
50316b0cc9eSSimon Atanasyan     SmallString<128> Path;
50416b0cc9eSSimon Atanasyan     (Config->Sysroot + S).toStringRef(Path);
50516b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
50616b0cc9eSSimon Atanasyan       Driver->addFile(Saver.save(Path.str()));
50716b0cc9eSSimon Atanasyan       return;
50816b0cc9eSSimon Atanasyan     }
50916b0cc9eSSimon Atanasyan   }
51016b0cc9eSSimon Atanasyan 
511f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
51252a1509eSRui Ueyama     Driver->addFile(S);
51352a1509eSRui Ueyama   } else if (S.startswith("=")) {
51452a1509eSRui Ueyama     if (Config->Sysroot.empty())
51552a1509eSRui Ueyama       Driver->addFile(S.substr(1));
51652a1509eSRui Ueyama     else
51752a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
51852a1509eSRui Ueyama   } else if (S.startswith("-l")) {
51921eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
520a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
521a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
52252a1509eSRui Ueyama   } else {
52352a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
52452a1509eSRui Ueyama     if (Path.empty())
525777f9630SGeorge Rimar       setError("unable to find " + S);
526025d59b1SRui Ueyama     else
52752a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
52852a1509eSRui Ueyama   }
52952a1509eSRui Ueyama }
53052a1509eSRui Ueyama 
531717677afSRui Ueyama void ScriptParser::readAsNeeded() {
532f7c5fbb1SRui Ueyama   expect("(");
53335da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
53435da9b6eSRui Ueyama   Config->AsNeeded = true;
535025d59b1SRui Ueyama   while (!Error) {
536f7c5fbb1SRui Ueyama     StringRef Tok = next();
537f7c5fbb1SRui Ueyama     if (Tok == ")")
53835da9b6eSRui Ueyama       break;
53952a1509eSRui Ueyama     addFile(Tok);
540f7c5fbb1SRui Ueyama   }
54135da9b6eSRui Ueyama   Config->AsNeeded = Orig;
542f7c5fbb1SRui Ueyama }
543f7c5fbb1SRui Ueyama 
544717677afSRui Ueyama void ScriptParser::readEntry() {
54590c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
54690c5099eSDenis Protivensky   expect("(");
54790c5099eSDenis Protivensky   StringRef Tok = next();
54890c5099eSDenis Protivensky   if (Config->Entry.empty())
54990c5099eSDenis Protivensky     Config->Entry = Tok;
55090c5099eSDenis Protivensky   expect(")");
55190c5099eSDenis Protivensky }
55290c5099eSDenis Protivensky 
553717677afSRui Ueyama void ScriptParser::readExtern() {
55483f406cfSGeorge Rimar   expect("(");
555025d59b1SRui Ueyama   while (!Error) {
55683f406cfSGeorge Rimar     StringRef Tok = next();
55783f406cfSGeorge Rimar     if (Tok == ")")
55883f406cfSGeorge Rimar       return;
55983f406cfSGeorge Rimar     Config->Undefined.push_back(Tok);
56083f406cfSGeorge Rimar   }
56183f406cfSGeorge Rimar }
56283f406cfSGeorge Rimar 
563717677afSRui Ueyama void ScriptParser::readGroup() {
564f7c5fbb1SRui Ueyama   expect("(");
565025d59b1SRui Ueyama   while (!Error) {
566f7c5fbb1SRui Ueyama     StringRef Tok = next();
567f7c5fbb1SRui Ueyama     if (Tok == ")")
568f7c5fbb1SRui Ueyama       return;
569f7c5fbb1SRui Ueyama     if (Tok == "AS_NEEDED") {
570f7c5fbb1SRui Ueyama       readAsNeeded();
571f7c5fbb1SRui Ueyama       continue;
572f7c5fbb1SRui Ueyama     }
57352a1509eSRui Ueyama     addFile(Tok);
574f7c5fbb1SRui Ueyama   }
575f7c5fbb1SRui Ueyama }
576f7c5fbb1SRui Ueyama 
577717677afSRui Ueyama void ScriptParser::readInclude() {
57831aa1f83SRui Ueyama   StringRef Tok = next();
57931aa1f83SRui Ueyama   auto MBOrErr = MemoryBuffer::getFile(Tok);
580025d59b1SRui Ueyama   if (!MBOrErr) {
5815761042dSGeorge Rimar     setError("cannot open " + Tok);
582025d59b1SRui Ueyama     return;
583025d59b1SRui Ueyama   }
58431aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
585a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
586a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
58731aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
58831aa1f83SRui Ueyama }
58931aa1f83SRui Ueyama 
590717677afSRui Ueyama void ScriptParser::readOutput() {
591ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
592ee59282bSRui Ueyama   expect("(");
593ee59282bSRui Ueyama   StringRef Tok = next();
594ee59282bSRui Ueyama   if (Config->OutputFile.empty())
595ee59282bSRui Ueyama     Config->OutputFile = Tok;
596ee59282bSRui Ueyama   expect(")");
597ee59282bSRui Ueyama }
598ee59282bSRui Ueyama 
599717677afSRui Ueyama void ScriptParser::readOutputArch() {
6009159ce93SDavide Italiano   // Error checking only for now.
6019159ce93SDavide Italiano   expect("(");
6029159ce93SDavide Italiano   next();
6039159ce93SDavide Italiano   expect(")");
6049159ce93SDavide Italiano }
6059159ce93SDavide Italiano 
606717677afSRui Ueyama void ScriptParser::readOutputFormat() {
607f7c5fbb1SRui Ueyama   // Error checking only for now.
608f7c5fbb1SRui Ueyama   expect("(");
609f7c5fbb1SRui Ueyama   next();
6106836c618SDavide Italiano   StringRef Tok = next();
6116836c618SDavide Italiano   if (Tok == ")")
6126836c618SDavide Italiano    return;
613025d59b1SRui Ueyama   if (Tok != ",") {
6145761042dSGeorge Rimar     setError("unexpected token: " + Tok);
615025d59b1SRui Ueyama     return;
616025d59b1SRui Ueyama   }
6176836c618SDavide Italiano   next();
6186836c618SDavide Italiano   expect(",");
6196836c618SDavide Italiano   next();
620f7c5fbb1SRui Ueyama   expect(")");
621f7c5fbb1SRui Ueyama }
622f7c5fbb1SRui Ueyama 
623bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
624bbe38602SEugene Leviant   expect("{");
625bbe38602SEugene Leviant   while (!Error && !skip("}")) {
626bbe38602SEugene Leviant     StringRef Tok = next();
627865bf863SEugene Leviant     Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
628bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
629bbe38602SEugene Leviant 
630bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
631bbe38602SEugene Leviant     do {
632bbe38602SEugene Leviant       Tok = next();
633bbe38602SEugene Leviant       if (Tok == ";")
634bbe38602SEugene Leviant         break;
635bbe38602SEugene Leviant       if (Tok == "FILEHDR")
636bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
637bbe38602SEugene Leviant       else if (Tok == "PHDRS")
638bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
639865bf863SEugene Leviant       else if (Tok == "FLAGS") {
640865bf863SEugene Leviant         expect("(");
641865bf863SEugene Leviant         next().getAsInteger(0, PhdrCmd.Flags);
642865bf863SEugene Leviant         expect(")");
643865bf863SEugene Leviant       } else
644bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
645bbe38602SEugene Leviant     } while (!Error);
646bbe38602SEugene Leviant   }
647bbe38602SEugene Leviant }
648bbe38602SEugene Leviant 
649717677afSRui Ueyama void ScriptParser::readSearchDir() {
65068a39a65SDavide Italiano   expect("(");
65106501920SRafael Espindola   Config->SearchPaths.push_back(next());
65268a39a65SDavide Italiano   expect(")");
65368a39a65SDavide Italiano }
65468a39a65SDavide Italiano 
655717677afSRui Ueyama void ScriptParser::readSections() {
6563de0a330SRui Ueyama   Opt.HasContents = true;
6578e3b38abSDenis Protivensky   expect("{");
658652852c5SGeorge Rimar   while (!Error && !skip("}")) {
659113cdec9SRui Ueyama     StringRef Tok = next();
66030835ea4SGeorge Rimar     if (peek() == "=" || peek() == "+=") {
661113cdec9SRui Ueyama       readAssignment(Tok);
662113cdec9SRui Ueyama       expect(";");
663113cdec9SRui Ueyama     } else if (Tok == "PROVIDE") {
664a31c91b1SEugene Leviant       readProvide(false);
665708019c4SRui Ueyama     } else if (Tok == "PROVIDE_HIDDEN") {
666a31c91b1SEugene Leviant       readProvide(true);
667708019c4SRui Ueyama     } else {
668eda81a1bSEugene Leviant       readOutputSectionDescription(Tok);
6698e3b38abSDenis Protivensky     }
670652852c5SGeorge Rimar   }
671708019c4SRui Ueyama }
6728e3b38abSDenis Protivensky 
673708019c4SRui Ueyama static int precedence(StringRef Op) {
674708019c4SRui Ueyama   return StringSwitch<int>(Op)
675708019c4SRui Ueyama       .Case("*", 4)
676708019c4SRui Ueyama       .Case("/", 4)
677708019c4SRui Ueyama       .Case("+", 3)
678708019c4SRui Ueyama       .Case("-", 3)
679708019c4SRui Ueyama       .Case("<", 2)
680708019c4SRui Ueyama       .Case(">", 2)
681708019c4SRui Ueyama       .Case(">=", 2)
682708019c4SRui Ueyama       .Case("<=", 2)
683708019c4SRui Ueyama       .Case("==", 2)
684708019c4SRui Ueyama       .Case("!=", 2)
685708019c4SRui Ueyama       .Case("&", 1)
686708019c4SRui Ueyama       .Default(-1);
687708019c4SRui Ueyama }
688708019c4SRui Ueyama 
689*0702c4e8SGeorge Rimar void ScriptParser::readInputFilePattern(InputSectionDescription *InCmd,
690*0702c4e8SGeorge Rimar                                         bool Keep) {
691*0702c4e8SGeorge Rimar   while (!Error && !skip(")")) {
692*0702c4e8SGeorge Rimar     if (Keep)
693*0702c4e8SGeorge Rimar       Opt.KeptSections.push_back(peek());
694*0702c4e8SGeorge Rimar     InCmd->SectionPatterns.push_back(next());
695*0702c4e8SGeorge Rimar   }
696*0702c4e8SGeorge Rimar }
697*0702c4e8SGeorge Rimar 
698*0702c4e8SGeorge Rimar void ScriptParser::readInputSectionRules(InputSectionDescription *InCmd,
699*0702c4e8SGeorge Rimar                                          bool Keep) {
7000659800eSGeorge Rimar   InCmd->FilePattern = next();
7010ed42b0cSDavide Italiano   expect("(");
702e7282797SDavide Italiano 
703e7282797SDavide Italiano   if (skip("EXCLUDE_FILE")) {
704e7282797SDavide Italiano     expect("(");
705e7282797SDavide Italiano     while (!Error && !skip(")"))
706e7282797SDavide Italiano       InCmd->ExcludedFiles.push_back(next());
707e7282797SDavide Italiano   }
708e7282797SDavide Italiano 
709*0702c4e8SGeorge Rimar   if (skip("SORT")) {
710*0702c4e8SGeorge Rimar     expect("(");
711*0702c4e8SGeorge Rimar     InCmd->Sort = true;
712*0702c4e8SGeorge Rimar     readInputFilePattern(InCmd, Keep);
713*0702c4e8SGeorge Rimar     expect(")");
714*0702c4e8SGeorge Rimar     return;
7150659800eSGeorge Rimar   }
716*0702c4e8SGeorge Rimar 
717*0702c4e8SGeorge Rimar   readInputFilePattern(InCmd, Keep);
7180659800eSGeorge Rimar }
7190659800eSGeorge Rimar 
7200659800eSGeorge Rimar std::unique_ptr<InputSectionDescription>
7210659800eSGeorge Rimar ScriptParser::readInputSectionDescription() {
722352eac37SGeorge Rimar   auto InCmd = llvm::make_unique<InputSectionDescription>();
7230659800eSGeorge Rimar 
7240659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
7250659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
7260659800eSGeorge Rimar   if (skip("KEEP")) {
727e7282797SDavide Italiano     expect("(");
7280659800eSGeorge Rimar     readInputSectionRules(InCmd.get(), true);
7290ed42b0cSDavide Italiano     expect(")");
7300659800eSGeorge Rimar   } else {
7310659800eSGeorge Rimar     readInputSectionRules(InCmd.get(), false);
7320659800eSGeorge Rimar   }
7330659800eSGeorge Rimar 
7340659800eSGeorge Rimar   return InCmd;
7350ed42b0cSDavide Italiano }
7360ed42b0cSDavide Italiano 
737630c6179SGeorge Rimar void ScriptParser::readAlign(OutputSectionCommand *Cmd) {
738630c6179SGeorge Rimar   expect("(");
739630c6179SGeorge Rimar   Cmd->AlignExpr = readExpr();
740630c6179SGeorge Rimar   expect(")");
741630c6179SGeorge Rimar }
742630c6179SGeorge Rimar 
74303fc010eSGeorge Rimar void ScriptParser::readSort() {
74403fc010eSGeorge Rimar   expect("(");
74503fc010eSGeorge Rimar   expect("CONSTRUCTORS");
74603fc010eSGeorge Rimar   expect(")");
74703fc010eSGeorge Rimar }
74803fc010eSGeorge Rimar 
749eda81a1bSEugene Leviant void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
750076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
751076fe157SGeorge Rimar   Opt.Commands.emplace_back(Cmd);
75258e5c4dcSGeorge Rimar 
75358e5c4dcSGeorge Rimar   // Read an address expression.
75458e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
75558e5c4dcSGeorge Rimar   if (peek() != ":")
75658e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
75758e5c4dcSGeorge Rimar 
7588e3b38abSDenis Protivensky   expect(":");
759246f681eSDavide Italiano 
760630c6179SGeorge Rimar   if (skip("ALIGN"))
761630c6179SGeorge Rimar     readAlign(Cmd);
762630c6179SGeorge Rimar 
763246f681eSDavide Italiano   // Parse constraints.
764246f681eSDavide Italiano   if (skip("ONLY_IF_RO"))
765efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
766246f681eSDavide Italiano   if (skip("ONLY_IF_RW"))
767efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
7688e3b38abSDenis Protivensky   expect("{");
7698ec77e64SRui Ueyama 
770025d59b1SRui Ueyama   while (!Error && !skip("}")) {
771f586ff7eSGeorge Rimar     if (peek().startswith("*") || peek() == "KEEP") {
7720659800eSGeorge Rimar       Cmd->Commands.push_back(readInputSectionDescription());
7730659800eSGeorge Rimar       continue;
7740659800eSGeorge Rimar     }
7750659800eSGeorge Rimar 
776481c2ce6SGeorge Rimar     StringRef Tok = next();
7770659800eSGeorge Rimar     if (Tok == "PROVIDE") {
778054a6796SDavide Italiano       readProvide(false);
779054a6796SDavide Italiano     } else if (Tok == "PROVIDE_HIDDEN") {
780054a6796SDavide Italiano       readProvide(true);
78103fc010eSGeorge Rimar     } else if (Tok == "SORT") {
78203fc010eSGeorge Rimar       readSort();
783481c2ce6SGeorge Rimar     } else {
784777f9630SGeorge Rimar       setError("unknown command " + Tok);
785481c2ce6SGeorge Rimar     }
7868e3b38abSDenis Protivensky   }
787076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
788f71caa2bSRui Ueyama   Cmd->Filler = readOutputSectionFiller();
789f71caa2bSRui Ueyama }
7908ec77e64SRui Ueyama 
791f71caa2bSRui Ueyama std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
792e2ee72b5SGeorge Rimar   StringRef Tok = peek();
793f71caa2bSRui Ueyama   if (!Tok.startswith("="))
794f71caa2bSRui Ueyama     return {};
795e2ee72b5SGeorge Rimar   if (!Tok.startswith("=0x")) {
7963ed2f069SRui Ueyama     setError("filler should be a hexadecimal value");
797f71caa2bSRui Ueyama     return {};
798e2ee72b5SGeorge Rimar   }
7993e808976SRui Ueyama   Tok = Tok.substr(3);
800e2ee72b5SGeorge Rimar   next();
801f71caa2bSRui Ueyama   return parseHex(Tok);
8028e3b38abSDenis Protivensky }
8038e3b38abSDenis Protivensky 
804a31c91b1SEugene Leviant void ScriptParser::readProvide(bool Hidden) {
805a31c91b1SEugene Leviant   expect("(");
806174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
807174e0a16SRui Ueyama   Cmd->Provide = true;
808174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
809a31c91b1SEugene Leviant   expect(")");
810a31c91b1SEugene Leviant   expect(";");
811eda81a1bSEugene Leviant }
812eda81a1bSEugene Leviant 
81330835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
81430835ea4SGeorge Rimar   if (S == ".")
81530835ea4SGeorge Rimar     return Dot;
816a31c91b1SEugene Leviant 
817a9c5a528SGeorge Rimar   switch (Config->EKind) {
818a9c5a528SGeorge Rimar   case ELF32LEKind:
819a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
820a9c5a528SGeorge Rimar       return B->getVA<ELF32LE>();
821a9c5a528SGeorge Rimar     break;
822a9c5a528SGeorge Rimar   case ELF32BEKind:
823a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
824a9c5a528SGeorge Rimar       return B->getVA<ELF32BE>();
825a9c5a528SGeorge Rimar     break;
826a9c5a528SGeorge Rimar   case ELF64LEKind:
827a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
828a9c5a528SGeorge Rimar       return B->getVA<ELF64LE>();
829a9c5a528SGeorge Rimar     break;
830a9c5a528SGeorge Rimar   case ELF64BEKind:
831a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
832a9c5a528SGeorge Rimar       return B->getVA<ELF64BE>();
833a9c5a528SGeorge Rimar     break;
8346930a6dcSGeorge Rimar   default:
835b567b628SGeorge Rimar     llvm_unreachable("unsupported target");
836a9c5a528SGeorge Rimar   }
837a9c5a528SGeorge Rimar   error("symbol not found: " + S);
838a9c5a528SGeorge Rimar   return 0;
839a9c5a528SGeorge Rimar }
840a9c5a528SGeorge Rimar 
84130835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
84230835ea4SGeorge Rimar   StringRef Op = next();
84330835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
84430835ea4SGeorge Rimar   Expr E = readExpr();
84530835ea4SGeorge Rimar   if (Op == "+=")
84630835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
84730835ea4SGeorge Rimar   auto *Cmd = new SymbolAssignment(Name, E);
84830835ea4SGeorge Rimar   Opt.Commands.emplace_back(Cmd);
84930835ea4SGeorge Rimar   return Cmd;
85030835ea4SGeorge Rimar }
85130835ea4SGeorge Rimar 
85230835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
85330835ea4SGeorge Rimar // script expression.
85430835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
85530835ea4SGeorge Rimar 
856708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
857708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
858708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
859708019c4SRui Ueyama   while (!atEOF() && !Error) {
860708019c4SRui Ueyama     // Read an operator and an expression.
861708019c4SRui Ueyama     StringRef Op1 = peek();
862708019c4SRui Ueyama     if (Op1 == "?")
863708019c4SRui Ueyama       return readTernary(Lhs);
864708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
865a31c91b1SEugene Leviant       break;
866a31c91b1SEugene Leviant     next();
867708019c4SRui Ueyama     Expr Rhs = readPrimary();
868708019c4SRui Ueyama 
869708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
870708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
871708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
872708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
873708019c4SRui Ueyama     while (!atEOF()) {
874708019c4SRui Ueyama       StringRef Op2 = peek();
875708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
876eda81a1bSEugene Leviant         break;
877708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
878eda81a1bSEugene Leviant     }
879708019c4SRui Ueyama 
880708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
881708019c4SRui Ueyama   }
882708019c4SRui Ueyama   return Lhs;
883708019c4SRui Ueyama }
884708019c4SRui Ueyama 
885708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
886708019c4SRui Ueyama   if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
887708019c4SRui Ueyama     return Target->PageSize;
888708019c4SRui Ueyama   error("unknown constant: " + S);
889708019c4SRui Ueyama   return 0;
890708019c4SRui Ueyama }
891708019c4SRui Ueyama 
892708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
893708019c4SRui Ueyama   StringRef Tok = next();
894708019c4SRui Ueyama 
895708019c4SRui Ueyama   if (Tok == "(") {
896708019c4SRui Ueyama     Expr E = readExpr();
897708019c4SRui Ueyama     expect(")");
898708019c4SRui Ueyama     return E;
899708019c4SRui Ueyama   }
900708019c4SRui Ueyama 
901708019c4SRui Ueyama   // Built-in functions are parsed here.
902708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
903708019c4SRui Ueyama   if (Tok == "ALIGN") {
904708019c4SRui Ueyama     expect("(");
905708019c4SRui Ueyama     Expr E = readExpr();
906708019c4SRui Ueyama     expect(")");
907708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
908708019c4SRui Ueyama   }
909708019c4SRui Ueyama   if (Tok == "CONSTANT") {
910708019c4SRui Ueyama     expect("(");
911708019c4SRui Ueyama     StringRef Tok = next();
912708019c4SRui Ueyama     expect(")");
913708019c4SRui Ueyama     return [=](uint64_t Dot) { return getConstant(Tok); };
914708019c4SRui Ueyama   }
91554c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
91654c145ceSRafael Espindola     expect("(");
91754c145ceSRafael Espindola     next();
91854c145ceSRafael Espindola     expect(",");
91954c145ceSRafael Espindola     uint64_t Val;
92054c145ceSRafael Espindola     next().getAsInteger(0, Val);
92154c145ceSRafael Espindola     expect(")");
92254c145ceSRafael Espindola     return [=](uint64_t Dot) { return Val; };
92354c145ceSRafael Espindola   }
924708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
925708019c4SRui Ueyama     expect("(");
926708019c4SRui Ueyama     Expr E = readExpr();
927708019c4SRui Ueyama     expect(",");
928708019c4SRui Ueyama     readExpr();
929708019c4SRui Ueyama     expect(")");
930f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
931708019c4SRui Ueyama   }
932708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
933708019c4SRui Ueyama     expect("(");
934708019c4SRui Ueyama     expect(".");
935708019c4SRui Ueyama     expect(")");
936708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
937708019c4SRui Ueyama   }
938276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
939276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
940276b4e64SGeorge Rimar   // the next page boundary for simplicity.
941276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
942276b4e64SGeorge Rimar     expect("(");
943276b4e64SGeorge Rimar     next();
944276b4e64SGeorge Rimar     expect(",");
945276b4e64SGeorge Rimar     readExpr();
946276b4e64SGeorge Rimar     expect(")");
947276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
948276b4e64SGeorge Rimar   }
949708019c4SRui Ueyama 
950a9c5a528SGeorge Rimar   // Parse a symbol name or a number literal.
951708019c4SRui Ueyama   uint64_t V = 0;
952a9c5a528SGeorge Rimar   if (Tok.getAsInteger(0, V)) {
95330835ea4SGeorge Rimar     if (Tok != "." && !isValidCIdentifier(Tok))
954708019c4SRui Ueyama       setError("malformed number: " + Tok);
95530835ea4SGeorge Rimar     return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
956a9c5a528SGeorge Rimar   }
957708019c4SRui Ueyama   return [=](uint64_t Dot) { return V; };
958708019c4SRui Ueyama }
959708019c4SRui Ueyama 
960708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
961708019c4SRui Ueyama   next();
962708019c4SRui Ueyama   Expr L = readExpr();
963708019c4SRui Ueyama   expect(":");
964708019c4SRui Ueyama   Expr R = readExpr();
965708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
966708019c4SRui Ueyama }
967708019c4SRui Ueyama 
968708019c4SRui Ueyama Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
969708019c4SRui Ueyama   if (Op == "*")
970708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
971708019c4SRui Ueyama   if (Op == "/") {
972708019c4SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
973708019c4SRui Ueyama       uint64_t RHS = R(Dot);
974708019c4SRui Ueyama       if (RHS == 0) {
975708019c4SRui Ueyama         error("division by zero");
976708019c4SRui Ueyama         return 0;
977708019c4SRui Ueyama       }
978708019c4SRui Ueyama       return L(Dot) / RHS;
979708019c4SRui Ueyama     };
980708019c4SRui Ueyama   }
981708019c4SRui Ueyama   if (Op == "+")
982708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
983708019c4SRui Ueyama   if (Op == "-")
984708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
985708019c4SRui Ueyama   if (Op == "<")
986708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
987708019c4SRui Ueyama   if (Op == ">")
988708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
989708019c4SRui Ueyama   if (Op == ">=")
990708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
991708019c4SRui Ueyama   if (Op == "<=")
992708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
993708019c4SRui Ueyama   if (Op == "==")
994708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
995708019c4SRui Ueyama   if (Op == "!=")
996708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
997708019c4SRui Ueyama   if (Op == "&")
998708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
999708019c4SRui Ueyama   llvm_unreachable("invalid operator");
1000eda81a1bSEugene Leviant }
1001eda81a1bSEugene Leviant 
1002bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1003bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
1004bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
1005bbe38602SEugene Leviant     StringRef Tok = next();
1006bbe38602SEugene Leviant     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1007bbe38602SEugene Leviant     if (Tok.empty()) {
1008bbe38602SEugene Leviant       setError("section header name is empty");
1009bbe38602SEugene Leviant       break;
1010bbe38602SEugene Leviant     }
1011bbe38602SEugene Leviant     Phdrs.push_back(Tok);
1012bbe38602SEugene Leviant   }
1013bbe38602SEugene Leviant   return Phdrs;
1014bbe38602SEugene Leviant }
1015bbe38602SEugene Leviant 
1016bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
1017bbe38602SEugene Leviant   StringRef Tok = next();
1018b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
1019b0f6c590SRui Ueyama       .Case("PT_NULL", PT_NULL)
1020b0f6c590SRui Ueyama       .Case("PT_LOAD", PT_LOAD)
1021b0f6c590SRui Ueyama       .Case("PT_DYNAMIC", PT_DYNAMIC)
1022b0f6c590SRui Ueyama       .Case("PT_INTERP", PT_INTERP)
1023b0f6c590SRui Ueyama       .Case("PT_NOTE", PT_NOTE)
1024b0f6c590SRui Ueyama       .Case("PT_SHLIB", PT_SHLIB)
1025b0f6c590SRui Ueyama       .Case("PT_PHDR", PT_PHDR)
1026b0f6c590SRui Ueyama       .Case("PT_TLS", PT_TLS)
1027b0f6c590SRui Ueyama       .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1028b0f6c590SRui Ueyama       .Case("PT_GNU_STACK", PT_GNU_STACK)
1029b0f6c590SRui Ueyama       .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1030b0f6c590SRui Ueyama       .Default(-1);
1031bbe38602SEugene Leviant 
1032b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1033b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1034b0f6c590SRui Ueyama     return PT_NULL;
1035b0f6c590SRui Ueyama   }
1036b0f6c590SRui Ueyama   return Ret;
1037bbe38602SEugene Leviant }
1038bbe38602SEugene Leviant 
103916b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
104016b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
104116b0cc9eSSimon Atanasyan     return false;
104216b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
104316b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
104416b0cc9eSSimon Atanasyan       return true;
104516b0cc9eSSimon Atanasyan   return false;
104616b0cc9eSSimon Atanasyan }
104716b0cc9eSSimon Atanasyan 
104807320e40SRui Ueyama // Entry point.
104907320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
105016b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
105107320e40SRui Ueyama   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
1052f7c5fbb1SRui Ueyama }
10531ebc8ed7SRui Ueyama 
105407320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
105507320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
105607320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
105707320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1058