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 
77*eaee2af5SGeorge 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 
120652852c5SGeorge Rimar template <class ELFT>
121a7f7884dSRui Ueyama std::vector<OutputSectionBase<ELFT> *>
122ad10c3d8SRui Ueyama LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
1236b274810SRui Ueyama   std::vector<OutputSectionBase<ELFT> *> Ret;
124a7f7884dSRui Ueyama 
125e63d81bdSEugene Leviant   // Add input section to output section. If there is no output section yet,
126e63d81bdSEugene Leviant   // then create it and add to output section list.
1276b274810SRui Ueyama   auto Add = [&](InputSectionBase<ELFT> *C, StringRef Name) {
128e63d81bdSEugene Leviant     OutputSectionBase<ELFT> *Sec;
129e63d81bdSEugene Leviant     bool IsNew;
130e63d81bdSEugene Leviant     std::tie(Sec, IsNew) = Factory.create(C, Name);
131e63d81bdSEugene Leviant     if (IsNew)
1326b274810SRui Ueyama       Ret.push_back(Sec);
133e63d81bdSEugene Leviant     Sec->addSection(C);
134e63d81bdSEugene Leviant   };
135e63d81bdSEugene Leviant 
1366b274810SRui Ueyama   for (auto &P : getSectionMap()) {
1376b274810SRui Ueyama     StringRef OutputName = P.first;
138e7282797SDavide Italiano     const InputSectionDescription *I = P.second;
139ad10c3d8SRui Ueyama     for (InputSectionBase<ELFT> *S : getInputSections(I)) {
1406b274810SRui Ueyama       if (OutputName == "/DISCARD/") {
141eea3114fSGeorge Rimar         S->Live = false;
1426b274810SRui Ueyama         reportDiscarded(S);
1436b274810SRui Ueyama         continue;
144eea3114fSGeorge Rimar       }
1456b274810SRui Ueyama       Add(S, OutputName);
146eea3114fSGeorge Rimar     }
147eea3114fSGeorge Rimar   }
148e63d81bdSEugene Leviant 
149e63d81bdSEugene Leviant   // Add all other input sections, which are not listed in script.
1506b274810SRui Ueyama   for (const std::unique_ptr<ObjectFile<ELFT>> &F :
1516b274810SRui Ueyama        Symtab<ELFT>::X->getObjectFiles())
1526b274810SRui Ueyama     for (InputSectionBase<ELFT> *S : F->getSections())
1536b274810SRui Ueyama       if (!isDiscarded(S) && !S->OutSec)
1546b274810SRui Ueyama         Add(S, getOutputSectionName(S));
155e63d81bdSEugene Leviant 
1563c291e1aSRui Ueyama   // Remove from the output all the sections which did not meet
1573c291e1aSRui Ueyama   // the optional constraints.
1586b274810SRui Ueyama   return filter(Ret);
1593c291e1aSRui Ueyama }
1603c291e1aSRui Ueyama 
1613c291e1aSRui Ueyama // Process ONLY_IF_RO and ONLY_IF_RW.
1623c291e1aSRui Ueyama template <class ELFT>
1633c291e1aSRui Ueyama std::vector<OutputSectionBase<ELFT> *>
1643c291e1aSRui Ueyama LinkerScript<ELFT>::filter(std::vector<OutputSectionBase<ELFT> *> &Sections) {
1653c291e1aSRui Ueyama   // In this loop, we remove output sections if they don't satisfy
1663c291e1aSRui Ueyama   // requested properties.
1673c291e1aSRui Ueyama   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
1683c291e1aSRui Ueyama     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
1693c291e1aSRui Ueyama     if (!Cmd || Cmd->Name == "/DISCARD/")
1703c291e1aSRui Ueyama       continue;
1713c291e1aSRui Ueyama 
172bfc4a4b7SGeorge Rimar     if (Cmd->Constraint == ConstraintKind::NoConstraint)
1733c291e1aSRui Ueyama       continue;
174bfc4a4b7SGeorge Rimar 
175bfc4a4b7SGeorge Rimar     auto It = llvm::find_if(Sections, [&](OutputSectionBase<ELFT> *S) {
176bfc4a4b7SGeorge Rimar       return S->getName() == Cmd->Name;
177bfc4a4b7SGeorge Rimar     });
178bfc4a4b7SGeorge Rimar     if (It == Sections.end())
179bfc4a4b7SGeorge Rimar       continue;
1803c291e1aSRui Ueyama 
1813c291e1aSRui Ueyama     OutputSectionBase<ELFT> *Sec = *It;
1823c291e1aSRui Ueyama     bool Writable = (Sec->getFlags() & SHF_WRITE);
1833c291e1aSRui Ueyama     bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
1843c291e1aSRui Ueyama     bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
1853c291e1aSRui Ueyama 
186ed942713SRui Ueyama     if ((RO && Writable) || (RW && !Writable))
1873c291e1aSRui Ueyama       Sections.erase(It);
1883c291e1aSRui Ueyama   }
1893c291e1aSRui Ueyama   return Sections;
190e63d81bdSEugene Leviant }
191e63d81bdSEugene Leviant 
192e63d81bdSEugene Leviant template <class ELFT>
19307320e40SRui Ueyama void LinkerScript<ELFT>::assignAddresses(
194dbbd8b15SGeorge Rimar     ArrayRef<OutputSectionBase<ELFT> *> Sections) {
195652852c5SGeorge Rimar   // Orphan sections are sections present in the input files which
1967c18c28cSRui Ueyama   // are not explicitly placed into the output file by the linker script.
1977c18c28cSRui Ueyama   // We place orphan sections at end of file.
1987c18c28cSRui Ueyama   // Other linkers places them using some heuristics as described in
199652852c5SGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
2007c18c28cSRui Ueyama   for (OutputSectionBase<ELFT> *Sec : Sections) {
201652852c5SGeorge Rimar     StringRef Name = Sec->getName();
202c3e2a4b0SRui Ueyama     if (getSectionIndex(Name) == INT_MAX)
203076fe157SGeorge Rimar       Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
204652852c5SGeorge Rimar   }
205652852c5SGeorge Rimar 
2067c18c28cSRui Ueyama   // Assign addresses as instructed by linker script SECTIONS sub-commands.
207c998a8c0SRui Ueyama   Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
208467c4d55SEugene Leviant   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
209652852c5SGeorge Rimar   uintX_t ThreadBssOffset = 0;
210652852c5SGeorge Rimar 
211076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
212076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
2138d083e6aSRui Ueyama       if (Cmd->Name == ".") {
2148d083e6aSRui Ueyama         Dot = Cmd->Expression(Dot);
2158d083e6aSRui Ueyama       } else if (Cmd->Sym) {
2168d083e6aSRui Ueyama         cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
2178d083e6aSRui Ueyama       }
21805ef4cffSRui Ueyama       continue;
219652852c5SGeorge Rimar     }
220652852c5SGeorge Rimar 
221fb8978fcSDima Stepanov     // Find all the sections with required name. There can be more than
2226ad330acSGeorge Rimar     // one section with such name, if the alignment, flags or type
223fb8978fcSDima Stepanov     // attribute differs.
224076fe157SGeorge Rimar     auto *Cmd = cast<OutputSectionCommand>(Base.get());
225fb8978fcSDima Stepanov     for (OutputSectionBase<ELFT> *Sec : Sections) {
226076fe157SGeorge Rimar       if (Sec->getName() != Cmd->Name)
227652852c5SGeorge Rimar         continue;
228652852c5SGeorge Rimar 
22958e5c4dcSGeorge Rimar       if (Cmd->AddrExpr)
23058e5c4dcSGeorge Rimar         Dot = Cmd->AddrExpr(Dot);
23158e5c4dcSGeorge Rimar 
232630c6179SGeorge Rimar       if (Cmd->AlignExpr)
233630c6179SGeorge Rimar         Sec->updateAlignment(Cmd->AlignExpr(Dot));
234630c6179SGeorge Rimar 
235652852c5SGeorge Rimar       if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
236c998a8c0SRui Ueyama         uintX_t TVA = Dot + ThreadBssOffset;
237424b4081SRui Ueyama         TVA = alignTo(TVA, Sec->getAlignment());
238652852c5SGeorge Rimar         Sec->setVA(TVA);
239c998a8c0SRui Ueyama         ThreadBssOffset = TVA - Dot + Sec->getSize();
240652852c5SGeorge Rimar         continue;
241652852c5SGeorge Rimar       }
242652852c5SGeorge Rimar 
243652852c5SGeorge Rimar       if (Sec->getFlags() & SHF_ALLOC) {
244424b4081SRui Ueyama         Dot = alignTo(Dot, Sec->getAlignment());
245c998a8c0SRui Ueyama         Sec->setVA(Dot);
246467c4d55SEugene Leviant         MinVA = std::min(MinVA, Dot);
247c998a8c0SRui Ueyama         Dot += Sec->getSize();
248652852c5SGeorge Rimar         continue;
249652852c5SGeorge Rimar       }
250652852c5SGeorge Rimar     }
251652852c5SGeorge Rimar   }
252467c4d55SEugene Leviant 
25364c32d6fSRafael Espindola   // ELF and Program headers need to be right before the first section in
254b91e7118SGeorge Rimar   // memory. Set their addresses accordingly.
255467c4d55SEugene Leviant   MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
256467c4d55SEugene Leviant                         Out<ELFT>::ProgramHeaders->getSize(),
257467c4d55SEugene Leviant                     Target->PageSize);
258467c4d55SEugene Leviant   Out<ELFT>::ElfHeader->setVA(MinVA);
259467c4d55SEugene Leviant   Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
260fb8978fcSDima Stepanov }
261652852c5SGeorge Rimar 
26207320e40SRui Ueyama template <class ELFT>
26374df5c7eSRafael Espindola std::vector<PhdrEntry<ELFT>>
264bbe38602SEugene Leviant LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
265edebbdf1SRui Ueyama   std::vector<PhdrEntry<ELFT>> Ret;
266bbe38602SEugene Leviant 
267bbe38602SEugene Leviant   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
268edebbdf1SRui Ueyama     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
269edebbdf1SRui Ueyama     PhdrEntry<ELFT> &Phdr = Ret.back();
270bbe38602SEugene Leviant 
271bbe38602SEugene Leviant     if (Cmd.HasFilehdr)
272adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ElfHeader);
273bbe38602SEugene Leviant     if (Cmd.HasPhdrs)
274adca245fSRui Ueyama       Phdr.add(Out<ELFT>::ProgramHeaders);
275bbe38602SEugene Leviant 
276bbe38602SEugene Leviant     switch (Cmd.Type) {
277bbe38602SEugene Leviant     case PT_INTERP:
278fd03cfd2SRui Ueyama       if (Out<ELFT>::Interp)
279adca245fSRui Ueyama         Phdr.add(Out<ELFT>::Interp);
280bbe38602SEugene Leviant       break;
281bbe38602SEugene Leviant     case PT_DYNAMIC:
282bbe38602SEugene Leviant       if (isOutputDynamic<ELFT>()) {
2830b113671SRafael Espindola         Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
284adca245fSRui Ueyama         Phdr.add(Out<ELFT>::Dynamic);
285bbe38602SEugene Leviant       }
286bbe38602SEugene Leviant       break;
287bbe38602SEugene Leviant     case PT_GNU_EH_FRAME:
288bbe38602SEugene Leviant       if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
2890b113671SRafael Espindola         Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
290adca245fSRui Ueyama         Phdr.add(Out<ELFT>::EhFrameHdr);
291bbe38602SEugene Leviant       }
292bbe38602SEugene Leviant       break;
293bbe38602SEugene Leviant     }
294bbe38602SEugene Leviant   }
295bbe38602SEugene Leviant 
296edebbdf1SRui Ueyama   PhdrEntry<ELFT> *Load = nullptr;
297edebbdf1SRui Ueyama   uintX_t Flags = PF_R;
298bbe38602SEugene Leviant   for (OutputSectionBase<ELFT> *Sec : Sections) {
299bbe38602SEugene Leviant     if (!(Sec->getFlags() & SHF_ALLOC))
300bbe38602SEugene Leviant       break;
301bbe38602SEugene Leviant 
302edebbdf1SRui Ueyama     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
303bbe38602SEugene Leviant     if (!PhdrIds.empty()) {
304bbe38602SEugene Leviant       // Assign headers specified by linker script
305bbe38602SEugene Leviant       for (size_t Id : PhdrIds) {
306edebbdf1SRui Ueyama         Ret[Id].add(Sec);
307865bf863SEugene Leviant         if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
3080b113671SRafael Espindola           Ret[Id].H.p_flags |= Sec->getPhdrFlags();
309bbe38602SEugene Leviant       }
310bbe38602SEugene Leviant     } else {
311bbe38602SEugene Leviant       // If we have no load segment or flags've changed then we want new load
312bbe38602SEugene Leviant       // segment.
3130b113671SRafael Espindola       uintX_t NewFlags = Sec->getPhdrFlags();
314bbe38602SEugene Leviant       if (Load == nullptr || Flags != NewFlags) {
315edebbdf1SRui Ueyama         Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
316bbe38602SEugene Leviant         Flags = NewFlags;
317bbe38602SEugene Leviant       }
31818f084ffSRui Ueyama       Load->add(Sec);
319bbe38602SEugene Leviant     }
320bbe38602SEugene Leviant   }
321edebbdf1SRui Ueyama   return Ret;
322bbe38602SEugene Leviant }
323bbe38602SEugene Leviant 
324bbe38602SEugene Leviant template <class ELFT>
32507320e40SRui Ueyama ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
326f6c3ccefSGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
327f6c3ccefSGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
328f6c3ccefSGeorge Rimar       if (Cmd->Name == Name)
329f6c3ccefSGeorge Rimar         return Cmd->Filler;
330e2ee72b5SGeorge Rimar   return {};
331e2ee72b5SGeorge Rimar }
332e2ee72b5SGeorge Rimar 
333c3e2a4b0SRui Ueyama // Returns the index of the given section name in linker script
334c3e2a4b0SRui Ueyama // SECTIONS commands. Sections are laid out as the same order as they
335c3e2a4b0SRui Ueyama // were in the script. If a given name did not appear in the script,
336c3e2a4b0SRui Ueyama // it returns INT_MAX, so that it will be laid out at end of file.
337076fe157SGeorge Rimar template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
338f510fa6bSRui Ueyama   int I = 0;
339f510fa6bSRui Ueyama   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
340076fe157SGeorge Rimar     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
341076fe157SGeorge Rimar       if (Cmd->Name == Name)
342f510fa6bSRui Ueyama         return I;
343f510fa6bSRui Ueyama     ++I;
344f510fa6bSRui Ueyama   }
345f510fa6bSRui Ueyama   return INT_MAX;
34671b26e94SGeorge Rimar }
34771b26e94SGeorge Rimar 
34871b26e94SGeorge Rimar // A compartor to sort output sections. Returns -1 or 1 if
34971b26e94SGeorge Rimar // A or B are mentioned in linker script. Otherwise, returns 0.
35007320e40SRui Ueyama template <class ELFT>
35107320e40SRui Ueyama int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
352c3e2a4b0SRui Ueyama   int I = getSectionIndex(A);
353c3e2a4b0SRui Ueyama   int J = getSectionIndex(B);
354c3e2a4b0SRui Ueyama   if (I == INT_MAX && J == INT_MAX)
355717677afSRui Ueyama     return 0;
356717677afSRui Ueyama   return I < J ? -1 : 1;
357717677afSRui Ueyama }
358717677afSRui Ueyama 
3598d083e6aSRui Ueyama // Add symbols defined by linker scripts.
360076fe157SGeorge Rimar template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
361a31c91b1SEugene Leviant   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
362a31c91b1SEugene Leviant     auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
363a31c91b1SEugene Leviant     if (!Cmd || Cmd->Name == ".")
364a31c91b1SEugene Leviant       continue;
365a31c91b1SEugene Leviant 
3668d083e6aSRui Ueyama     // If a symbol was in PROVIDE(), define it only when it is an
3678d083e6aSRui Ueyama     // undefined symbol.
3688ab4108dSDavide Italiano     SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
3698d083e6aSRui Ueyama     if (Cmd->Provide && !(B && B->isUndefined()))
3708d083e6aSRui Ueyama       continue;
3718d083e6aSRui Ueyama 
3728d083e6aSRui Ueyama     // Define an absolute symbol. The symbol value will be assigned later.
3738d083e6aSRui Ueyama     // (At this point, we don't know the final address yet.)
3748d083e6aSRui Ueyama     Symbol *Sym = Symtab<ELFT>::X->addUndefined(Cmd->Name);
3758d083e6aSRui Ueyama     replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, STV_DEFAULT);
3768d083e6aSRui Ueyama     Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
3778d083e6aSRui Ueyama     Cmd->Sym = Sym->body();
378a31c91b1SEugene Leviant   }
379eda81a1bSEugene Leviant }
380eda81a1bSEugene Leviant 
381bbe38602SEugene Leviant template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
382bbe38602SEugene Leviant   return !Opt.PhdrsCommands.empty();
383bbe38602SEugene Leviant }
384bbe38602SEugene Leviant 
385bbe38602SEugene Leviant // Returns indices of ELF headers containing specific section, identified
386bbe38602SEugene Leviant // by Name. Each index is a zero based number of ELF header listed within
387bbe38602SEugene Leviant // PHDRS {} script block.
388bbe38602SEugene Leviant template <class ELFT>
389edebbdf1SRui Ueyama std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
390076fe157SGeorge Rimar   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
391076fe157SGeorge Rimar     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
392edebbdf1SRui Ueyama     if (!Cmd || Cmd->Name != SectionName)
39331d842f5SGeorge Rimar       continue;
39431d842f5SGeorge Rimar 
39529c5a2a9SRui Ueyama     std::vector<size_t> Ret;
39629c5a2a9SRui Ueyama     for (StringRef PhdrName : Cmd->Phdrs)
39729c5a2a9SRui Ueyama       Ret.push_back(getPhdrIndex(PhdrName));
39829c5a2a9SRui Ueyama     return Ret;
399bbe38602SEugene Leviant   }
40031d842f5SGeorge Rimar   return {};
40131d842f5SGeorge Rimar }
402bbe38602SEugene Leviant 
40329c5a2a9SRui Ueyama template <class ELFT>
40429c5a2a9SRui Ueyama size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
40529c5a2a9SRui Ueyama   size_t I = 0;
40629c5a2a9SRui Ueyama   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
40729c5a2a9SRui Ueyama     if (Cmd.Name == PhdrName)
40829c5a2a9SRui Ueyama       return I;
40929c5a2a9SRui Ueyama     ++I;
41029c5a2a9SRui Ueyama   }
41129c5a2a9SRui Ueyama   error("section header '" + PhdrName + "' is not listed in PHDRS");
41229c5a2a9SRui Ueyama   return 0;
41329c5a2a9SRui Ueyama }
41429c5a2a9SRui Ueyama 
41507320e40SRui Ueyama class elf::ScriptParser : public ScriptParserBase {
416c3794e58SGeorge Rimar   typedef void (ScriptParser::*Handler)();
417c3794e58SGeorge Rimar 
418f7c5fbb1SRui Ueyama public:
41907320e40SRui Ueyama   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
420f23b2320SGeorge Rimar 
4214a46539cSRui Ueyama   void run();
422f7c5fbb1SRui Ueyama 
423f7c5fbb1SRui Ueyama private:
42452a1509eSRui Ueyama   void addFile(StringRef Path);
42552a1509eSRui Ueyama 
426f7c5fbb1SRui Ueyama   void readAsNeeded();
42790c5099eSDenis Protivensky   void readEntry();
42883f406cfSGeorge Rimar   void readExtern();
429f7c5fbb1SRui Ueyama   void readGroup();
43031aa1f83SRui Ueyama   void readInclude();
431c3794e58SGeorge Rimar   void readNothing() {}
432ee59282bSRui Ueyama   void readOutput();
4339159ce93SDavide Italiano   void readOutputArch();
434f7c5fbb1SRui Ueyama   void readOutputFormat();
435bbe38602SEugene Leviant   void readPhdrs();
43668a39a65SDavide Italiano   void readSearchDir();
4378e3b38abSDenis Protivensky   void readSections();
4388e3b38abSDenis Protivensky 
439113cdec9SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
440eda81a1bSEugene Leviant   void readOutputSectionDescription(StringRef OutSec);
441f71caa2bSRui Ueyama   std::vector<uint8_t> readOutputSectionFiller();
442bbe38602SEugene Leviant   std::vector<StringRef> readOutputSectionPhdrs();
4430659800eSGeorge Rimar   std::unique_ptr<InputSectionDescription> readInputSectionDescription();
4440659800eSGeorge Rimar   void readInputSectionRules(InputSectionDescription *InCmd, bool Keep);
445bbe38602SEugene Leviant   unsigned readPhdrType();
446a31c91b1SEugene Leviant   void readProvide(bool Hidden);
447630c6179SGeorge Rimar   void readAlign(OutputSectionCommand *Cmd);
44803fc010eSGeorge Rimar   void readSort();
449708019c4SRui Ueyama 
450708019c4SRui Ueyama   Expr readExpr();
451708019c4SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
452708019c4SRui Ueyama   Expr readPrimary();
453708019c4SRui Ueyama   Expr readTernary(Expr Cond);
454708019c4SRui Ueyama   Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
455f7c5fbb1SRui Ueyama 
456c3794e58SGeorge Rimar   const static StringMap<Handler> Cmd;
45707320e40SRui Ueyama   ScriptConfiguration &Opt = *ScriptConfig;
45807320e40SRui Ueyama   StringSaver Saver = {ScriptConfig->Alloc};
45916b0cc9eSSimon Atanasyan   bool IsUnderSysroot;
460f7c5fbb1SRui Ueyama };
461f7c5fbb1SRui Ueyama 
462e0df00b9SRafael Espindola const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
463c3794e58SGeorge Rimar     {"ENTRY", &ScriptParser::readEntry},
464c3794e58SGeorge Rimar     {"EXTERN", &ScriptParser::readExtern},
465c3794e58SGeorge Rimar     {"GROUP", &ScriptParser::readGroup},
466c3794e58SGeorge Rimar     {"INCLUDE", &ScriptParser::readInclude},
467c3794e58SGeorge Rimar     {"INPUT", &ScriptParser::readGroup},
468c3794e58SGeorge Rimar     {"OUTPUT", &ScriptParser::readOutput},
469c3794e58SGeorge Rimar     {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
470c3794e58SGeorge Rimar     {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
471bbe38602SEugene Leviant     {"PHDRS", &ScriptParser::readPhdrs},
472c3794e58SGeorge Rimar     {"SEARCH_DIR", &ScriptParser::readSearchDir},
473c3794e58SGeorge Rimar     {"SECTIONS", &ScriptParser::readSections},
474c3794e58SGeorge Rimar     {";", &ScriptParser::readNothing}};
475c3794e58SGeorge Rimar 
476717677afSRui Ueyama void ScriptParser::run() {
477f7c5fbb1SRui Ueyama   while (!atEOF()) {
478f7c5fbb1SRui Ueyama     StringRef Tok = next();
479c3794e58SGeorge Rimar     if (Handler Fn = Cmd.lookup(Tok))
480c3794e58SGeorge Rimar       (this->*Fn)();
481c3794e58SGeorge Rimar     else
4825761042dSGeorge Rimar       setError("unknown directive: " + Tok);
483f7c5fbb1SRui Ueyama   }
484f7c5fbb1SRui Ueyama }
485f7c5fbb1SRui Ueyama 
486717677afSRui Ueyama void ScriptParser::addFile(StringRef S) {
48716b0cc9eSSimon Atanasyan   if (IsUnderSysroot && S.startswith("/")) {
48816b0cc9eSSimon Atanasyan     SmallString<128> Path;
48916b0cc9eSSimon Atanasyan     (Config->Sysroot + S).toStringRef(Path);
49016b0cc9eSSimon Atanasyan     if (sys::fs::exists(Path)) {
49116b0cc9eSSimon Atanasyan       Driver->addFile(Saver.save(Path.str()));
49216b0cc9eSSimon Atanasyan       return;
49316b0cc9eSSimon Atanasyan     }
49416b0cc9eSSimon Atanasyan   }
49516b0cc9eSSimon Atanasyan 
496f03f3cc1SRui Ueyama   if (sys::path::is_absolute(S)) {
49752a1509eSRui Ueyama     Driver->addFile(S);
49852a1509eSRui Ueyama   } else if (S.startswith("=")) {
49952a1509eSRui Ueyama     if (Config->Sysroot.empty())
50052a1509eSRui Ueyama       Driver->addFile(S.substr(1));
50152a1509eSRui Ueyama     else
50252a1509eSRui Ueyama       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
50352a1509eSRui Ueyama   } else if (S.startswith("-l")) {
50421eecb4fSRui Ueyama     Driver->addLibrary(S.substr(2));
505a1b8fc3bSSimon Atanasyan   } else if (sys::fs::exists(S)) {
506a1b8fc3bSSimon Atanasyan     Driver->addFile(S);
50752a1509eSRui Ueyama   } else {
50852a1509eSRui Ueyama     std::string Path = findFromSearchPaths(S);
50952a1509eSRui Ueyama     if (Path.empty())
510777f9630SGeorge Rimar       setError("unable to find " + S);
511025d59b1SRui Ueyama     else
51252a1509eSRui Ueyama       Driver->addFile(Saver.save(Path));
51352a1509eSRui Ueyama   }
51452a1509eSRui Ueyama }
51552a1509eSRui Ueyama 
516717677afSRui Ueyama void ScriptParser::readAsNeeded() {
517f7c5fbb1SRui Ueyama   expect("(");
51835da9b6eSRui Ueyama   bool Orig = Config->AsNeeded;
51935da9b6eSRui Ueyama   Config->AsNeeded = true;
520025d59b1SRui Ueyama   while (!Error) {
521f7c5fbb1SRui Ueyama     StringRef Tok = next();
522f7c5fbb1SRui Ueyama     if (Tok == ")")
52335da9b6eSRui Ueyama       break;
52452a1509eSRui Ueyama     addFile(Tok);
525f7c5fbb1SRui Ueyama   }
52635da9b6eSRui Ueyama   Config->AsNeeded = Orig;
527f7c5fbb1SRui Ueyama }
528f7c5fbb1SRui Ueyama 
529717677afSRui Ueyama void ScriptParser::readEntry() {
53090c5099eSDenis Protivensky   // -e <symbol> takes predecence over ENTRY(<symbol>).
53190c5099eSDenis Protivensky   expect("(");
53290c5099eSDenis Protivensky   StringRef Tok = next();
53390c5099eSDenis Protivensky   if (Config->Entry.empty())
53490c5099eSDenis Protivensky     Config->Entry = Tok;
53590c5099eSDenis Protivensky   expect(")");
53690c5099eSDenis Protivensky }
53790c5099eSDenis Protivensky 
538717677afSRui Ueyama void ScriptParser::readExtern() {
53983f406cfSGeorge Rimar   expect("(");
540025d59b1SRui Ueyama   while (!Error) {
54183f406cfSGeorge Rimar     StringRef Tok = next();
54283f406cfSGeorge Rimar     if (Tok == ")")
54383f406cfSGeorge Rimar       return;
54483f406cfSGeorge Rimar     Config->Undefined.push_back(Tok);
54583f406cfSGeorge Rimar   }
54683f406cfSGeorge Rimar }
54783f406cfSGeorge Rimar 
548717677afSRui Ueyama void ScriptParser::readGroup() {
549f7c5fbb1SRui Ueyama   expect("(");
550025d59b1SRui Ueyama   while (!Error) {
551f7c5fbb1SRui Ueyama     StringRef Tok = next();
552f7c5fbb1SRui Ueyama     if (Tok == ")")
553f7c5fbb1SRui Ueyama       return;
554f7c5fbb1SRui Ueyama     if (Tok == "AS_NEEDED") {
555f7c5fbb1SRui Ueyama       readAsNeeded();
556f7c5fbb1SRui Ueyama       continue;
557f7c5fbb1SRui Ueyama     }
55852a1509eSRui Ueyama     addFile(Tok);
559f7c5fbb1SRui Ueyama   }
560f7c5fbb1SRui Ueyama }
561f7c5fbb1SRui Ueyama 
562717677afSRui Ueyama void ScriptParser::readInclude() {
56331aa1f83SRui Ueyama   StringRef Tok = next();
56431aa1f83SRui Ueyama   auto MBOrErr = MemoryBuffer::getFile(Tok);
565025d59b1SRui Ueyama   if (!MBOrErr) {
5665761042dSGeorge Rimar     setError("cannot open " + Tok);
567025d59b1SRui Ueyama     return;
568025d59b1SRui Ueyama   }
56931aa1f83SRui Ueyama   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
570a47ee68dSRui Ueyama   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
571a47ee68dSRui Ueyama   std::vector<StringRef> V = tokenize(S);
57231aa1f83SRui Ueyama   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
57331aa1f83SRui Ueyama }
57431aa1f83SRui Ueyama 
575717677afSRui Ueyama void ScriptParser::readOutput() {
576ee59282bSRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
577ee59282bSRui Ueyama   expect("(");
578ee59282bSRui Ueyama   StringRef Tok = next();
579ee59282bSRui Ueyama   if (Config->OutputFile.empty())
580ee59282bSRui Ueyama     Config->OutputFile = Tok;
581ee59282bSRui Ueyama   expect(")");
582ee59282bSRui Ueyama }
583ee59282bSRui Ueyama 
584717677afSRui Ueyama void ScriptParser::readOutputArch() {
5859159ce93SDavide Italiano   // Error checking only for now.
5869159ce93SDavide Italiano   expect("(");
5879159ce93SDavide Italiano   next();
5889159ce93SDavide Italiano   expect(")");
5899159ce93SDavide Italiano }
5909159ce93SDavide Italiano 
591717677afSRui Ueyama void ScriptParser::readOutputFormat() {
592f7c5fbb1SRui Ueyama   // Error checking only for now.
593f7c5fbb1SRui Ueyama   expect("(");
594f7c5fbb1SRui Ueyama   next();
5956836c618SDavide Italiano   StringRef Tok = next();
5966836c618SDavide Italiano   if (Tok == ")")
5976836c618SDavide Italiano    return;
598025d59b1SRui Ueyama   if (Tok != ",") {
5995761042dSGeorge Rimar     setError("unexpected token: " + Tok);
600025d59b1SRui Ueyama     return;
601025d59b1SRui Ueyama   }
6026836c618SDavide Italiano   next();
6036836c618SDavide Italiano   expect(",");
6046836c618SDavide Italiano   next();
605f7c5fbb1SRui Ueyama   expect(")");
606f7c5fbb1SRui Ueyama }
607f7c5fbb1SRui Ueyama 
608bbe38602SEugene Leviant void ScriptParser::readPhdrs() {
609bbe38602SEugene Leviant   expect("{");
610bbe38602SEugene Leviant   while (!Error && !skip("}")) {
611bbe38602SEugene Leviant     StringRef Tok = next();
612865bf863SEugene Leviant     Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
613bbe38602SEugene Leviant     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
614bbe38602SEugene Leviant 
615bbe38602SEugene Leviant     PhdrCmd.Type = readPhdrType();
616bbe38602SEugene Leviant     do {
617bbe38602SEugene Leviant       Tok = next();
618bbe38602SEugene Leviant       if (Tok == ";")
619bbe38602SEugene Leviant         break;
620bbe38602SEugene Leviant       if (Tok == "FILEHDR")
621bbe38602SEugene Leviant         PhdrCmd.HasFilehdr = true;
622bbe38602SEugene Leviant       else if (Tok == "PHDRS")
623bbe38602SEugene Leviant         PhdrCmd.HasPhdrs = true;
624865bf863SEugene Leviant       else if (Tok == "FLAGS") {
625865bf863SEugene Leviant         expect("(");
626865bf863SEugene Leviant         next().getAsInteger(0, PhdrCmd.Flags);
627865bf863SEugene Leviant         expect(")");
628865bf863SEugene Leviant       } else
629bbe38602SEugene Leviant         setError("unexpected header attribute: " + Tok);
630bbe38602SEugene Leviant     } while (!Error);
631bbe38602SEugene Leviant   }
632bbe38602SEugene Leviant }
633bbe38602SEugene Leviant 
634717677afSRui Ueyama void ScriptParser::readSearchDir() {
63568a39a65SDavide Italiano   expect("(");
63606501920SRafael Espindola   Config->SearchPaths.push_back(next());
63768a39a65SDavide Italiano   expect(")");
63868a39a65SDavide Italiano }
63968a39a65SDavide Italiano 
640717677afSRui Ueyama void ScriptParser::readSections() {
6413de0a330SRui Ueyama   Opt.HasContents = true;
6428e3b38abSDenis Protivensky   expect("{");
643652852c5SGeorge Rimar   while (!Error && !skip("}")) {
644113cdec9SRui Ueyama     StringRef Tok = next();
64530835ea4SGeorge Rimar     if (peek() == "=" || peek() == "+=") {
646113cdec9SRui Ueyama       readAssignment(Tok);
647113cdec9SRui Ueyama       expect(";");
648113cdec9SRui Ueyama     } else if (Tok == "PROVIDE") {
649a31c91b1SEugene Leviant       readProvide(false);
650708019c4SRui Ueyama     } else if (Tok == "PROVIDE_HIDDEN") {
651a31c91b1SEugene Leviant       readProvide(true);
652708019c4SRui Ueyama     } else {
653eda81a1bSEugene Leviant       readOutputSectionDescription(Tok);
6548e3b38abSDenis Protivensky     }
655652852c5SGeorge Rimar   }
656708019c4SRui Ueyama }
6578e3b38abSDenis Protivensky 
658708019c4SRui Ueyama static int precedence(StringRef Op) {
659708019c4SRui Ueyama   return StringSwitch<int>(Op)
660708019c4SRui Ueyama       .Case("*", 4)
661708019c4SRui Ueyama       .Case("/", 4)
662708019c4SRui Ueyama       .Case("+", 3)
663708019c4SRui Ueyama       .Case("-", 3)
664708019c4SRui Ueyama       .Case("<", 2)
665708019c4SRui Ueyama       .Case(">", 2)
666708019c4SRui Ueyama       .Case(">=", 2)
667708019c4SRui Ueyama       .Case("<=", 2)
668708019c4SRui Ueyama       .Case("==", 2)
669708019c4SRui Ueyama       .Case("!=", 2)
670708019c4SRui Ueyama       .Case("&", 1)
671708019c4SRui Ueyama       .Default(-1);
672708019c4SRui Ueyama }
673708019c4SRui Ueyama 
6740659800eSGeorge Rimar void ScriptParser::readInputSectionRules(InputSectionDescription *InCmd, bool Keep) {
6750659800eSGeorge Rimar   InCmd->FilePattern = next();
6760ed42b0cSDavide Italiano   expect("(");
677e7282797SDavide Italiano 
678e7282797SDavide Italiano   if (skip("EXCLUDE_FILE")) {
679e7282797SDavide Italiano     expect("(");
680e7282797SDavide Italiano     while (!Error && !skip(")"))
681e7282797SDavide Italiano       InCmd->ExcludedFiles.push_back(next());
682e7282797SDavide Italiano   }
683e7282797SDavide Italiano 
6840659800eSGeorge Rimar   while (!Error && !skip(")")) {
6850659800eSGeorge Rimar     if (Keep)
6860659800eSGeorge Rimar       Opt.KeptSections.push_back(peek());
6870659800eSGeorge Rimar     InCmd->SectionPatterns.push_back(next());
6880659800eSGeorge Rimar   }
6890659800eSGeorge Rimar }
6900659800eSGeorge Rimar 
6910659800eSGeorge Rimar std::unique_ptr<InputSectionDescription>
6920659800eSGeorge Rimar ScriptParser::readInputSectionDescription() {
693352eac37SGeorge Rimar   auto InCmd = llvm::make_unique<InputSectionDescription>();
6940659800eSGeorge Rimar 
6950659800eSGeorge Rimar   // Input section wildcard can be surrounded by KEEP.
6960659800eSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
6970659800eSGeorge Rimar   if (skip("KEEP")) {
698e7282797SDavide Italiano     expect("(");
6990659800eSGeorge Rimar     readInputSectionRules(InCmd.get(), true);
7000ed42b0cSDavide Italiano     expect(")");
7010659800eSGeorge Rimar   } else {
7020659800eSGeorge Rimar     readInputSectionRules(InCmd.get(), false);
7030659800eSGeorge Rimar   }
7040659800eSGeorge Rimar 
7050659800eSGeorge Rimar   return InCmd;
7060ed42b0cSDavide Italiano }
7070ed42b0cSDavide Italiano 
708630c6179SGeorge Rimar void ScriptParser::readAlign(OutputSectionCommand *Cmd) {
709630c6179SGeorge Rimar   expect("(");
710630c6179SGeorge Rimar   Cmd->AlignExpr = readExpr();
711630c6179SGeorge Rimar   expect(")");
712630c6179SGeorge Rimar }
713630c6179SGeorge Rimar 
71403fc010eSGeorge Rimar void ScriptParser::readSort() {
71503fc010eSGeorge Rimar   expect("(");
71603fc010eSGeorge Rimar   expect("CONSTRUCTORS");
71703fc010eSGeorge Rimar   expect(")");
71803fc010eSGeorge Rimar }
71903fc010eSGeorge Rimar 
720eda81a1bSEugene Leviant void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
721076fe157SGeorge Rimar   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
722076fe157SGeorge Rimar   Opt.Commands.emplace_back(Cmd);
72358e5c4dcSGeorge Rimar 
72458e5c4dcSGeorge Rimar   // Read an address expression.
72558e5c4dcSGeorge Rimar   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
72658e5c4dcSGeorge Rimar   if (peek() != ":")
72758e5c4dcSGeorge Rimar     Cmd->AddrExpr = readExpr();
72858e5c4dcSGeorge Rimar 
7298e3b38abSDenis Protivensky   expect(":");
730246f681eSDavide Italiano 
731630c6179SGeorge Rimar   if (skip("ALIGN"))
732630c6179SGeorge Rimar     readAlign(Cmd);
733630c6179SGeorge Rimar 
734246f681eSDavide Italiano   // Parse constraints.
735246f681eSDavide Italiano   if (skip("ONLY_IF_RO"))
736efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
737246f681eSDavide Italiano   if (skip("ONLY_IF_RW"))
738efc4066bSRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
7398e3b38abSDenis Protivensky   expect("{");
7408ec77e64SRui Ueyama 
741025d59b1SRui Ueyama   while (!Error && !skip("}")) {
742f586ff7eSGeorge Rimar     if (peek().startswith("*") || peek() == "KEEP") {
7430659800eSGeorge Rimar       Cmd->Commands.push_back(readInputSectionDescription());
7440659800eSGeorge Rimar       continue;
7450659800eSGeorge Rimar     }
7460659800eSGeorge Rimar 
747481c2ce6SGeorge Rimar     StringRef Tok = next();
7480659800eSGeorge Rimar     if (Tok == "PROVIDE") {
749054a6796SDavide Italiano       readProvide(false);
750054a6796SDavide Italiano     } else if (Tok == "PROVIDE_HIDDEN") {
751054a6796SDavide Italiano       readProvide(true);
75203fc010eSGeorge Rimar     } else if (Tok == "SORT") {
75303fc010eSGeorge Rimar       readSort();
754481c2ce6SGeorge Rimar     } else {
755777f9630SGeorge Rimar       setError("unknown command " + Tok);
756481c2ce6SGeorge Rimar     }
7578e3b38abSDenis Protivensky   }
758076fe157SGeorge Rimar   Cmd->Phdrs = readOutputSectionPhdrs();
759f71caa2bSRui Ueyama   Cmd->Filler = readOutputSectionFiller();
760f71caa2bSRui Ueyama }
7618ec77e64SRui Ueyama 
762f71caa2bSRui Ueyama std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
763e2ee72b5SGeorge Rimar   StringRef Tok = peek();
764f71caa2bSRui Ueyama   if (!Tok.startswith("="))
765f71caa2bSRui Ueyama     return {};
766e2ee72b5SGeorge Rimar   if (!Tok.startswith("=0x")) {
7673ed2f069SRui Ueyama     setError("filler should be a hexadecimal value");
768f71caa2bSRui Ueyama     return {};
769e2ee72b5SGeorge Rimar   }
7703e808976SRui Ueyama   Tok = Tok.substr(3);
771e2ee72b5SGeorge Rimar   next();
772f71caa2bSRui Ueyama   return parseHex(Tok);
7738e3b38abSDenis Protivensky }
7748e3b38abSDenis Protivensky 
775a31c91b1SEugene Leviant void ScriptParser::readProvide(bool Hidden) {
776a31c91b1SEugene Leviant   expect("(");
777174e0a16SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
778174e0a16SRui Ueyama   Cmd->Provide = true;
779174e0a16SRui Ueyama   Cmd->Hidden = Hidden;
780a31c91b1SEugene Leviant   expect(")");
781a31c91b1SEugene Leviant   expect(";");
782eda81a1bSEugene Leviant }
783eda81a1bSEugene Leviant 
78430835ea4SGeorge Rimar static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
78530835ea4SGeorge Rimar   if (S == ".")
78630835ea4SGeorge Rimar     return Dot;
787a31c91b1SEugene Leviant 
788a9c5a528SGeorge Rimar   switch (Config->EKind) {
789a9c5a528SGeorge Rimar   case ELF32LEKind:
790a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
791a9c5a528SGeorge Rimar       return B->getVA<ELF32LE>();
792a9c5a528SGeorge Rimar     break;
793a9c5a528SGeorge Rimar   case ELF32BEKind:
794a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
795a9c5a528SGeorge Rimar       return B->getVA<ELF32BE>();
796a9c5a528SGeorge Rimar     break;
797a9c5a528SGeorge Rimar   case ELF64LEKind:
798a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
799a9c5a528SGeorge Rimar       return B->getVA<ELF64LE>();
800a9c5a528SGeorge Rimar     break;
801a9c5a528SGeorge Rimar   case ELF64BEKind:
802a9c5a528SGeorge Rimar     if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
803a9c5a528SGeorge Rimar       return B->getVA<ELF64BE>();
804a9c5a528SGeorge Rimar     break;
8056930a6dcSGeorge Rimar   default:
806b567b628SGeorge Rimar     llvm_unreachable("unsupported target");
807a9c5a528SGeorge Rimar   }
808a9c5a528SGeorge Rimar   error("symbol not found: " + S);
809a9c5a528SGeorge Rimar   return 0;
810a9c5a528SGeorge Rimar }
811a9c5a528SGeorge Rimar 
81230835ea4SGeorge Rimar SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
81330835ea4SGeorge Rimar   StringRef Op = next();
81430835ea4SGeorge Rimar   assert(Op == "=" || Op == "+=");
81530835ea4SGeorge Rimar   Expr E = readExpr();
81630835ea4SGeorge Rimar   if (Op == "+=")
81730835ea4SGeorge Rimar     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
81830835ea4SGeorge Rimar   auto *Cmd = new SymbolAssignment(Name, E);
81930835ea4SGeorge Rimar   Opt.Commands.emplace_back(Cmd);
82030835ea4SGeorge Rimar   return Cmd;
82130835ea4SGeorge Rimar }
82230835ea4SGeorge Rimar 
82330835ea4SGeorge Rimar // This is an operator-precedence parser to parse a linker
82430835ea4SGeorge Rimar // script expression.
82530835ea4SGeorge Rimar Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
82630835ea4SGeorge Rimar 
827708019c4SRui Ueyama // This is a part of the operator-precedence parser. This function
828708019c4SRui Ueyama // assumes that the remaining token stream starts with an operator.
829708019c4SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
830708019c4SRui Ueyama   while (!atEOF() && !Error) {
831708019c4SRui Ueyama     // Read an operator and an expression.
832708019c4SRui Ueyama     StringRef Op1 = peek();
833708019c4SRui Ueyama     if (Op1 == "?")
834708019c4SRui Ueyama       return readTernary(Lhs);
835708019c4SRui Ueyama     if (precedence(Op1) < MinPrec)
836a31c91b1SEugene Leviant       break;
837a31c91b1SEugene Leviant     next();
838708019c4SRui Ueyama     Expr Rhs = readPrimary();
839708019c4SRui Ueyama 
840708019c4SRui Ueyama     // Evaluate the remaining part of the expression first if the
841708019c4SRui Ueyama     // next operator has greater precedence than the previous one.
842708019c4SRui Ueyama     // For example, if we have read "+" and "3", and if the next
843708019c4SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
844708019c4SRui Ueyama     while (!atEOF()) {
845708019c4SRui Ueyama       StringRef Op2 = peek();
846708019c4SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
847eda81a1bSEugene Leviant         break;
848708019c4SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
849eda81a1bSEugene Leviant     }
850708019c4SRui Ueyama 
851708019c4SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
852708019c4SRui Ueyama   }
853708019c4SRui Ueyama   return Lhs;
854708019c4SRui Ueyama }
855708019c4SRui Ueyama 
856708019c4SRui Ueyama uint64_t static getConstant(StringRef S) {
857708019c4SRui Ueyama   if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
858708019c4SRui Ueyama     return Target->PageSize;
859708019c4SRui Ueyama   error("unknown constant: " + S);
860708019c4SRui Ueyama   return 0;
861708019c4SRui Ueyama }
862708019c4SRui Ueyama 
863708019c4SRui Ueyama Expr ScriptParser::readPrimary() {
864708019c4SRui Ueyama   StringRef Tok = next();
865708019c4SRui Ueyama 
866708019c4SRui Ueyama   if (Tok == "(") {
867708019c4SRui Ueyama     Expr E = readExpr();
868708019c4SRui Ueyama     expect(")");
869708019c4SRui Ueyama     return E;
870708019c4SRui Ueyama   }
871708019c4SRui Ueyama 
872708019c4SRui Ueyama   // Built-in functions are parsed here.
873708019c4SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
874708019c4SRui Ueyama   if (Tok == "ALIGN") {
875708019c4SRui Ueyama     expect("(");
876708019c4SRui Ueyama     Expr E = readExpr();
877708019c4SRui Ueyama     expect(")");
878708019c4SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
879708019c4SRui Ueyama   }
880708019c4SRui Ueyama   if (Tok == "CONSTANT") {
881708019c4SRui Ueyama     expect("(");
882708019c4SRui Ueyama     StringRef Tok = next();
883708019c4SRui Ueyama     expect(")");
884708019c4SRui Ueyama     return [=](uint64_t Dot) { return getConstant(Tok); };
885708019c4SRui Ueyama   }
88654c145ceSRafael Espindola   if (Tok == "SEGMENT_START") {
88754c145ceSRafael Espindola     expect("(");
88854c145ceSRafael Espindola     next();
88954c145ceSRafael Espindola     expect(",");
89054c145ceSRafael Espindola     uint64_t Val;
89154c145ceSRafael Espindola     next().getAsInteger(0, Val);
89254c145ceSRafael Espindola     expect(")");
89354c145ceSRafael Espindola     return [=](uint64_t Dot) { return Val; };
89454c145ceSRafael Espindola   }
895708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
896708019c4SRui Ueyama     expect("(");
897708019c4SRui Ueyama     Expr E = readExpr();
898708019c4SRui Ueyama     expect(",");
899708019c4SRui Ueyama     readExpr();
900708019c4SRui Ueyama     expect(")");
901f7791bb9SRui Ueyama     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
902708019c4SRui Ueyama   }
903708019c4SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
904708019c4SRui Ueyama     expect("(");
905708019c4SRui Ueyama     expect(".");
906708019c4SRui Ueyama     expect(")");
907708019c4SRui Ueyama     return [](uint64_t Dot) { return Dot; };
908708019c4SRui Ueyama   }
909276b4e64SGeorge Rimar   // GNU linkers implements more complicated logic to handle
910276b4e64SGeorge Rimar   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
911276b4e64SGeorge Rimar   // the next page boundary for simplicity.
912276b4e64SGeorge Rimar   if (Tok == "DATA_SEGMENT_RELRO_END") {
913276b4e64SGeorge Rimar     expect("(");
914276b4e64SGeorge Rimar     next();
915276b4e64SGeorge Rimar     expect(",");
916276b4e64SGeorge Rimar     readExpr();
917276b4e64SGeorge Rimar     expect(")");
918276b4e64SGeorge Rimar     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
919276b4e64SGeorge Rimar   }
920708019c4SRui Ueyama 
921a9c5a528SGeorge Rimar   // Parse a symbol name or a number literal.
922708019c4SRui Ueyama   uint64_t V = 0;
923a9c5a528SGeorge Rimar   if (Tok.getAsInteger(0, V)) {
92430835ea4SGeorge Rimar     if (Tok != "." && !isValidCIdentifier(Tok))
925708019c4SRui Ueyama       setError("malformed number: " + Tok);
92630835ea4SGeorge Rimar     return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
927a9c5a528SGeorge Rimar   }
928708019c4SRui Ueyama   return [=](uint64_t Dot) { return V; };
929708019c4SRui Ueyama }
930708019c4SRui Ueyama 
931708019c4SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
932708019c4SRui Ueyama   next();
933708019c4SRui Ueyama   Expr L = readExpr();
934708019c4SRui Ueyama   expect(":");
935708019c4SRui Ueyama   Expr R = readExpr();
936708019c4SRui Ueyama   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
937708019c4SRui Ueyama }
938708019c4SRui Ueyama 
939708019c4SRui Ueyama Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
940708019c4SRui Ueyama   if (Op == "*")
941708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
942708019c4SRui Ueyama   if (Op == "/") {
943708019c4SRui Ueyama     return [=](uint64_t Dot) -> uint64_t {
944708019c4SRui Ueyama       uint64_t RHS = R(Dot);
945708019c4SRui Ueyama       if (RHS == 0) {
946708019c4SRui Ueyama         error("division by zero");
947708019c4SRui Ueyama         return 0;
948708019c4SRui Ueyama       }
949708019c4SRui Ueyama       return L(Dot) / RHS;
950708019c4SRui Ueyama     };
951708019c4SRui Ueyama   }
952708019c4SRui Ueyama   if (Op == "+")
953708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
954708019c4SRui Ueyama   if (Op == "-")
955708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
956708019c4SRui Ueyama   if (Op == "<")
957708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
958708019c4SRui Ueyama   if (Op == ">")
959708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
960708019c4SRui Ueyama   if (Op == ">=")
961708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
962708019c4SRui Ueyama   if (Op == "<=")
963708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
964708019c4SRui Ueyama   if (Op == "==")
965708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
966708019c4SRui Ueyama   if (Op == "!=")
967708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
968708019c4SRui Ueyama   if (Op == "&")
969708019c4SRui Ueyama     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
970708019c4SRui Ueyama   llvm_unreachable("invalid operator");
971eda81a1bSEugene Leviant }
972eda81a1bSEugene Leviant 
973bbe38602SEugene Leviant std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
974bbe38602SEugene Leviant   std::vector<StringRef> Phdrs;
975bbe38602SEugene Leviant   while (!Error && peek().startswith(":")) {
976bbe38602SEugene Leviant     StringRef Tok = next();
977bbe38602SEugene Leviant     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
978bbe38602SEugene Leviant     if (Tok.empty()) {
979bbe38602SEugene Leviant       setError("section header name is empty");
980bbe38602SEugene Leviant       break;
981bbe38602SEugene Leviant     }
982bbe38602SEugene Leviant     Phdrs.push_back(Tok);
983bbe38602SEugene Leviant   }
984bbe38602SEugene Leviant   return Phdrs;
985bbe38602SEugene Leviant }
986bbe38602SEugene Leviant 
987bbe38602SEugene Leviant unsigned ScriptParser::readPhdrType() {
988bbe38602SEugene Leviant   StringRef Tok = next();
989b0f6c590SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
990b0f6c590SRui Ueyama       .Case("PT_NULL", PT_NULL)
991b0f6c590SRui Ueyama       .Case("PT_LOAD", PT_LOAD)
992b0f6c590SRui Ueyama       .Case("PT_DYNAMIC", PT_DYNAMIC)
993b0f6c590SRui Ueyama       .Case("PT_INTERP", PT_INTERP)
994b0f6c590SRui Ueyama       .Case("PT_NOTE", PT_NOTE)
995b0f6c590SRui Ueyama       .Case("PT_SHLIB", PT_SHLIB)
996b0f6c590SRui Ueyama       .Case("PT_PHDR", PT_PHDR)
997b0f6c590SRui Ueyama       .Case("PT_TLS", PT_TLS)
998b0f6c590SRui Ueyama       .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
999b0f6c590SRui Ueyama       .Case("PT_GNU_STACK", PT_GNU_STACK)
1000b0f6c590SRui Ueyama       .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1001b0f6c590SRui Ueyama       .Default(-1);
1002bbe38602SEugene Leviant 
1003b0f6c590SRui Ueyama   if (Ret == (unsigned)-1) {
1004b0f6c590SRui Ueyama     setError("invalid program header type: " + Tok);
1005b0f6c590SRui Ueyama     return PT_NULL;
1006b0f6c590SRui Ueyama   }
1007b0f6c590SRui Ueyama   return Ret;
1008bbe38602SEugene Leviant }
1009bbe38602SEugene Leviant 
101016b0cc9eSSimon Atanasyan static bool isUnderSysroot(StringRef Path) {
101116b0cc9eSSimon Atanasyan   if (Config->Sysroot == "")
101216b0cc9eSSimon Atanasyan     return false;
101316b0cc9eSSimon Atanasyan   for (; !Path.empty(); Path = sys::path::parent_path(Path))
101416b0cc9eSSimon Atanasyan     if (sys::fs::equivalent(Config->Sysroot, Path))
101516b0cc9eSSimon Atanasyan       return true;
101616b0cc9eSSimon Atanasyan   return false;
101716b0cc9eSSimon Atanasyan }
101816b0cc9eSSimon Atanasyan 
101907320e40SRui Ueyama // Entry point.
102007320e40SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
102116b0cc9eSSimon Atanasyan   StringRef Path = MB.getBufferIdentifier();
102207320e40SRui Ueyama   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
1023f7c5fbb1SRui Ueyama }
10241ebc8ed7SRui Ueyama 
102507320e40SRui Ueyama template class elf::LinkerScript<ELF32LE>;
102607320e40SRui Ueyama template class elf::LinkerScript<ELF32BE>;
102707320e40SRui Ueyama template class elf::LinkerScript<ELF64LE>;
102807320e40SRui Ueyama template class elf::LinkerScript<ELF64BE>;
1029