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 
776b274810SRui Ueyama // Create a vector of (<output section name>, <input section name patterns>).
786b274810SRui Ueyama // For example, if a returned vector contains (".text" (".foo.*" ".bar.*")),
796b274810SRui Ueyama // input sections start with ".foo." or ".bar." should be added to
806b274810SRui Ueyama // ".text" section.
816b274810SRui Ueyama template <class ELFT>
826b274810SRui Ueyama std::vector<std::pair<StringRef, ArrayRef<StringRef>>>
836b274810SRui Ueyama LinkerScript<ELFT>::getSectionMap() {
846b274810SRui Ueyama   std::vector<std::pair<StringRef, ArrayRef<StringRef>>> Ret;
856b274810SRui Ueyama 
866b274810SRui Ueyama   for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands)
876b274810SRui Ueyama     if (auto *Cmd1 = dyn_cast<OutputSectionCommand>(Base1.get()))
886b274810SRui Ueyama       for (const std::unique_ptr<BaseCommand> &Base2 : Cmd1->Commands)
896b274810SRui Ueyama         if (auto *Cmd2 = dyn_cast<InputSectionDescription>(Base2.get()))
906b274810SRui Ueyama           Ret.emplace_back(Cmd1->Name, Cmd2->Patterns);
916b274810SRui Ueyama 
926b274810SRui Ueyama   return Ret;
936b274810SRui Ueyama }
946b274810SRui Ueyama 
956b274810SRui Ueyama // Returns input sections filtered by given glob patterns.
966b274810SRui Ueyama template <class ELFT>
976b274810SRui Ueyama std::vector<InputSectionBase<ELFT> *>
986b274810SRui Ueyama LinkerScript<ELFT>::getInputSections(ArrayRef<StringRef> Patterns) {
996b274810SRui Ueyama   std::vector<InputSectionBase<ELFT> *> Ret;
1006b274810SRui Ueyama   for (const std::unique_ptr<ObjectFile<ELFT>> &F :
1016b274810SRui Ueyama        Symtab<ELFT>::X->getObjectFiles())
1026b274810SRui Ueyama     for (InputSectionBase<ELFT> *S : F->getSections())
1036b274810SRui Ueyama       if (!isDiscarded(S) && !S->OutSec && match(Patterns, S->getSectionName()))
1046b274810SRui Ueyama         Ret.push_back(S);
1056b274810SRui Ueyama   return Ret;
1066b274810SRui Ueyama }
1076b274810SRui Ueyama 
108652852c5SGeorge Rimar template <class ELFT>
109a7f7884dSRui Ueyama std::vector<OutputSectionBase<ELFT> *>
110e63d81bdSEugene Leviant LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
1116b274810SRui Ueyama   std::vector<OutputSectionBase<ELFT> *> Ret;
112a7f7884dSRui Ueyama 
113e63d81bdSEugene Leviant   // Add input section to output section. If there is no output section yet,
114e63d81bdSEugene Leviant   // then create it and add to output section list.
1156b274810SRui Ueyama   auto Add = [&](InputSectionBase<ELFT> *C, StringRef Name) {
116e63d81bdSEugene Leviant     OutputSectionBase<ELFT> *Sec;
117e63d81bdSEugene Leviant     bool IsNew;
118e63d81bdSEugene Leviant     std::tie(Sec, IsNew) = Factory.create(C, Name);
119e63d81bdSEugene Leviant     if (IsNew)
1206b274810SRui Ueyama       Ret.push_back(Sec);
121e63d81bdSEugene Leviant     Sec->addSection(C);
122e63d81bdSEugene Leviant   };
123e63d81bdSEugene Leviant 
1246b274810SRui Ueyama   for (auto &P : getSectionMap()) {
1256b274810SRui Ueyama     StringRef OutputName = P.first;
1266b274810SRui Ueyama     ArrayRef<StringRef> InputPatterns = P.second;
1276b274810SRui Ueyama     for (InputSectionBase<ELFT> *S : getInputSections(InputPatterns)) {
1286b274810SRui Ueyama       if (OutputName == "/DISCARD/") {
129eea3114fSGeorge Rimar         S->Live = false;
1306b274810SRui Ueyama         reportDiscarded(S);
1316b274810SRui Ueyama         continue;
132eea3114fSGeorge Rimar       }
1336b274810SRui Ueyama       Add(S, OutputName);
134eea3114fSGeorge Rimar     }
135eea3114fSGeorge Rimar   }
136e63d81bdSEugene Leviant 
137e63d81bdSEugene Leviant   // Add all other input sections, which are not listed in script.
1386b274810SRui Ueyama   for (const std::unique_ptr<ObjectFile<ELFT>> &F :
1396b274810SRui Ueyama        Symtab<ELFT>::X->getObjectFiles())
1406b274810SRui Ueyama     for (InputSectionBase<ELFT> *S : F->getSections())
1416b274810SRui Ueyama       if (!isDiscarded(S) && !S->OutSec)
1426b274810SRui Ueyama         Add(S, getOutputSectionName(S));
143e63d81bdSEugene Leviant 
1443c291e1aSRui Ueyama   // Remove from the output all the sections which did not meet
1453c291e1aSRui Ueyama   // the optional constraints.
1466b274810SRui Ueyama   return filter(Ret);
1473c291e1aSRui Ueyama }
1483c291e1aSRui Ueyama 
1493c291e1aSRui Ueyama // Process ONLY_IF_RO and ONLY_IF_RW.
1503c291e1aSRui Ueyama template <class ELFT>
1513c291e1aSRui Ueyama std::vector<OutputSectionBase<ELFT> *>
1523c291e1aSRui Ueyama LinkerScript<ELFT>::filter(std::vector<OutputSectionBase<ELFT> *> &Sections) {
1533c291e1aSRui Ueyama   // In this loop, we remove output sections if they don't satisfy
1543c291e1aSRui Ueyama   // requested properties.
1553c291e1aSRui Ueyama   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
1563c291e1aSRui Ueyama     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
1573c291e1aSRui Ueyama     if (!Cmd || Cmd->Name == "/DISCARD/")
1583c291e1aSRui Ueyama       continue;
1593c291e1aSRui Ueyama 
160bfc4a4b7SGeorge Rimar     if (Cmd->Constraint == ConstraintKind::NoConstraint)
1613c291e1aSRui Ueyama       continue;
162bfc4a4b7SGeorge Rimar 
163bfc4a4b7SGeorge Rimar     auto It = llvm::find_if(Sections, [&](OutputSectionBase<ELFT> *S) {
164bfc4a4b7SGeorge Rimar       return S->getName() == Cmd->Name;
165bfc4a4b7SGeorge Rimar     });
166bfc4a4b7SGeorge Rimar     if (It == Sections.end())
167bfc4a4b7SGeorge Rimar       continue;
1683c291e1aSRui Ueyama 
1693c291e1aSRui Ueyama     OutputSectionBase<ELFT> *Sec = *It;
1703c291e1aSRui Ueyama     bool Writable = (Sec->getFlags() & SHF_WRITE);
1713c291e1aSRui Ueyama     bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
1723c291e1aSRui Ueyama     bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
1733c291e1aSRui Ueyama 
1743c291e1aSRui Ueyama     if ((RO && Writable) || (RW && !Writable)) {
1753c291e1aSRui Ueyama       Sections.erase(It);
1763c291e1aSRui Ueyama       continue;
1773c291e1aSRui Ueyama     }
1783c291e1aSRui Ueyama   }
1793c291e1aSRui Ueyama   return Sections;
180e63d81bdSEugene Leviant }
181e63d81bdSEugene Leviant 
182e63d81bdSEugene Leviant template <class ELFT>
18310e576e1SGeorge Rimar void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
184708019c4SRui Ueyama   uint64_t Val = Cmd->Expression(Dot);
18510e576e1SGeorge Rimar   if (Cmd->Name == ".") {
18610e576e1SGeorge Rimar     Dot = Val;
187a31c91b1SEugene Leviant   } else if (!Cmd->Ignore) {
18810e576e1SGeorge Rimar     auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
18910e576e1SGeorge Rimar     D->Value = Val;
19010e576e1SGeorge Rimar   }
19110e576e1SGeorge Rimar }
19210e576e1SGeorge Rimar 
19310e576e1SGeorge Rimar template <class ELFT>
19407320e40SRui Ueyama void LinkerScript<ELFT>::assignAddresses(
195dbbd8b15SGeorge Rimar     ArrayRef<OutputSectionBase<ELFT> *> Sections) {
196652852c5SGeorge Rimar   // Orphan sections are sections present in the input files which
1977c18c28cSRui Ueyama   // are not explicitly placed into the output file by the linker script.
1987c18c28cSRui Ueyama   // We place orphan sections at end of file.
1997c18c28cSRui Ueyama   // Other linkers places them using some heuristics as described in
200652852c5SGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
2017c18c28cSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : Sections) {
202652852c5SGeorge Rimar     StringRef Name = Sec->getName();
203c3e2a4b0SRui Ueyama     if (getSectionIndex(Name) == INT_MAX)
204076fe157SGeorge Rimar       Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
205652852c5SGeorge Rimar   }
206652852c5SGeorge Rimar 
2077c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
208c998a8c0SRui Ueyama   Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
209467c4d55SEugene Leviant   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
210652852c5SGeorge Rimar   uintX_t ThreadBssOffset = 0;
211652852c5SGeorge Rimar 
212076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
213076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
21410e576e1SGeorge Rimar       dispatchAssignment(Cmd);
21505ef4cffSRui Ueyama       continue;
216652852c5SGeorge Rimar     }
217652852c5SGeorge Rimar 
218fb8978fcSDima Stepanov     // Find all the sections with required name. There can be more than
2196ad330acSGeorge Rimar     // one section with such name, if the alignment, flags or type
220fb8978fcSDima Stepanov     // attribute differs.
221076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
222fb8978fcSDima Stepanov     for (OutputSectionBase<ELFT> *Sec : Sections) {
223076fe157SGeorge Rimar       if (Sec->getName() != Cmd->Name)
224652852c5SGeorge Rimar         continue;
225652852c5SGeorge Rimar 
22658e5c4dcSGeorge Rimar       if (Cmd->AddrExpr)
22758e5c4dcSGeorge Rimar         Dot = Cmd->AddrExpr(Dot);
22858e5c4dcSGeorge Rimar 
229652852c5SGeorge Rimar       if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
230c998a8c0SRui Ueyama         uintX_t TVA = Dot + ThreadBssOffset;
231424b4081SRui Ueyama         TVA = alignTo(TVA, Sec->getAlignment());
232652852c5SGeorge Rimar         Sec->setVA(TVA);
233c998a8c0SRui Ueyama         ThreadBssOffset = TVA - Dot + Sec->getSize();
234652852c5SGeorge Rimar         continue;
235652852c5SGeorge Rimar       }
236652852c5SGeorge Rimar 
237652852c5SGeorge Rimar       if (Sec->getFlags() & SHF_ALLOC) {
238424b4081SRui Ueyama         Dot = alignTo(Dot, Sec->getAlignment());
239c998a8c0SRui Ueyama         Sec->setVA(Dot);
240467c4d55SEugene Leviant         MinVA = std::min(MinVA, Dot);
241c998a8c0SRui Ueyama         Dot += Sec->getSize();
242652852c5SGeorge Rimar         continue;
243652852c5SGeorge Rimar       }
244652852c5SGeorge Rimar     }
245652852c5SGeorge Rimar   }
246467c4d55SEugene Leviant 
24764c32d6fSRafael Espindola   // ELF and Program headers need to be right before the first section in
248b91e7118SGeorge Rimar   // memory. Set their addresses accordingly.
249467c4d55SEugene Leviant   MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
250467c4d55SEugene Leviant                         Out<ELFT>::ProgramHeaders->getSize(),
251467c4d55SEugene Leviant                     Target->PageSize);
252467c4d55SEugene Leviant   Out<ELFT>::ElfHeader->setVA(MinVA);
253467c4d55SEugene Leviant   Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
254fb8978fcSDima Stepanov }
255652852c5SGeorge Rimar 
25607320e40SRui Ueyama template <class ELFT>
25774df5c7eSRafael Espindola std::vector<PhdrEntry<ELFT>>
258bbe38602SEugene Leviant LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
259edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
260bbe38602SEugene Leviant 
261bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
262edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
263edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
264bbe38602SEugene Leviant 
265bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
266adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
267bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
268adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
269bbe38602SEugene Leviant 
270bbe38602SEugene Leviant     switch (Cmd.Type) {
271bbe38602SEugene Leviant     case PT_INTERP:
272fd03cfd2SRui Ueyama       if (Out<ELFT>::Interp)
273adca245fSRui Ueyama         Phdr.add(Out<ELFT>::Interp);
274bbe38602SEugene Leviant       break;
275bbe38602SEugene Leviant     case PT_DYNAMIC:
276bbe38602SEugene Leviant       if (isOutputDynamic<ELFT>()) {
277adca245fSRui Ueyama         Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
278adca245fSRui Ueyama         Phdr.add(Out<ELFT>::Dynamic);
279bbe38602SEugene Leviant       }
280bbe38602SEugene Leviant       break;
281bbe38602SEugene Leviant     case PT_GNU_EH_FRAME:
282bbe38602SEugene Leviant       if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
283adca245fSRui Ueyama         Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
284adca245fSRui Ueyama         Phdr.add(Out<ELFT>::EhFrameHdr);
285bbe38602SEugene Leviant       }
286bbe38602SEugene Leviant       break;
287bbe38602SEugene Leviant     }
288bbe38602SEugene Leviant   }
289bbe38602SEugene Leviant 
290edebbdf1SRui Ueyama   PhdrEntry<ELFT> *Load = nullptr;
291edebbdf1SRui Ueyama   uintX_t Flags = PF_R;
292bbe38602SEugene Leviant   for (OutputSectionBase<ELFT> *Sec : Sections) {
293bbe38602SEugene Leviant     if (!(Sec->getFlags() & SHF_ALLOC))
294bbe38602SEugene Leviant       break;
295bbe38602SEugene Leviant 
296edebbdf1SRui Ueyama     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
297bbe38602SEugene Leviant     if (!PhdrIds.empty()) {
298bbe38602SEugene Leviant       // Assign headers specified by linker script
299bbe38602SEugene Leviant       for (size_t Id : PhdrIds) {
300edebbdf1SRui Ueyama         Ret[Id].add(Sec);
301865bf863SEugene Leviant         if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
302edebbdf1SRui Ueyama           Ret[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
303bbe38602SEugene Leviant       }
304bbe38602SEugene Leviant     } else {
305bbe38602SEugene Leviant       // If we have no load segment or flags've changed then we want new load
306bbe38602SEugene Leviant       // segment.
307bbe38602SEugene Leviant       uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
308bbe38602SEugene Leviant       if (Load == nullptr || Flags != NewFlags) {
309edebbdf1SRui Ueyama         Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
310bbe38602SEugene Leviant         Flags = NewFlags;
311bbe38602SEugene Leviant       }
31218f084ffSRui Ueyama       Load->add(Sec);
313bbe38602SEugene Leviant     }
314bbe38602SEugene Leviant   }
315edebbdf1SRui Ueyama   return Ret;
316bbe38602SEugene Leviant }
317bbe38602SEugene Leviant 
318bbe38602SEugene Leviant template <class ELFT>
31907320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
320f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
321f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
322f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
323f6c3ccefSGeorge Rimar         return Cmd->Filler;
324e2ee72b5SGeorge Rimar   return {};
325e2ee72b5SGeorge Rimar }
326e2ee72b5SGeorge Rimar 
327c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
328c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
329c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
330c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
331076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
332f510fa6bSRui Ueyama   int I = 0;
333f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
334076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
335076fe157SGeorge Rimar       if (Cmd->Name == Name)
336f510fa6bSRui Ueyama         return I;
337f510fa6bSRui Ueyama     ++I;
338f510fa6bSRui Ueyama   }
339f510fa6bSRui Ueyama   return INT_MAX;
34071b26e94SGeorge Rimar }
34171b26e94SGeorge Rimar 
34271b26e94SGeorge Rimar // A compartor to sort output sections. Returns -1 or 1 if
34371b26e94SGeorge Rimar // A or B are mentioned in linker script. Otherwise, returns 0.
34407320e40SRui Ueyama template <class ELFT>
34507320e40SRui Ueyama int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
346c3e2a4b0SRui Ueyama   int I = getSectionIndex(A);
347c3e2a4b0SRui Ueyama   int J = getSectionIndex(B);
348c3e2a4b0SRui Ueyama   if (I == INT_MAX && J == INT_MAX)
349717677afSRui Ueyama     return 0;
350717677afSRui Ueyama   return I < J ? -1 : 1;
351717677afSRui Ueyama }
352717677afSRui Ueyama 
353076fe157SGeorge Rimar template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
354a31c91b1SEugene Leviant   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
355a31c91b1SEugene Leviant     auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
356a31c91b1SEugene Leviant     if (!Cmd || Cmd->Name == ".")
357a31c91b1SEugene Leviant       continue;
358a31c91b1SEugene Leviant 
3598ab4108dSDavide Italiano     SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
360373a533aSDavide Italiano     // The semantic of PROVIDE is that of introducing a symbol only if
361373a533aSDavide Italiano     // it's not defined and there's at least a reference to it.
362373a533aSDavide Italiano     if ((!B && !Cmd->Provide) || (B && B->isUndefined()))
363a31c91b1SEugene Leviant       Symtab<ELFT>::X->addAbsolute(Cmd->Name,
364a31c91b1SEugene Leviant                                    Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
365a31c91b1SEugene Leviant     else
366a31c91b1SEugene Leviant       // Symbol already exists in symbol table. If it is provided
367a31c91b1SEugene Leviant       // then we can't override its value.
368a31c91b1SEugene Leviant       Cmd->Ignore = Cmd->Provide;
369a31c91b1SEugene Leviant   }
370eda81a1bSEugene Leviant }
371eda81a1bSEugene Leviant 
372bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
373bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
374bbe38602SEugene Leviant }
375bbe38602SEugene Leviant 
376bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
377bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
378bbe38602SEugene Leviant // PHDRS {} script block.
379bbe38602SEugene Leviant template <class ELFT>
380edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
381076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
382076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
383edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
38431d842f5SGeorge Rimar       continue;
38531d842f5SGeorge Rimar 
38629c5a2a9SRui Ueyama     std::vector<size_t> Ret;
38729c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
38829c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
38929c5a2a9SRui Ueyama     return Ret;
390bbe38602SEugene Leviant   }
39131d842f5SGeorge Rimar   return {};
39231d842f5SGeorge Rimar }
393bbe38602SEugene Leviant 
39429c5a2a9SRui Ueyama template <class ELFT>
39529c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
39629c5a2a9SRui Ueyama   size_t I = 0;
39729c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
39829c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
39929c5a2a9SRui Ueyama       return I;
40029c5a2a9SRui Ueyama     ++I;
40129c5a2a9SRui Ueyama   }
40229c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
40329c5a2a9SRui Ueyama   return 0;
40429c5a2a9SRui Ueyama }
40529c5a2a9SRui Ueyama 
40607320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
407c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
408c3794e58SGeorge Rimar 
409f7c5fbb1SRui Ueyama public:
41007320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
411f23b2320SGeorge Rimar 
4124a46539cSRui Ueyama   void run();
413f7c5fbb1SRui Ueyama 
414f7c5fbb1SRui Ueyama private:
41552a1509eSRui Ueyama   void addFile(StringRef Path);
41652a1509eSRui Ueyama 
417f7c5fbb1SRui Ueyama   void readAsNeeded();
41890c5099eSDenis Protivensky   void readEntry();
41983f406cfSGeorge Rimar   void readExtern();
420f7c5fbb1SRui Ueyama   void readGroup();
4210ed42b0cSDavide Italiano   void readKeep(OutputSectionCommand *Cmd);
42231aa1f83SRui Ueyama   void readInclude();
423c3794e58SGeorge Rimar   void readNothing() {}
424ee59282bSRui Ueyama   void readOutput();
4259159ce93SDavide Italiano   void readOutputArch();
426f7c5fbb1SRui Ueyama   void readOutputFormat();
427bbe38602SEugene Leviant   void readPhdrs();
42868a39a65SDavide Italiano   void readSearchDir();
4298e3b38abSDenis Protivensky   void readSections();
4308e3b38abSDenis Protivensky 
431113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
432eda81a1bSEugene Leviant   void readOutputSectionDescription(StringRef OutSec);
433bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
434bbe38602SEugene Leviant   unsigned readPhdrType();
435a31c91b1SEugene Leviant   void readProvide(bool Hidden);
436708019c4SRui Ueyama 
437708019c4SRui Ueyama   Expr readExpr();
438708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
439708019c4SRui Ueyama   Expr readPrimary();
440708019c4SRui Ueyama   Expr readTernary(Expr Cond);
441708019c4SRui Ueyama   Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
442f7c5fbb1SRui Ueyama 
443c3794e58SGeorge Rimar   const static StringMap<Handler> Cmd;
44407320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
44507320e40SRui Ueyama   StringSaver Saver = {ScriptConfig->Alloc};
44616b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
447f7c5fbb1SRui Ueyama };
448f7c5fbb1SRui Ueyama 
449e0df00b9SRafael Espindola const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
450c3794e58SGeorge Rimar     {"ENTRY", &ScriptParser::readEntry},
451c3794e58SGeorge Rimar     {"EXTERN", &ScriptParser::readExtern},
452c3794e58SGeorge Rimar     {"GROUP", &ScriptParser::readGroup},
453c3794e58SGeorge Rimar     {"INCLUDE", &ScriptParser::readInclude},
454c3794e58SGeorge Rimar     {"INPUT", &ScriptParser::readGroup},
455c3794e58SGeorge Rimar     {"OUTPUT", &ScriptParser::readOutput},
456c3794e58SGeorge Rimar     {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
457c3794e58SGeorge Rimar     {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
458bbe38602SEugene Leviant     {"PHDRS", &ScriptParser::readPhdrs},
459c3794e58SGeorge Rimar     {"SEARCH_DIR", &ScriptParser::readSearchDir},
460c3794e58SGeorge Rimar     {"SECTIONS", &ScriptParser::readSections},
461c3794e58SGeorge Rimar     {";", &ScriptParser::readNothing}};
462c3794e58SGeorge Rimar 
463717677afSRui Ueyama void ScriptParser::run() {
464f7c5fbb1SRui Ueyama   while (!atEOF()) {
465f7c5fbb1SRui Ueyama     StringRef Tok = next();
466c3794e58SGeorge Rimar     if (Handler Fn = Cmd.lookup(Tok))
467c3794e58SGeorge Rimar       (this->*Fn)();
468c3794e58SGeorge Rimar     else
4695761042dSGeorge Rimar       setError("unknown directive: " + Tok);
470f7c5fbb1SRui Ueyama   }
471f7c5fbb1SRui Ueyama }
472f7c5fbb1SRui Ueyama 
473717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
47416b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
47516b0cc9eSSimon Atanasyan     SmallString<128> Path;
47616b0cc9eSSimon Atanasyan     (Config->Sysroot + S).toStringRef(Path);
47716b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
47816b0cc9eSSimon Atanasyan       Driver->addFile(Saver.save(Path.str()));
47916b0cc9eSSimon Atanasyan       return;
48016b0cc9eSSimon Atanasyan     }
48116b0cc9eSSimon Atanasyan   }
48216b0cc9eSSimon Atanasyan 
483f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
48452a1509eSRui Ueyama     Driver->addFile(S);
48552a1509eSRui Ueyama   } else if (S.startswith("=")) {
48652a1509eSRui Ueyama     if (Config->Sysroot.empty())
48752a1509eSRui Ueyama       Driver->addFile(S.substr(1));
48852a1509eSRui Ueyama     else
48952a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
49052a1509eSRui Ueyama   } else if (S.startswith("-l")) {
49121eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
492a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
493a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
49452a1509eSRui Ueyama   } else {
49552a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
49652a1509eSRui Ueyama     if (Path.empty())
497777f9630SGeorge Rimar       setError("unable to find " + S);
498025d59b1SRui Ueyama     else
49952a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
50052a1509eSRui Ueyama   }
50152a1509eSRui Ueyama }
50252a1509eSRui Ueyama 
503717677afSRui Ueyama void ScriptParser::readAsNeeded() {
504f7c5fbb1SRui Ueyama   expect("(");
50535da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
50635da9b6eSRui Ueyama   Config->AsNeeded = true;
507025d59b1SRui Ueyama   while (!Error) {
508f7c5fbb1SRui Ueyama     StringRef Tok = next();
509f7c5fbb1SRui Ueyama     if (Tok == ")")
51035da9b6eSRui Ueyama       break;
51152a1509eSRui Ueyama     addFile(Tok);
512f7c5fbb1SRui Ueyama   }
51335da9b6eSRui Ueyama   Config->AsNeeded = Orig;
514f7c5fbb1SRui Ueyama }
515f7c5fbb1SRui Ueyama 
516717677afSRui Ueyama void ScriptParser::readEntry() {
51790c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
51890c5099eSDenis Protivensky   expect("(");
51990c5099eSDenis Protivensky   StringRef Tok = next();
52090c5099eSDenis Protivensky   if (Config->Entry.empty())
52190c5099eSDenis Protivensky     Config->Entry = Tok;
52290c5099eSDenis Protivensky   expect(")");
52390c5099eSDenis Protivensky }
52490c5099eSDenis Protivensky 
525717677afSRui Ueyama void ScriptParser::readExtern() {
52683f406cfSGeorge Rimar   expect("(");
527025d59b1SRui Ueyama   while (!Error) {
52883f406cfSGeorge Rimar     StringRef Tok = next();
52983f406cfSGeorge Rimar     if (Tok == ")")
53083f406cfSGeorge Rimar       return;
53183f406cfSGeorge Rimar     Config->Undefined.push_back(Tok);
53283f406cfSGeorge Rimar   }
53383f406cfSGeorge Rimar }
53483f406cfSGeorge Rimar 
535717677afSRui Ueyama void ScriptParser::readGroup() {
536f7c5fbb1SRui Ueyama   expect("(");
537025d59b1SRui Ueyama   while (!Error) {
538f7c5fbb1SRui Ueyama     StringRef Tok = next();
539f7c5fbb1SRui Ueyama     if (Tok == ")")
540f7c5fbb1SRui Ueyama       return;
541f7c5fbb1SRui Ueyama     if (Tok == "AS_NEEDED") {
542f7c5fbb1SRui Ueyama       readAsNeeded();
543f7c5fbb1SRui Ueyama       continue;
544f7c5fbb1SRui Ueyama     }
54552a1509eSRui Ueyama     addFile(Tok);
546f7c5fbb1SRui Ueyama   }
547f7c5fbb1SRui Ueyama }
548f7c5fbb1SRui Ueyama 
549717677afSRui Ueyama void ScriptParser::readInclude() {
55031aa1f83SRui Ueyama   StringRef Tok = next();
55131aa1f83SRui Ueyama   auto MBOrErr = MemoryBuffer::getFile(Tok);
552025d59b1SRui Ueyama   if (!MBOrErr) {
5535761042dSGeorge Rimar     setError("cannot open " + Tok);
554025d59b1SRui Ueyama     return;
555025d59b1SRui Ueyama   }
55631aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
557a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
558a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
55931aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
56031aa1f83SRui Ueyama }
56131aa1f83SRui Ueyama 
562717677afSRui Ueyama void ScriptParser::readOutput() {
563ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
564ee59282bSRui Ueyama   expect("(");
565ee59282bSRui Ueyama   StringRef Tok = next();
566ee59282bSRui Ueyama   if (Config->OutputFile.empty())
567ee59282bSRui Ueyama     Config->OutputFile = Tok;
568ee59282bSRui Ueyama   expect(")");
569ee59282bSRui Ueyama }
570ee59282bSRui Ueyama 
571717677afSRui Ueyama void ScriptParser::readOutputArch() {
5729159ce93SDavide Italiano   // Error checking only for now.
5739159ce93SDavide Italiano   expect("(");
5749159ce93SDavide Italiano   next();
5759159ce93SDavide Italiano   expect(")");
5769159ce93SDavide Italiano }
5779159ce93SDavide Italiano 
578717677afSRui Ueyama void ScriptParser::readOutputFormat() {
579f7c5fbb1SRui Ueyama   // Error checking only for now.
580f7c5fbb1SRui Ueyama   expect("(");
581f7c5fbb1SRui Ueyama   next();
5826836c618SDavide Italiano   StringRef Tok = next();
5836836c618SDavide Italiano   if (Tok == ")")
5846836c618SDavide Italiano    return;
585025d59b1SRui Ueyama   if (Tok != ",") {
5865761042dSGeorge Rimar     setError("unexpected token: " + Tok);
587025d59b1SRui Ueyama     return;
588025d59b1SRui Ueyama   }
5896836c618SDavide Italiano   next();
5906836c618SDavide Italiano   expect(",");
5916836c618SDavide Italiano   next();
592f7c5fbb1SRui Ueyama   expect(")");
593f7c5fbb1SRui Ueyama }
594f7c5fbb1SRui Ueyama 
595bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
596bbe38602SEugene Leviant   expect("{");
597bbe38602SEugene Leviant   while (!Error && !skip("}")) {
598bbe38602SEugene Leviant     StringRef Tok = next();
599865bf863SEugene Leviant     Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
600bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
601bbe38602SEugene Leviant 
602bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
603bbe38602SEugene Leviant     do {
604bbe38602SEugene Leviant       Tok = next();
605bbe38602SEugene Leviant       if (Tok == ";")
606bbe38602SEugene Leviant         break;
607bbe38602SEugene Leviant       if (Tok == "FILEHDR")
608bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
609bbe38602SEugene Leviant       else if (Tok == "PHDRS")
610bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
611865bf863SEugene Leviant       else if (Tok == "FLAGS") {
612865bf863SEugene Leviant         expect("(");
613865bf863SEugene Leviant         next().getAsInteger(0, PhdrCmd.Flags);
614865bf863SEugene Leviant         expect(")");
615865bf863SEugene Leviant       } else
616bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
617bbe38602SEugene Leviant     } while (!Error);
618bbe38602SEugene Leviant   }
619bbe38602SEugene Leviant }
620bbe38602SEugene Leviant 
621717677afSRui Ueyama void ScriptParser::readSearchDir() {
62268a39a65SDavide Italiano   expect("(");
62306501920SRafael Espindola   Config->SearchPaths.push_back(next());
62468a39a65SDavide Italiano   expect(")");
62568a39a65SDavide Italiano }
62668a39a65SDavide Italiano 
627717677afSRui Ueyama void ScriptParser::readSections() {
62807320e40SRui Ueyama   Opt.DoLayout = true;
6298e3b38abSDenis Protivensky   expect("{");
630652852c5SGeorge Rimar   while (!Error && !skip("}")) {
631113cdec9SRui Ueyama     StringRef Tok = next();
632113cdec9SRui Ueyama     if (peek() == "=") {
633113cdec9SRui Ueyama       readAssignment(Tok);
634113cdec9SRui Ueyama       expect(";");
635113cdec9SRui Ueyama     } else if (Tok == "PROVIDE") {
636a31c91b1SEugene Leviant       readProvide(false);
637708019c4SRui Ueyama     } else if (Tok == "PROVIDE_HIDDEN") {
638a31c91b1SEugene Leviant       readProvide(true);
639708019c4SRui Ueyama     } else {
640eda81a1bSEugene Leviant       readOutputSectionDescription(Tok);
6418e3b38abSDenis Protivensky     }
642652852c5SGeorge Rimar   }
643708019c4SRui Ueyama }
6448e3b38abSDenis Protivensky 
645708019c4SRui Ueyama static int precedence(StringRef Op) {
646708019c4SRui Ueyama   return StringSwitch<int>(Op)
647708019c4SRui Ueyama       .Case("*", 4)
648708019c4SRui Ueyama       .Case("/", 4)
649708019c4SRui Ueyama       .Case("+", 3)
650708019c4SRui Ueyama       .Case("-", 3)
651708019c4SRui Ueyama       .Case("<", 2)
652708019c4SRui Ueyama       .Case(">", 2)
653708019c4SRui Ueyama       .Case(">=", 2)
654708019c4SRui Ueyama       .Case("<=", 2)
655708019c4SRui Ueyama       .Case("==", 2)
656708019c4SRui Ueyama       .Case("!=", 2)
657708019c4SRui Ueyama       .Case("&", 1)
658708019c4SRui Ueyama       .Default(-1);
659708019c4SRui Ueyama }
660708019c4SRui Ueyama 
6610ed42b0cSDavide Italiano void ScriptParser::readKeep(OutputSectionCommand *Cmd) {
6620ed42b0cSDavide Italiano   expect("(");
6630ed42b0cSDavide Italiano   expect("*");
6640ed42b0cSDavide Italiano   expect("(");
6650ed42b0cSDavide Italiano   auto *InCmd = new InputSectionDescription();
6660ed42b0cSDavide Italiano   Cmd->Commands.emplace_back(InCmd);
6670ed42b0cSDavide Italiano   while (!Error && !skip(")")) {
6680ed42b0cSDavide Italiano     Opt.KeptSections.push_back(peek());
6690ed42b0cSDavide Italiano     InCmd->Patterns.push_back(next());
6700ed42b0cSDavide Italiano   }
6710ed42b0cSDavide Italiano   expect(")");
6720ed42b0cSDavide Italiano }
6730ed42b0cSDavide Italiano 
674eda81a1bSEugene Leviant void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
675076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
676076fe157SGeorge Rimar   Opt.Commands.emplace_back(Cmd);
67758e5c4dcSGeorge Rimar 
67858e5c4dcSGeorge Rimar   // Read an address expression.
67958e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
68058e5c4dcSGeorge Rimar   if (peek() != ":")
68158e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
68258e5c4dcSGeorge Rimar 
6838e3b38abSDenis Protivensky   expect(":");
684246f681eSDavide Italiano 
685246f681eSDavide Italiano   // Parse constraints.
686246f681eSDavide Italiano   if (skip("ONLY_IF_RO"))
687efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
688246f681eSDavide Italiano   if (skip("ONLY_IF_RW"))
689efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
6908e3b38abSDenis Protivensky   expect("{");
6918ec77e64SRui Ueyama 
692025d59b1SRui Ueyama   while (!Error && !skip("}")) {
693481c2ce6SGeorge Rimar     StringRef Tok = next();
694481c2ce6SGeorge Rimar     if (Tok == "*") {
695eea3114fSGeorge Rimar       auto *InCmd = new InputSectionDescription();
696eea3114fSGeorge Rimar       Cmd->Commands.emplace_back(InCmd);
6978ec77e64SRui Ueyama       expect("(");
6988ec77e64SRui Ueyama       while (!Error && !skip(")"))
699eea3114fSGeorge Rimar         InCmd->Patterns.push_back(next());
700481c2ce6SGeorge Rimar     } else if (Tok == "KEEP") {
7010ed42b0cSDavide Italiano       readKeep(Cmd);
702054a6796SDavide Italiano     } else if (Tok == "PROVIDE") {
703054a6796SDavide Italiano       readProvide(false);
704054a6796SDavide Italiano     } else if (Tok == "PROVIDE_HIDDEN") {
705054a6796SDavide Italiano       readProvide(true);
706481c2ce6SGeorge Rimar     } else {
707777f9630SGeorge Rimar       setError("unknown command " + Tok);
708481c2ce6SGeorge Rimar     }
7098e3b38abSDenis Protivensky   }
710076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
7118ec77e64SRui Ueyama 
712e2ee72b5SGeorge Rimar   StringRef Tok = peek();
713e2ee72b5SGeorge Rimar   if (Tok.startswith("=")) {
714e2ee72b5SGeorge Rimar     if (!Tok.startswith("=0x")) {
7153ed2f069SRui Ueyama       setError("filler should be a hexadecimal value");
716e2ee72b5SGeorge Rimar       return;
717e2ee72b5SGeorge Rimar     }
7183e808976SRui Ueyama     Tok = Tok.substr(3);
719f6c3ccefSGeorge Rimar     Cmd->Filler = parseHex(Tok);
720e2ee72b5SGeorge Rimar     next();
721e2ee72b5SGeorge Rimar   }
7228e3b38abSDenis Protivensky }
7238e3b38abSDenis Protivensky 
724a31c91b1SEugene Leviant void ScriptParser::readProvide(bool Hidden) {
725a31c91b1SEugene Leviant   expect("(");
726113cdec9SRui Ueyama   if (SymbolAssignment *Assignment = readAssignment(next())) {
727a31c91b1SEugene Leviant     Assignment->Provide = true;
728a31c91b1SEugene Leviant     Assignment->Hidden = Hidden;
729a31c91b1SEugene Leviant   }
730a31c91b1SEugene Leviant   expect(")");
731a31c91b1SEugene Leviant   expect(";");
732eda81a1bSEugene Leviant }
733eda81a1bSEugene Leviant 
734113cdec9SRui Ueyama SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
735a31c91b1SEugene Leviant   expect("=");
736708019c4SRui Ueyama   Expr E = readExpr();
737113cdec9SRui Ueyama   auto *Cmd = new SymbolAssignment(Name, E);
738113cdec9SRui Ueyama   Opt.Commands.emplace_back(Cmd);
739113cdec9SRui Ueyama   return Cmd;
740a31c91b1SEugene Leviant }
741a31c91b1SEugene Leviant 
742708019c4SRui Ueyama // This is an operator-precedence parser to parse a linker
743708019c4SRui Ueyama // script expression.
744708019c4SRui Ueyama Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
745a31c91b1SEugene Leviant 
746708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
747708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
748708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
749708019c4SRui Ueyama   while (!atEOF() && !Error) {
750708019c4SRui Ueyama     // Read an operator and an expression.
751708019c4SRui Ueyama     StringRef Op1 = peek();
752708019c4SRui Ueyama     if (Op1 == "?")
753708019c4SRui Ueyama       return readTernary(Lhs);
754708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
755a31c91b1SEugene Leviant       break;
756a31c91b1SEugene Leviant     next();
757708019c4SRui Ueyama     Expr Rhs = readPrimary();
758708019c4SRui Ueyama 
759708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
760708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
761708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
762708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
763708019c4SRui Ueyama     while (!atEOF()) {
764708019c4SRui Ueyama       StringRef Op2 = peek();
765708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
766eda81a1bSEugene Leviant         break;
767708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
768eda81a1bSEugene Leviant     }
769708019c4SRui Ueyama 
770708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
771708019c4SRui Ueyama   }
772708019c4SRui Ueyama   return Lhs;
773708019c4SRui Ueyama }
774708019c4SRui Ueyama 
775708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
776708019c4SRui Ueyama   if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
777708019c4SRui Ueyama     return Target->PageSize;
778708019c4SRui Ueyama   error("unknown constant: " + S);
779708019c4SRui Ueyama   return 0;
780708019c4SRui Ueyama }
781708019c4SRui Ueyama 
782708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
783708019c4SRui Ueyama   StringRef Tok = next();
784708019c4SRui Ueyama 
785708019c4SRui Ueyama   if (Tok == ".")
786708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
787708019c4SRui Ueyama 
788708019c4SRui Ueyama   if (Tok == "(") {
789708019c4SRui Ueyama     Expr E = readExpr();
790708019c4SRui Ueyama     expect(")");
791708019c4SRui Ueyama     return E;
792708019c4SRui Ueyama   }
793708019c4SRui Ueyama 
794708019c4SRui Ueyama   // Built-in functions are parsed here.
795708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
796708019c4SRui Ueyama   if (Tok == "ALIGN") {
797708019c4SRui Ueyama     expect("(");
798708019c4SRui Ueyama     Expr E = readExpr();
799708019c4SRui Ueyama     expect(")");
800708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
801708019c4SRui Ueyama   }
802708019c4SRui Ueyama   if (Tok == "CONSTANT") {
803708019c4SRui Ueyama     expect("(");
804708019c4SRui Ueyama     StringRef Tok = next();
805708019c4SRui Ueyama     expect(")");
806708019c4SRui Ueyama     return [=](uint64_t Dot) { return getConstant(Tok); };
807708019c4SRui Ueyama   }
808708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
809708019c4SRui Ueyama     expect("(");
810708019c4SRui Ueyama     Expr E = readExpr();
811708019c4SRui Ueyama     expect(",");
812708019c4SRui Ueyama     readExpr();
813708019c4SRui Ueyama     expect(")");
8144509a4f5SGeorge Rimar     return [=](uint64_t Dot) -> uint64_t { return alignTo(Dot, E(Dot)); };
815708019c4SRui Ueyama   }
816708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
817708019c4SRui Ueyama     expect("(");
818708019c4SRui Ueyama     expect(".");
819708019c4SRui Ueyama     expect(")");
820708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
821708019c4SRui Ueyama   }
822*276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
823*276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
824*276b4e64SGeorge Rimar   // the next page boundary for simplicity.
825*276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
826*276b4e64SGeorge Rimar     expect("(");
827*276b4e64SGeorge Rimar     next();
828*276b4e64SGeorge Rimar     expect(",");
829*276b4e64SGeorge Rimar     readExpr();
830*276b4e64SGeorge Rimar     expect(")");
831*276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
832*276b4e64SGeorge Rimar   }
833708019c4SRui Ueyama 
834708019c4SRui Ueyama   // Parse a number literal
835708019c4SRui Ueyama   uint64_t V = 0;
836708019c4SRui Ueyama   if (Tok.getAsInteger(0, V))
837708019c4SRui Ueyama     setError("malformed number: " + Tok);
838708019c4SRui Ueyama   return [=](uint64_t Dot) { return V; };
839708019c4SRui Ueyama }
840708019c4SRui Ueyama 
841708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
842708019c4SRui Ueyama   next();
843708019c4SRui Ueyama   Expr L = readExpr();
844708019c4SRui Ueyama   expect(":");
845708019c4SRui Ueyama   Expr R = readExpr();
846708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
847708019c4SRui Ueyama }
848708019c4SRui Ueyama 
849708019c4SRui Ueyama Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
850708019c4SRui Ueyama   if (Op == "*")
851708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
852708019c4SRui Ueyama   if (Op == "/") {
853708019c4SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
854708019c4SRui Ueyama       uint64_t RHS = R(Dot);
855708019c4SRui Ueyama       if (RHS == 0) {
856708019c4SRui Ueyama         error("division by zero");
857708019c4SRui Ueyama         return 0;
858708019c4SRui Ueyama       }
859708019c4SRui Ueyama       return L(Dot) / RHS;
860708019c4SRui Ueyama     };
861708019c4SRui Ueyama   }
862708019c4SRui Ueyama   if (Op == "+")
863708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
864708019c4SRui Ueyama   if (Op == "-")
865708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
866708019c4SRui Ueyama   if (Op == "<")
867708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
868708019c4SRui Ueyama   if (Op == ">")
869708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
870708019c4SRui Ueyama   if (Op == ">=")
871708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
872708019c4SRui Ueyama   if (Op == "<=")
873708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
874708019c4SRui Ueyama   if (Op == "==")
875708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
876708019c4SRui Ueyama   if (Op == "!=")
877708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
878708019c4SRui Ueyama   if (Op == "&")
879708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
880708019c4SRui Ueyama   llvm_unreachable("invalid operator");
881eda81a1bSEugene Leviant }
882eda81a1bSEugene Leviant 
883bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
884bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
885bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
886bbe38602SEugene Leviant     StringRef Tok = next();
887bbe38602SEugene Leviant     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
888bbe38602SEugene Leviant     if (Tok.empty()) {
889bbe38602SEugene Leviant       setError("section header name is empty");
890bbe38602SEugene Leviant       break;
891bbe38602SEugene Leviant     }
892bbe38602SEugene Leviant     Phdrs.push_back(Tok);
893bbe38602SEugene Leviant   }
894bbe38602SEugene Leviant   return Phdrs;
895bbe38602SEugene Leviant }
896bbe38602SEugene Leviant 
897bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
898bbe38602SEugene Leviant   StringRef Tok = next();
899b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
900b0f6c590SRui Ueyama       .Case("PT_NULL", PT_NULL)
901b0f6c590SRui Ueyama       .Case("PT_LOAD", PT_LOAD)
902b0f6c590SRui Ueyama       .Case("PT_DYNAMIC", PT_DYNAMIC)
903b0f6c590SRui Ueyama       .Case("PT_INTERP", PT_INTERP)
904b0f6c590SRui Ueyama       .Case("PT_NOTE", PT_NOTE)
905b0f6c590SRui Ueyama       .Case("PT_SHLIB", PT_SHLIB)
906b0f6c590SRui Ueyama       .Case("PT_PHDR", PT_PHDR)
907b0f6c590SRui Ueyama       .Case("PT_TLS", PT_TLS)
908b0f6c590SRui Ueyama       .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
909b0f6c590SRui Ueyama       .Case("PT_GNU_STACK", PT_GNU_STACK)
910b0f6c590SRui Ueyama       .Case("PT_GNU_RELRO", PT_GNU_RELRO)
911b0f6c590SRui Ueyama       .Default(-1);
912bbe38602SEugene Leviant 
913b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
914b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
915b0f6c590SRui Ueyama     return PT_NULL;
916b0f6c590SRui Ueyama   }
917b0f6c590SRui Ueyama   return Ret;
918bbe38602SEugene Leviant }
919bbe38602SEugene Leviant 
92016b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
92116b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
92216b0cc9eSSimon Atanasyan     return false;
92316b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
92416b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
92516b0cc9eSSimon Atanasyan       return true;
92616b0cc9eSSimon Atanasyan   return false;
92716b0cc9eSSimon Atanasyan }
92816b0cc9eSSimon Atanasyan 
92907320e40SRui Ueyama // Entry point.
93007320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
93116b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
93207320e40SRui Ueyama   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
933f7c5fbb1SRui Ueyama }
9341ebc8ed7SRui Ueyama 
93507320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
93607320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
93707320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
93807320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
939