1 //===- LinkerScript.cpp ---------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the parser/evaluator of the linker script.
11 // It parses a linker script and write the result to Config or ScriptConfig
12 // objects.
13 //
14 // If SECTIONS command is used, a ScriptConfig contains an AST
15 // of the command which will later be consumed by createSections() and
16 // assignAddresses().
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "LinkerScript.h"
21 #include "Config.h"
22 #include "Driver.h"
23 #include "InputSection.h"
24 #include "OutputSections.h"
25 #include "ScriptParser.h"
26 #include "Strings.h"
27 #include "Symbols.h"
28 #include "SymbolTable.h"
29 #include "Target.h"
30 #include "Writer.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/StringSaver.h"
37 
38 using namespace llvm;
39 using namespace llvm::ELF;
40 using namespace llvm::object;
41 using namespace lld;
42 using namespace lld::elf;
43 
44 ScriptConfiguration *elf::ScriptConfig;
45 
46 template <class ELFT>
47 static void addRegular(SymbolAssignment *Cmd) {
48   Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49   Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50   Cmd->Sym = Sym->body();
51 }
52 
53 template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
54   Symbol *Sym = Symtab<ELFT>::X->addSynthetic(Cmd->Name, nullptr, 0);
55   Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
56   Cmd->Sym = Sym->body();
57 }
58 
59 // If a symbol was in PROVIDE(), we need to define it only when
60 // it is an undefined symbol.
61 template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
62   if (Cmd->Name == ".")
63     return false;
64   if (!Cmd->Provide)
65     return true;
66   SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
67   return B && B->isUndefined();
68 }
69 
70 bool SymbolAssignment::classof(const BaseCommand *C) {
71   return C->Kind == AssignmentKind;
72 }
73 
74 bool OutputSectionCommand::classof(const BaseCommand *C) {
75   return C->Kind == OutputSectionKind;
76 }
77 
78 bool InputSectionDescription::classof(const BaseCommand *C) {
79   return C->Kind == InputSectionKind;
80 }
81 
82 bool AssertCommand::classof(const BaseCommand *C) {
83   return C->Kind == AssertKind;
84 }
85 
86 template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
87   return !S || !S->Live;
88 }
89 
90 template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
91 template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
92 
93 template <class ELFT>
94 bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
95   for (StringRef Pat : Opt.KeptSections)
96     if (globMatch(Pat, S->getSectionName()))
97       return true;
98   return false;
99 }
100 
101 static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
102   for (StringRef Pat : Patterns)
103     if (globMatch(Pat, S))
104       return true;
105   return false;
106 }
107 
108 static bool fileMatches(const InputSectionDescription *Desc,
109                         StringRef Filename) {
110   if (!globMatch(Desc->FilePattern, Filename))
111     return false;
112   return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
113 }
114 
115 // Returns input sections filtered by given glob patterns.
116 template <class ELFT>
117 std::vector<InputSectionBase<ELFT> *>
118 LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
119   ArrayRef<StringRef> Patterns = I->SectionPatterns;
120   std::vector<InputSectionBase<ELFT> *> Ret;
121   for (const std::unique_ptr<ObjectFile<ELFT>> &F :
122        Symtab<ELFT>::X->getObjectFiles()) {
123     if (fileMatches(I, sys::path::filename(F->getName())))
124       for (InputSectionBase<ELFT> *S : F->getSections())
125         if (!isDiscarded(S) && !S->OutSec &&
126             match(Patterns, S->getSectionName()))
127           Ret.push_back(S);
128   }
129 
130   if (llvm::find(Patterns, "COMMON") != Patterns.end())
131     Ret.push_back(CommonInputSection<ELFT>::X);
132 
133   return Ret;
134 }
135 
136 // You can define new symbols using linker scripts. For example,
137 // ".text { abc.o(.text); foo = .; def.o(.text); }" defines symbol
138 // foo just after abc.o's text section contents. This class is to
139 // handle such symbol definitions.
140 //
141 // In order to handle scripts like the above one, we want to
142 // keep symbol definitions in output sections. Because output sections
143 // can contain only input sections, we wrap symbol definitions
144 // with dummy input sections. This class serves that purpose.
145 template <class ELFT>
146 class elf::LayoutInputSection : public InputSectionBase<ELFT> {
147 public:
148   explicit LayoutInputSection(SymbolAssignment *Cmd);
149   static bool classof(const InputSectionBase<ELFT> *S);
150   SymbolAssignment *Cmd;
151 
152 private:
153   typename ELFT::Shdr Hdr;
154 };
155 
156 template <class ELFT>
157 static InputSectionBase<ELFT> *
158 getNonLayoutSection(std::vector<InputSectionBase<ELFT> *> &Vec) {
159   for (InputSectionBase<ELFT> *S : Vec)
160     if (!isa<LayoutInputSection<ELFT>>(S))
161       return S;
162   return nullptr;
163 }
164 
165 template <class T> static T *zero(T *Val) {
166   memset(Val, 0, sizeof(*Val));
167   return Val;
168 }
169 
170 template <class ELFT>
171 LayoutInputSection<ELFT>::LayoutInputSection(SymbolAssignment *Cmd)
172     : InputSectionBase<ELFT>(nullptr, zero(&Hdr),
173                              InputSectionBase<ELFT>::Layout),
174       Cmd(Cmd) {
175   this->Live = true;
176   Hdr.sh_type = SHT_NOBITS;
177 }
178 
179 template <class ELFT>
180 bool LayoutInputSection<ELFT>::classof(const InputSectionBase<ELFT> *S) {
181   return S->SectionKind == InputSectionBase<ELFT>::Layout;
182 }
183 
184 template <class ELFT>
185 static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
186   return A->getSectionName() < B->getSectionName();
187 }
188 
189 template <class ELFT>
190 static bool compareAlignment(InputSectionBase<ELFT> *A,
191                              InputSectionBase<ELFT> *B) {
192   // ">" is not a mistake. Larger alignments are placed before smaller
193   // alignments in order to reduce the amount of padding necessary.
194   // This is compatible with GNU.
195   return A->Alignment > B->Alignment;
196 }
197 
198 template <class ELFT>
199 static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
200 getComparator(SortKind K) {
201   if (K == SortByName)
202     return compareName<ELFT>;
203   return compareAlignment<ELFT>;
204 }
205 
206 template <class ELFT>
207 void LinkerScript<ELFT>::discard(OutputSectionCommand &Cmd) {
208   for (const std::unique_ptr<BaseCommand> &Base : Cmd.Commands) {
209     if (auto *Cmd = dyn_cast<InputSectionDescription>(Base.get())) {
210       for (InputSectionBase<ELFT> *S : getInputSections(Cmd)) {
211         S->Live = false;
212         reportDiscarded(S);
213       }
214     }
215   }
216 }
217 
218 template <class ELFT>
219 static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
220                              ConstraintKind Kind) {
221   bool RO = (Kind == ConstraintKind::ReadOnly);
222   bool RW = (Kind == ConstraintKind::ReadWrite);
223   return !llvm::any_of(Sections, [=](InputSectionBase<ELFT> *Sec) {
224     bool Writable = Sec->getSectionHdr()->sh_flags & SHF_WRITE;
225     return (RO && Writable) || (RW && !Writable);
226   });
227 }
228 
229 template <class ELFT>
230 std::vector<InputSectionBase<ELFT> *>
231 LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
232   std::vector<InputSectionBase<ELFT> *> Ret;
233 
234   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
235     if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get())) {
236       if (shouldDefine<ELFT>(OutCmd))
237         addSynthetic<ELFT>(OutCmd);
238       Ret.push_back(new (LAlloc.Allocate()) LayoutInputSection<ELFT>(OutCmd));
239       continue;
240     }
241 
242     auto *Cmd = cast<InputSectionDescription>(Base.get());
243     std::vector<InputSectionBase<ELFT> *> V = getInputSections(Cmd);
244     if (!matchConstraints<ELFT>(V, OutCmd.Constraint))
245       continue;
246     if (Cmd->SortInner)
247       std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortInner));
248     if (Cmd->SortOuter)
249       std::stable_sort(V.begin(), V.end(), getComparator<ELFT>(Cmd->SortOuter));
250     Ret.insert(Ret.end(), V.begin(), V.end());
251   }
252   return Ret;
253 }
254 
255 template <class ELFT>
256 void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
257   for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands) {
258     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
259       if (shouldDefine<ELFT>(Cmd))
260         addRegular<ELFT>(Cmd);
261       continue;
262     }
263 
264     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
265       if (Cmd->Name == "/DISCARD/") {
266         discard(*Cmd);
267         continue;
268       }
269 
270       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
271       InputSectionBase<ELFT> *Head = getNonLayoutSection<ELFT>(V);
272       if (!Head)
273         continue;
274 
275       OutputSectionBase<ELFT> *OutSec;
276       bool IsNew;
277       std::tie(OutSec, IsNew) = Factory.create(Head, Cmd->Name);
278       if (IsNew)
279         OutputSections->push_back(OutSec);
280       for (InputSectionBase<ELFT> *Sec : V)
281         OutSec->addSection(Sec);
282     }
283   }
284 
285   // Add orphan sections.
286   for (const std::unique_ptr<ObjectFile<ELFT>> &F :
287        Symtab<ELFT>::X->getObjectFiles()) {
288     for (InputSectionBase<ELFT> *S : F->getSections()) {
289       if (isDiscarded(S) || S->OutSec)
290         continue;
291       OutputSectionBase<ELFT> *OutSec;
292       bool IsNew;
293       std::tie(OutSec, IsNew) = Factory.create(S, getOutputSectionName(S));
294       if (IsNew)
295         OutputSections->push_back(OutSec);
296       OutSec->addSection(S);
297     }
298   }
299 }
300 
301 template <class ELFT> void assignOffsets(OutputSectionBase<ELFT> *Sec) {
302   auto *OutSec = dyn_cast<OutputSection<ELFT>>(Sec);
303   if (!OutSec) {
304     Sec->assignOffsets();
305     return;
306   }
307 
308   typedef typename ELFT::uint uintX_t;
309   uintX_t Off = 0;
310 
311   for (InputSection<ELFT> *I : OutSec->Sections) {
312     if (auto *L = dyn_cast<LayoutInputSection<ELFT>>(I)) {
313       uintX_t Value = L->Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
314       if (L->Cmd->Name == ".") {
315         Off = Value;
316       } else {
317         auto *Sym = cast<DefinedSynthetic<ELFT>>(L->Cmd->Sym);
318         Sym->Section = OutSec;
319         Sym->Value = Value;
320       }
321     } else {
322       Off = alignTo(Off, I->Alignment);
323       I->OutSecOff = Off;
324       Off += I->getSize();
325     }
326     // Update section size inside for-loop, so that SIZEOF
327     // works correctly in the case below:
328     // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
329     Sec->setSize(Off);
330   }
331 }
332 
333 template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
334   // Orphan sections are sections present in the input files which
335   // are not explicitly placed into the output file by the linker script.
336   // We place orphan sections at end of file.
337   // Other linkers places them using some heuristics as described in
338   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
339   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
340     StringRef Name = Sec->getName();
341     if (getSectionIndex(Name) == INT_MAX)
342       Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
343   }
344 
345   // Assign addresses as instructed by linker script SECTIONS sub-commands.
346   Dot = getHeaderSize();
347   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
348   uintX_t ThreadBssOffset = 0;
349 
350   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
351     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
352       if (Cmd->Name == ".") {
353         Dot = Cmd->Expression(Dot);
354       } else if (Cmd->Sym) {
355         cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
356       }
357       continue;
358     }
359 
360     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
361       Cmd->Expression(Dot);
362       continue;
363     }
364 
365     // Find all the sections with required name. There can be more than
366     // one section with such name, if the alignment, flags or type
367     // attribute differs.
368     auto *Cmd = cast<OutputSectionCommand>(Base.get());
369     for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
370       if (Sec->getName() != Cmd->Name)
371         continue;
372 
373       if (Cmd->AddrExpr)
374         Dot = Cmd->AddrExpr(Dot);
375 
376       if (Cmd->AlignExpr)
377         Sec->updateAlignment(Cmd->AlignExpr(Dot));
378 
379       if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
380         uintX_t TVA = Dot + ThreadBssOffset;
381         TVA = alignTo(TVA, Sec->getAlignment());
382         Sec->setVA(TVA);
383         assignOffsets(Sec);
384         ThreadBssOffset = TVA - Dot + Sec->getSize();
385         continue;
386       }
387 
388       if (Sec->getFlags() & SHF_ALLOC) {
389         Dot = alignTo(Dot, Sec->getAlignment());
390         Sec->setVA(Dot);
391         assignOffsets(Sec);
392         MinVA = std::min(MinVA, Dot);
393         Dot += Sec->getSize();
394         continue;
395       }
396       Sec->assignOffsets();
397     }
398   }
399 
400   // ELF and Program headers need to be right before the first section in
401   // memory. Set their addresses accordingly.
402   MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
403                         Out<ELFT>::ProgramHeaders->getSize(),
404                     Target->PageSize);
405   Out<ELFT>::ElfHeader->setVA(MinVA);
406   Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
407 }
408 
409 template <class ELFT>
410 std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
411   ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
412   std::vector<PhdrEntry<ELFT>> Ret;
413 
414   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
415     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
416     PhdrEntry<ELFT> &Phdr = Ret.back();
417 
418     if (Cmd.HasFilehdr)
419       Phdr.add(Out<ELFT>::ElfHeader);
420     if (Cmd.HasPhdrs)
421       Phdr.add(Out<ELFT>::ProgramHeaders);
422 
423     switch (Cmd.Type) {
424     case PT_INTERP:
425       if (Out<ELFT>::Interp)
426         Phdr.add(Out<ELFT>::Interp);
427       break;
428     case PT_DYNAMIC:
429       if (Out<ELFT>::DynSymTab) {
430         Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
431         Phdr.add(Out<ELFT>::Dynamic);
432       }
433       break;
434     case PT_GNU_EH_FRAME:
435       if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
436         Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
437         Phdr.add(Out<ELFT>::EhFrameHdr);
438       }
439       break;
440     }
441   }
442 
443   PhdrEntry<ELFT> *Load = nullptr;
444   uintX_t Flags = PF_R;
445   for (OutputSectionBase<ELFT> *Sec : Sections) {
446     if (!(Sec->getFlags() & SHF_ALLOC))
447       break;
448 
449     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
450     if (!PhdrIds.empty()) {
451       // Assign headers specified by linker script
452       for (size_t Id : PhdrIds) {
453         Ret[Id].add(Sec);
454         if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
455           Ret[Id].H.p_flags |= Sec->getPhdrFlags();
456       }
457     } else {
458       // If we have no load segment or flags've changed then we want new load
459       // segment.
460       uintX_t NewFlags = Sec->getPhdrFlags();
461       if (Load == nullptr || Flags != NewFlags) {
462         Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
463         Flags = NewFlags;
464       }
465       Load->add(Sec);
466     }
467   }
468   return Ret;
469 }
470 
471 template <class ELFT>
472 ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
473   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
474     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
475       if (Cmd->Name == Name)
476         return Cmd->Filler;
477   return {};
478 }
479 
480 // Returns the index of the given section name in linker script
481 // SECTIONS commands. Sections are laid out as the same order as they
482 // were in the script. If a given name did not appear in the script,
483 // it returns INT_MAX, so that it will be laid out at end of file.
484 template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
485   int I = 0;
486   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
487     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
488       if (Cmd->Name == Name)
489         return I;
490     ++I;
491   }
492   return INT_MAX;
493 }
494 
495 // A compartor to sort output sections. Returns -1 or 1 if
496 // A or B are mentioned in linker script. Otherwise, returns 0.
497 template <class ELFT>
498 int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
499   int I = getSectionIndex(A);
500   int J = getSectionIndex(B);
501   if (I == INT_MAX && J == INT_MAX)
502     return 0;
503   return I < J ? -1 : 1;
504 }
505 
506 template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
507   return !Opt.PhdrsCommands.empty();
508 }
509 
510 template <class ELFT>
511 typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
512   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
513     if (Sec->getName() == Name)
514       return Sec->getSize();
515   error("undefined section " + Name);
516   return 0;
517 }
518 
519 template <class ELFT>
520 typename ELFT::uint LinkerScript<ELFT>::getHeaderSize() {
521   return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
522 }
523 
524 // Returns indices of ELF headers containing specific section, identified
525 // by Name. Each index is a zero based number of ELF header listed within
526 // PHDRS {} script block.
527 template <class ELFT>
528 std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
529   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
530     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
531     if (!Cmd || Cmd->Name != SectionName)
532       continue;
533 
534     std::vector<size_t> Ret;
535     for (StringRef PhdrName : Cmd->Phdrs)
536       Ret.push_back(getPhdrIndex(PhdrName));
537     return Ret;
538   }
539   return {};
540 }
541 
542 template <class ELFT>
543 size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
544   size_t I = 0;
545   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
546     if (Cmd.Name == PhdrName)
547       return I;
548     ++I;
549   }
550   error("section header '" + PhdrName + "' is not listed in PHDRS");
551   return 0;
552 }
553 
554 class elf::ScriptParser : public ScriptParserBase {
555   typedef void (ScriptParser::*Handler)();
556 
557 public:
558   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
559 
560   void run();
561 
562 private:
563   void addFile(StringRef Path);
564 
565   void readAsNeeded();
566   void readEntry();
567   void readExtern();
568   void readGroup();
569   void readInclude();
570   void readNothing() {}
571   void readOutput();
572   void readOutputArch();
573   void readOutputFormat();
574   void readPhdrs();
575   void readSearchDir();
576   void readSections();
577 
578   SymbolAssignment *readAssignment(StringRef Name);
579   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
580   std::vector<uint8_t> readOutputSectionFiller();
581   std::vector<StringRef> readOutputSectionPhdrs();
582   InputSectionDescription *readInputSectionDescription();
583   std::vector<StringRef> readInputFilePatterns();
584   InputSectionDescription *readInputSectionRules();
585   unsigned readPhdrType();
586   SortKind readSortKind();
587   SymbolAssignment *readProvide(bool Hidden);
588   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
589   Expr readAlign();
590   void readSort();
591   Expr readAssert();
592 
593   Expr readExpr();
594   Expr readExpr1(Expr Lhs, int MinPrec);
595   Expr readPrimary();
596   Expr readTernary(Expr Cond);
597 
598   const static StringMap<Handler> Cmd;
599   ScriptConfiguration &Opt = *ScriptConfig;
600   StringSaver Saver = {ScriptConfig->Alloc};
601   bool IsUnderSysroot;
602 };
603 
604 const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
605     {"ENTRY", &ScriptParser::readEntry},
606     {"EXTERN", &ScriptParser::readExtern},
607     {"GROUP", &ScriptParser::readGroup},
608     {"INCLUDE", &ScriptParser::readInclude},
609     {"INPUT", &ScriptParser::readGroup},
610     {"OUTPUT", &ScriptParser::readOutput},
611     {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
612     {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
613     {"PHDRS", &ScriptParser::readPhdrs},
614     {"SEARCH_DIR", &ScriptParser::readSearchDir},
615     {"SECTIONS", &ScriptParser::readSections},
616     {";", &ScriptParser::readNothing}};
617 
618 void ScriptParser::run() {
619   while (!atEOF()) {
620     StringRef Tok = next();
621     if (Handler Fn = Cmd.lookup(Tok))
622       (this->*Fn)();
623     else
624       setError("unknown directive: " + Tok);
625   }
626 }
627 
628 void ScriptParser::addFile(StringRef S) {
629   if (IsUnderSysroot && S.startswith("/")) {
630     SmallString<128> Path;
631     (Config->Sysroot + S).toStringRef(Path);
632     if (sys::fs::exists(Path)) {
633       Driver->addFile(Saver.save(Path.str()));
634       return;
635     }
636   }
637 
638   if (sys::path::is_absolute(S)) {
639     Driver->addFile(S);
640   } else if (S.startswith("=")) {
641     if (Config->Sysroot.empty())
642       Driver->addFile(S.substr(1));
643     else
644       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
645   } else if (S.startswith("-l")) {
646     Driver->addLibrary(S.substr(2));
647   } else if (sys::fs::exists(S)) {
648     Driver->addFile(S);
649   } else {
650     std::string Path = findFromSearchPaths(S);
651     if (Path.empty())
652       setError("unable to find " + S);
653     else
654       Driver->addFile(Saver.save(Path));
655   }
656 }
657 
658 void ScriptParser::readAsNeeded() {
659   expect("(");
660   bool Orig = Config->AsNeeded;
661   Config->AsNeeded = true;
662   while (!Error && !skip(")"))
663     addFile(next());
664   Config->AsNeeded = Orig;
665 }
666 
667 void ScriptParser::readEntry() {
668   // -e <symbol> takes predecence over ENTRY(<symbol>).
669   expect("(");
670   StringRef Tok = next();
671   if (Config->Entry.empty())
672     Config->Entry = Tok;
673   expect(")");
674 }
675 
676 void ScriptParser::readExtern() {
677   expect("(");
678   while (!Error && !skip(")"))
679     Config->Undefined.push_back(next());
680 }
681 
682 void ScriptParser::readGroup() {
683   expect("(");
684   while (!Error && !skip(")")) {
685     StringRef Tok = next();
686     if (Tok == "AS_NEEDED")
687       readAsNeeded();
688     else
689       addFile(Tok);
690   }
691 }
692 
693 void ScriptParser::readInclude() {
694   StringRef Tok = next();
695   auto MBOrErr = MemoryBuffer::getFile(Tok);
696   if (!MBOrErr) {
697     setError("cannot open " + Tok);
698     return;
699   }
700   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
701   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
702   std::vector<StringRef> V = tokenize(S);
703   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
704 }
705 
706 void ScriptParser::readOutput() {
707   // -o <file> takes predecence over OUTPUT(<file>).
708   expect("(");
709   StringRef Tok = next();
710   if (Config->OutputFile.empty())
711     Config->OutputFile = Tok;
712   expect(")");
713 }
714 
715 void ScriptParser::readOutputArch() {
716   // Error checking only for now.
717   expect("(");
718   next();
719   expect(")");
720 }
721 
722 void ScriptParser::readOutputFormat() {
723   // Error checking only for now.
724   expect("(");
725   next();
726   StringRef Tok = next();
727   if (Tok == ")")
728    return;
729   if (Tok != ",") {
730     setError("unexpected token: " + Tok);
731     return;
732   }
733   next();
734   expect(",");
735   next();
736   expect(")");
737 }
738 
739 void ScriptParser::readPhdrs() {
740   expect("{");
741   while (!Error && !skip("}")) {
742     StringRef Tok = next();
743     Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
744     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
745 
746     PhdrCmd.Type = readPhdrType();
747     do {
748       Tok = next();
749       if (Tok == ";")
750         break;
751       if (Tok == "FILEHDR")
752         PhdrCmd.HasFilehdr = true;
753       else if (Tok == "PHDRS")
754         PhdrCmd.HasPhdrs = true;
755       else if (Tok == "FLAGS") {
756         expect("(");
757         // Passing 0 for the value of dot is a bit of a hack. It means that
758         // we accept expressions like ".|1".
759         PhdrCmd.Flags = readExpr()(0);
760         expect(")");
761       } else
762         setError("unexpected header attribute: " + Tok);
763     } while (!Error);
764   }
765 }
766 
767 void ScriptParser::readSearchDir() {
768   expect("(");
769   Config->SearchPaths.push_back(next());
770   expect(")");
771 }
772 
773 void ScriptParser::readSections() {
774   Opt.HasContents = true;
775   expect("{");
776   while (!Error && !skip("}")) {
777     StringRef Tok = next();
778     BaseCommand *Cmd = readProvideOrAssignment(Tok);
779     if (!Cmd) {
780       if (Tok == "ASSERT")
781         Cmd = new AssertCommand(readAssert());
782       else
783         Cmd = readOutputSectionDescription(Tok);
784     }
785     Opt.Commands.emplace_back(Cmd);
786   }
787 }
788 
789 static int precedence(StringRef Op) {
790   return StringSwitch<int>(Op)
791       .Case("*", 4)
792       .Case("/", 4)
793       .Case("+", 3)
794       .Case("-", 3)
795       .Case("<", 2)
796       .Case(">", 2)
797       .Case(">=", 2)
798       .Case("<=", 2)
799       .Case("==", 2)
800       .Case("!=", 2)
801       .Case("&", 1)
802       .Default(-1);
803 }
804 
805 std::vector<StringRef> ScriptParser::readInputFilePatterns() {
806   std::vector<StringRef> V;
807   while (!Error && !skip(")"))
808     V.push_back(next());
809   return V;
810 }
811 
812 SortKind ScriptParser::readSortKind() {
813   if (skip("SORT") || skip("SORT_BY_NAME"))
814     return SortByName;
815   if (skip("SORT_BY_ALIGNMENT"))
816     return SortByAlignment;
817   return SortNone;
818 }
819 
820 InputSectionDescription *ScriptParser::readInputSectionRules() {
821   auto *Cmd = new InputSectionDescription;
822   Cmd->FilePattern = next();
823   expect("(");
824 
825   // Read EXCLUDE_FILE().
826   if (skip("EXCLUDE_FILE")) {
827     expect("(");
828     while (!Error && !skip(")"))
829       Cmd->ExcludedFiles.push_back(next());
830   }
831 
832   // Read SORT().
833   if (SortKind K1 = readSortKind()) {
834     Cmd->SortOuter = K1;
835     expect("(");
836     if (SortKind K2 = readSortKind()) {
837       Cmd->SortInner = K2;
838       expect("(");
839       Cmd->SectionPatterns = readInputFilePatterns();
840       expect(")");
841     } else {
842       Cmd->SectionPatterns = readInputFilePatterns();
843     }
844     expect(")");
845     return Cmd;
846   }
847 
848   Cmd->SectionPatterns = readInputFilePatterns();
849   return Cmd;
850 }
851 
852 InputSectionDescription *ScriptParser::readInputSectionDescription() {
853   // Input section wildcard can be surrounded by KEEP.
854   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
855   if (skip("KEEP")) {
856     expect("(");
857     InputSectionDescription *Cmd = readInputSectionRules();
858     expect(")");
859     Opt.KeptSections.insert(Opt.KeptSections.end(),
860                             Cmd->SectionPatterns.begin(),
861                             Cmd->SectionPatterns.end());
862     return Cmd;
863   }
864   return readInputSectionRules();
865 }
866 
867 Expr ScriptParser::readAlign() {
868   expect("(");
869   Expr E = readExpr();
870   expect(")");
871   return E;
872 }
873 
874 void ScriptParser::readSort() {
875   expect("(");
876   expect("CONSTRUCTORS");
877   expect(")");
878 }
879 
880 Expr ScriptParser::readAssert() {
881   expect("(");
882   Expr E = readExpr();
883   expect(",");
884   StringRef Msg = next();
885   expect(")");
886   return [=](uint64_t Dot) {
887     uint64_t V = E(Dot);
888     if (!V)
889       error(Msg);
890     return V;
891   };
892 }
893 
894 OutputSectionCommand *
895 ScriptParser::readOutputSectionDescription(StringRef OutSec) {
896   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
897 
898   // Read an address expression.
899   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
900   if (peek() != ":")
901     Cmd->AddrExpr = readExpr();
902 
903   expect(":");
904 
905   if (skip("ALIGN"))
906     Cmd->AlignExpr = readAlign();
907 
908   // Parse constraints.
909   if (skip("ONLY_IF_RO"))
910     Cmd->Constraint = ConstraintKind::ReadOnly;
911   if (skip("ONLY_IF_RW"))
912     Cmd->Constraint = ConstraintKind::ReadWrite;
913   expect("{");
914 
915   while (!Error && !skip("}")) {
916     if (peek().startswith("*") || peek() == "KEEP") {
917       Cmd->Commands.emplace_back(readInputSectionDescription());
918       continue;
919     }
920 
921     StringRef Tok = next();
922     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
923       Cmd->Commands.emplace_back(Assignment);
924     else if (Tok == "SORT")
925       readSort();
926     else
927       setError("unknown command " + Tok);
928   }
929   Cmd->Phdrs = readOutputSectionPhdrs();
930   Cmd->Filler = readOutputSectionFiller();
931   return Cmd;
932 }
933 
934 std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
935   StringRef Tok = peek();
936   if (!Tok.startswith("="))
937     return {};
938   next();
939 
940   // Read a hexstring of arbitrary length.
941   if (Tok.startswith("=0x"))
942     return parseHex(Tok.substr(3));
943 
944   // Read a decimal or octal value as a big-endian 32 bit value.
945   // Why do this? I don't know, but that's what gold does.
946   uint32_t V;
947   if (Tok.substr(1).getAsInteger(0, V)) {
948     setError("invalid filler expression: " + Tok);
949     return {};
950   }
951   return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
952 }
953 
954 SymbolAssignment *ScriptParser::readProvide(bool Hidden) {
955   expect("(");
956   SymbolAssignment *Cmd = readAssignment(next());
957   Cmd->Provide = true;
958   Cmd->Hidden = Hidden;
959   expect(")");
960   expect(";");
961   return Cmd;
962 }
963 
964 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
965   SymbolAssignment *Cmd = nullptr;
966   if (peek() == "=" || peek() == "+=") {
967     Cmd = readAssignment(Tok);
968     expect(";");
969   } else if (Tok == "PROVIDE") {
970     Cmd = readProvide(false);
971   } else if (Tok == "PROVIDE_HIDDEN") {
972     Cmd = readProvide(true);
973   }
974   return Cmd;
975 }
976 
977 static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
978   if (S == ".")
979     return Dot;
980 
981   switch (Config->EKind) {
982   case ELF32LEKind:
983     if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
984       return B->getVA<ELF32LE>();
985     break;
986   case ELF32BEKind:
987     if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
988       return B->getVA<ELF32BE>();
989     break;
990   case ELF64LEKind:
991     if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
992       return B->getVA<ELF64LE>();
993     break;
994   case ELF64BEKind:
995     if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
996       return B->getVA<ELF64BE>();
997     break;
998   default:
999     llvm_unreachable("unsupported target");
1000   }
1001   error("symbol not found: " + S);
1002   return 0;
1003 }
1004 
1005 static uint64_t getSectionSize(StringRef Name) {
1006   switch (Config->EKind) {
1007   case ELF32LEKind:
1008     return Script<ELF32LE>::X->getOutputSectionSize(Name);
1009   case ELF32BEKind:
1010     return Script<ELF32BE>::X->getOutputSectionSize(Name);
1011   case ELF64LEKind:
1012     return Script<ELF64LE>::X->getOutputSectionSize(Name);
1013   case ELF64BEKind:
1014     return Script<ELF64BE>::X->getOutputSectionSize(Name);
1015   default:
1016     llvm_unreachable("unsupported target");
1017   }
1018 }
1019 
1020 static uint64_t getHeaderSize() {
1021   switch (Config->EKind) {
1022   case ELF32LEKind:
1023     return Script<ELF32LE>::X->getHeaderSize();
1024   case ELF32BEKind:
1025     return Script<ELF32BE>::X->getHeaderSize();
1026   case ELF64LEKind:
1027     return Script<ELF64LE>::X->getHeaderSize();
1028   case ELF64BEKind:
1029     return Script<ELF64BE>::X->getHeaderSize();
1030   default:
1031     llvm_unreachable("unsupported target");
1032   }
1033 }
1034 
1035 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1036   StringRef Op = next();
1037   assert(Op == "=" || Op == "+=");
1038   Expr E = readExpr();
1039   if (Op == "+=")
1040     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1041   return new SymbolAssignment(Name, E);
1042 }
1043 
1044 // This is an operator-precedence parser to parse a linker
1045 // script expression.
1046 Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1047 
1048 static Expr combine(StringRef Op, Expr L, Expr R) {
1049   if (Op == "*")
1050     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1051   if (Op == "/") {
1052     return [=](uint64_t Dot) -> uint64_t {
1053       uint64_t RHS = R(Dot);
1054       if (RHS == 0) {
1055         error("division by zero");
1056         return 0;
1057       }
1058       return L(Dot) / RHS;
1059     };
1060   }
1061   if (Op == "+")
1062     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1063   if (Op == "-")
1064     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1065   if (Op == "<")
1066     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1067   if (Op == ">")
1068     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1069   if (Op == ">=")
1070     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1071   if (Op == "<=")
1072     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1073   if (Op == "==")
1074     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1075   if (Op == "!=")
1076     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1077   if (Op == "&")
1078     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1079   llvm_unreachable("invalid operator");
1080 }
1081 
1082 // This is a part of the operator-precedence parser. This function
1083 // assumes that the remaining token stream starts with an operator.
1084 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1085   while (!atEOF() && !Error) {
1086     // Read an operator and an expression.
1087     StringRef Op1 = peek();
1088     if (Op1 == "?")
1089       return readTernary(Lhs);
1090     if (precedence(Op1) < MinPrec)
1091       break;
1092     next();
1093     Expr Rhs = readPrimary();
1094 
1095     // Evaluate the remaining part of the expression first if the
1096     // next operator has greater precedence than the previous one.
1097     // For example, if we have read "+" and "3", and if the next
1098     // operator is "*", then we'll evaluate 3 * ... part first.
1099     while (!atEOF()) {
1100       StringRef Op2 = peek();
1101       if (precedence(Op2) <= precedence(Op1))
1102         break;
1103       Rhs = readExpr1(Rhs, precedence(Op2));
1104     }
1105 
1106     Lhs = combine(Op1, Lhs, Rhs);
1107   }
1108   return Lhs;
1109 }
1110 
1111 uint64_t static getConstant(StringRef S) {
1112   if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
1113     return Target->PageSize;
1114   error("unknown constant: " + S);
1115   return 0;
1116 }
1117 
1118 Expr ScriptParser::readPrimary() {
1119   StringRef Tok = next();
1120 
1121   if (Tok == "(") {
1122     Expr E = readExpr();
1123     expect(")");
1124     return E;
1125   }
1126 
1127   // Built-in functions are parsed here.
1128   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1129   if (Tok == "ASSERT")
1130     return readAssert();
1131   if (Tok == "ALIGN") {
1132     expect("(");
1133     Expr E = readExpr();
1134     expect(")");
1135     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1136   }
1137   if (Tok == "CONSTANT") {
1138     expect("(");
1139     StringRef Tok = next();
1140     expect(")");
1141     return [=](uint64_t Dot) { return getConstant(Tok); };
1142   }
1143   if (Tok == "SEGMENT_START") {
1144     expect("(");
1145     next();
1146     expect(",");
1147     uint64_t Val;
1148     next().getAsInteger(0, Val);
1149     expect(")");
1150     return [=](uint64_t Dot) { return Val; };
1151   }
1152   if (Tok == "DATA_SEGMENT_ALIGN") {
1153     expect("(");
1154     Expr E = readExpr();
1155     expect(",");
1156     readExpr();
1157     expect(")");
1158     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1159   }
1160   if (Tok == "DATA_SEGMENT_END") {
1161     expect("(");
1162     expect(".");
1163     expect(")");
1164     return [](uint64_t Dot) { return Dot; };
1165   }
1166   // GNU linkers implements more complicated logic to handle
1167   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1168   // the next page boundary for simplicity.
1169   if (Tok == "DATA_SEGMENT_RELRO_END") {
1170     expect("(");
1171     next();
1172     expect(",");
1173     readExpr();
1174     expect(")");
1175     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1176   }
1177   if (Tok == "SIZEOF") {
1178     expect("(");
1179     StringRef Name = next();
1180     expect(")");
1181     return [=](uint64_t Dot) { return getSectionSize(Name); };
1182   }
1183   if (Tok == "SIZEOF_HEADERS")
1184     return [=](uint64_t Dot) { return getHeaderSize(); };
1185 
1186   // Parse a symbol name or a number literal.
1187   uint64_t V = 0;
1188   if (Tok.getAsInteger(0, V)) {
1189     if (Tok != "." && !isValidCIdentifier(Tok))
1190       setError("malformed number: " + Tok);
1191     return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
1192   }
1193   return [=](uint64_t Dot) { return V; };
1194 }
1195 
1196 Expr ScriptParser::readTernary(Expr Cond) {
1197   next();
1198   Expr L = readExpr();
1199   expect(":");
1200   Expr R = readExpr();
1201   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1202 }
1203 
1204 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1205   std::vector<StringRef> Phdrs;
1206   while (!Error && peek().startswith(":")) {
1207     StringRef Tok = next();
1208     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1209     if (Tok.empty()) {
1210       setError("section header name is empty");
1211       break;
1212     }
1213     Phdrs.push_back(Tok);
1214   }
1215   return Phdrs;
1216 }
1217 
1218 unsigned ScriptParser::readPhdrType() {
1219   StringRef Tok = next();
1220   unsigned Ret = StringSwitch<unsigned>(Tok)
1221       .Case("PT_NULL", PT_NULL)
1222       .Case("PT_LOAD", PT_LOAD)
1223       .Case("PT_DYNAMIC", PT_DYNAMIC)
1224       .Case("PT_INTERP", PT_INTERP)
1225       .Case("PT_NOTE", PT_NOTE)
1226       .Case("PT_SHLIB", PT_SHLIB)
1227       .Case("PT_PHDR", PT_PHDR)
1228       .Case("PT_TLS", PT_TLS)
1229       .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1230       .Case("PT_GNU_STACK", PT_GNU_STACK)
1231       .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1232       .Default(-1);
1233 
1234   if (Ret == (unsigned)-1) {
1235     setError("invalid program header type: " + Tok);
1236     return PT_NULL;
1237   }
1238   return Ret;
1239 }
1240 
1241 static bool isUnderSysroot(StringRef Path) {
1242   if (Config->Sysroot == "")
1243     return false;
1244   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1245     if (sys::fs::equivalent(Config->Sysroot, Path))
1246       return true;
1247   return false;
1248 }
1249 
1250 // Entry point.
1251 void elf::readLinkerScript(MemoryBufferRef MB) {
1252   StringRef Path = MB.getBufferIdentifier();
1253   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
1254 }
1255 
1256 template class elf::LinkerScript<ELF32LE>;
1257 template class elf::LinkerScript<ELF32BE>;
1258 template class elf::LinkerScript<ELF64LE>;
1259 template class elf::LinkerScript<ELF64BE>;
1260