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