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