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 "Memory.h"
25 #include "OutputSections.h"
26 #include "ScriptParser.h"
27 #include "Strings.h"
28 #include "SymbolTable.h"
29 #include "Symbols.h"
30 #include "Target.h"
31 #include "Writer.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/ADT/StringSwitch.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/ELF.h"
38 #include "llvm/Support/Endian.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include <algorithm>
45 #include <cassert>
46 #include <cstddef>
47 #include <cstdint>
48 #include <iterator>
49 #include <limits>
50 #include <memory>
51 #include <string>
52 #include <tuple>
53 #include <vector>
54 
55 using namespace llvm;
56 using namespace llvm::ELF;
57 using namespace llvm::object;
58 using namespace llvm::support::endian;
59 using namespace lld;
60 using namespace lld::elf;
61 
62 LinkerScriptBase *elf::ScriptBase;
63 ScriptConfiguration *elf::ScriptConfig;
64 
65 template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
66   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
67   Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, Visibility, STT_NOTYPE,
68                                             0, 0, STB_GLOBAL, nullptr);
69   Cmd->Sym = Sym->body();
70 
71   // If we have no SECTIONS then we don't have '.' and don't call
72   // assignAddresses(). We calculate symbol value immediately in this case.
73   if (!ScriptConfig->HasSections)
74     cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
75 }
76 
77 template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
78   Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
79       Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
80   Cmd->Sym = Sym->body();
81 }
82 
83 template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
84   if (Cmd->Expression.IsAbsolute())
85     addRegular<ELFT>(Cmd);
86   else
87     addSynthetic<ELFT>(Cmd);
88 }
89 // If a symbol was in PROVIDE(), we need to define it only when
90 // it is an undefined symbol.
91 template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
92   if (Cmd->Name == ".")
93     return false;
94   if (!Cmd->Provide)
95     return true;
96   SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
97   return B && B->isUndefined();
98 }
99 
100 bool SymbolAssignment::classof(const BaseCommand *C) {
101   return C->Kind == AssignmentKind;
102 }
103 
104 bool OutputSectionCommand::classof(const BaseCommand *C) {
105   return C->Kind == OutputSectionKind;
106 }
107 
108 bool InputSectionDescription::classof(const BaseCommand *C) {
109   return C->Kind == InputSectionKind;
110 }
111 
112 bool AssertCommand::classof(const BaseCommand *C) {
113   return C->Kind == AssertKind;
114 }
115 
116 bool BytesDataCommand::classof(const BaseCommand *C) {
117   return C->Kind == BytesDataKind;
118 }
119 
120 template <class ELFT> LinkerScript<ELFT>::LinkerScript() = default;
121 template <class ELFT> LinkerScript<ELFT>::~LinkerScript() = default;
122 
123 template <class ELFT>
124 bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
125   for (InputSectionDescription *ID : Opt.KeptSections) {
126     StringRef Filename = S->getFile()->getName();
127     if (!ID->FilePat.match(sys::path::filename(Filename)))
128       continue;
129 
130     for (SectionPattern &P : ID->SectionPatterns)
131       if (P.SectionPat.match(S->Name))
132         return true;
133   }
134   return false;
135 }
136 
137 static bool comparePriority(InputSectionData *A, InputSectionData *B) {
138   return getPriority(A->Name) < getPriority(B->Name);
139 }
140 
141 static bool compareName(InputSectionData *A, InputSectionData *B) {
142   return A->Name < B->Name;
143 }
144 
145 static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
146   // ">" is not a mistake. Larger alignments are placed before smaller
147   // alignments in order to reduce the amount of padding necessary.
148   // This is compatible with GNU.
149   return A->Alignment > B->Alignment;
150 }
151 
152 static std::function<bool(InputSectionData *, InputSectionData *)>
153 getComparator(SortSectionPolicy K) {
154   switch (K) {
155   case SortSectionPolicy::Alignment:
156     return compareAlignment;
157   case SortSectionPolicy::Name:
158     return compareName;
159   case SortSectionPolicy::Priority:
160     return comparePriority;
161   default:
162     llvm_unreachable("unknown sort policy");
163   }
164 }
165 
166 template <class ELFT>
167 static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
168                              ConstraintKind Kind) {
169   if (Kind == ConstraintKind::NoConstraint)
170     return true;
171   bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
172     auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
173     return Sec->Flags & SHF_WRITE;
174   });
175   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
176          (!IsRW && Kind == ConstraintKind::ReadOnly);
177 }
178 
179 static void sortSections(InputSectionData **Begin, InputSectionData **End,
180                          SortSectionPolicy K) {
181   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
182     std::stable_sort(Begin, End, getComparator(K));
183 }
184 
185 // Compute and remember which sections the InputSectionDescription matches.
186 template <class ELFT>
187 void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
188   // Collects all sections that satisfy constraints of I
189   // and attach them to I.
190   for (SectionPattern &Pat : I->SectionPatterns) {
191     size_t SizeBefore = I->Sections.size();
192 
193     for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections) {
194       if (!S->Live || S->OutSec)
195         continue;
196 
197       StringRef Filename;
198       if (elf::ObjectFile<ELFT> *F = S->getFile())
199         Filename = sys::path::filename(F->getName());
200 
201       if (I->FilePat.match(Filename) && !Pat.ExcludedFilePat.match(Filename) &&
202           Pat.SectionPat.match(S->Name))
203         I->Sections.push_back(S);
204     }
205 
206     // Sort sections as instructed by SORT-family commands and --sort-section
207     // option. Because SORT-family commands can be nested at most two depth
208     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
209     // line option is respected even if a SORT command is given, the exact
210     // behavior we have here is a bit complicated. Here are the rules.
211     //
212     // 1. If two SORT commands are given, --sort-section is ignored.
213     // 2. If one SORT command is given, and if it is not SORT_NONE,
214     //    --sort-section is handled as an inner SORT command.
215     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
216     // 4. If no SORT command is given, sort according to --sort-section.
217     InputSectionData **Begin = I->Sections.data() + SizeBefore;
218     InputSectionData **End = I->Sections.data() + I->Sections.size();
219     if (Pat.SortOuter != SortSectionPolicy::None) {
220       if (Pat.SortInner == SortSectionPolicy::Default)
221         sortSections(Begin, End, Config->SortSection);
222       else
223         sortSections(Begin, End, Pat.SortInner);
224       sortSections(Begin, End, Pat.SortOuter);
225     }
226   }
227 
228   // We do not add duplicate input sections, so mark them with a dummy output
229   // section for now.
230   for (InputSectionData *S : I->Sections) {
231     auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
232     S2->OutSec = (OutputSectionBase *)-1;
233   }
234 }
235 
236 template <class ELFT>
237 void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
238   for (InputSectionBase<ELFT> *S : V) {
239     S->Live = false;
240     reportDiscarded(S);
241   }
242 }
243 
244 template <class ELFT>
245 std::vector<InputSectionBase<ELFT> *>
246 LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
247   std::vector<InputSectionBase<ELFT> *> Ret;
248 
249   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
250     auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
251     if (!Cmd)
252       continue;
253     computeInputSections(Cmd);
254     for (InputSectionData *S : Cmd->Sections)
255       Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
256   }
257 
258   // After we created final list we should now set OutSec pointer to null,
259   // instead of -1. Otherwise we may get a crash when writing relocs, in
260   // case section is discarded by linker script
261   for (InputSectionBase<ELFT> *S : Ret)
262     S->OutSec = nullptr;
263 
264   return Ret;
265 }
266 
267 template <class ELFT>
268 static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
269                                             StringRef OutsecName) {
270   // When using linker script the merge rules are different.
271   // Unfortunately, linker scripts are name based. This means that expressions
272   // like *(.foo*) can refer to multiple input sections that would normally be
273   // placed in different output sections. We cannot put them in different
274   // output sections or we would produce wrong results for
275   // start = .; *(.foo.*) end = .; *(.bar)
276   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
277   // another. The problem is that there is no way to layout those output
278   // sections such that the .foo sections are the only thing between the
279   // start and end symbols.
280 
281   // An extra annoyance is that we cannot simply disable merging of the contents
282   // of SHF_MERGE sections, but our implementation requires one output section
283   // per "kind" (string or not, which size/aligment).
284   // Fortunately, creating symbols in the middle of a merge section is not
285   // supported by bfd or gold, so we can just create multiple section in that
286   // case.
287   typedef typename ELFT::uint uintX_t;
288   uintX_t Flags = C->Flags & (SHF_MERGE | SHF_STRINGS);
289 
290   uintX_t Alignment = 0;
291   if (isa<MergeInputSection<ELFT>>(C))
292     Alignment = std::max<uintX_t>(C->Alignment, C->Entsize);
293 
294   return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
295 }
296 
297 template <class ELFT>
298 void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
299                                     InputSectionBase<ELFT> *Sec,
300                                     StringRef Name) {
301   OutputSectionBase *OutSec;
302   bool IsNew;
303   std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
304   if (IsNew)
305     OutputSections->push_back(OutSec);
306   OutSec->addSection(Sec);
307 }
308 
309 template <class ELFT>
310 void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
311   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
312     auto Iter = Opt.Commands.begin() + I;
313     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
314     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
315       if (shouldDefine<ELFT>(Cmd))
316         addSymbol<ELFT>(Cmd);
317       continue;
318     }
319     if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
320       // If we don't have SECTIONS then output sections have already been
321       // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
322       // will not be called, so ASSERT should be evaluated now.
323       if (!Opt.HasSections)
324         Cmd->Expression(0);
325       continue;
326     }
327 
328     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
329       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
330 
331       if (Cmd->Name == "/DISCARD/") {
332         discard(V);
333         continue;
334       }
335 
336       if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
337         for (InputSectionBase<ELFT> *S : V)
338           S->OutSec = nullptr;
339         Opt.Commands.erase(Iter);
340         --I;
341         continue;
342       }
343 
344       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
345         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
346           if (shouldDefine<ELFT>(OutCmd))
347             addSymbol<ELFT>(OutCmd);
348 
349       if (V.empty())
350         continue;
351 
352       for (InputSectionBase<ELFT> *Sec : V) {
353         addSection(Factory, Sec, Cmd->Name);
354         if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
355           Sec->Alignment = Subalign;
356       }
357     }
358   }
359 }
360 
361 template <class ELFT>
362 void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
363   processCommands(Factory);
364 
365   // Add orphan sections.
366   for (InputSectionBase<ELFT> *S : Symtab<ELFT>::X->Sections)
367     if (S->Live && !S->OutSec)
368       addSection(Factory, S, getOutputSectionName(S->Name));
369 }
370 
371 // Sets value of a section-defined symbol. Two kinds of
372 // symbols are processed: synthetic symbols, whose value
373 // is an offset from beginning of section and regular
374 // symbols whose value is absolute.
375 template <class ELFT>
376 static void assignSectionSymbol(SymbolAssignment *Cmd, OutputSectionBase *Sec,
377                                 typename ELFT::uint Value) {
378   if (!Cmd->Sym)
379     return;
380 
381   if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
382     Body->Section = Sec;
383     Body->Value = Cmd->Expression(Value) - Sec->Addr;
384     return;
385   }
386   auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
387   Body->Value = Cmd->Expression(Value);
388 }
389 
390 template <class ELFT> static bool isTbss(OutputSectionBase *Sec) {
391   return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
392 }
393 
394 template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
395   if (!AlreadyOutputIS.insert(S).second)
396     return;
397   bool IsTbss = isTbss<ELFT>(CurOutSec);
398 
399   uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
400   Pos = alignTo(Pos, S->Alignment);
401   S->OutSecOff = Pos - CurOutSec->Addr;
402   Pos += S->getSize();
403 
404   // Update output section size after adding each section. This is so that
405   // SIZEOF works correctly in the case below:
406   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
407   CurOutSec->Size = Pos - CurOutSec->Addr;
408 
409   if (IsTbss)
410     ThreadBssOffset = Pos - Dot;
411   else
412     Dot = Pos;
413 }
414 
415 template <class ELFT> void LinkerScript<ELFT>::flush() {
416   if (!CurOutSec || !AlreadyOutputOS.insert(CurOutSec).second)
417     return;
418   if (auto *OutSec = dyn_cast<OutputSection<ELFT>>(CurOutSec)) {
419     for (InputSection<ELFT> *I : OutSec->Sections)
420       output(I);
421   } else {
422     Dot += CurOutSec->Size;
423   }
424 }
425 
426 template <class ELFT>
427 void LinkerScript<ELFT>::switchTo(OutputSectionBase *Sec) {
428   if (CurOutSec == Sec)
429     return;
430   if (AlreadyOutputOS.count(Sec))
431     return;
432 
433   flush();
434   CurOutSec = Sec;
435 
436   Dot = alignTo(Dot, CurOutSec->Addralign);
437   CurOutSec->Addr = isTbss<ELFT>(CurOutSec) ? Dot + ThreadBssOffset : Dot;
438 
439   // If neither AT nor AT> is specified for an allocatable section, the linker
440   // will set the LMA such that the difference between VMA and LMA for the
441   // section is the same as the preceding output section in the same region
442   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
443   CurOutSec->setLMAOffset(LMAOffset);
444 }
445 
446 template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
447   // This handles the assignments to symbol or to a location counter (.)
448   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
449     if (AssignCmd->Name == ".") {
450       // Update to location counter means update to section size.
451       Dot = AssignCmd->Expression(Dot);
452       CurOutSec->Size = Dot - CurOutSec->Addr;
453       return;
454     }
455     assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot);
456     return;
457   }
458 
459   // Handle BYTE(), SHORT(), LONG(), or QUAD().
460   if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
461     DataCmd->Offset = Dot - CurOutSec->Addr;
462     Dot += DataCmd->Size;
463     CurOutSec->Size = Dot - CurOutSec->Addr;
464     return;
465   }
466 
467   // It handles single input section description command,
468   // calculates and assigns the offsets for each section and also
469   // updates the output section size.
470   auto &ICmd = cast<InputSectionDescription>(Base);
471   for (InputSectionData *ID : ICmd.Sections) {
472     auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
473     switchTo(IB->OutSec);
474     if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
475       output(I);
476     else
477       flush();
478   }
479 }
480 
481 template <class ELFT>
482 static std::vector<OutputSectionBase *>
483 findSections(StringRef Name, const std::vector<OutputSectionBase *> &Sections) {
484   std::vector<OutputSectionBase *> Ret;
485   for (OutputSectionBase *Sec : Sections)
486     if (Sec->getName() == Name)
487       Ret.push_back(Sec);
488   return Ret;
489 }
490 
491 template <class ELFT>
492 void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
493   if (Cmd->LMAExpr)
494     LMAOffset = Cmd->LMAExpr(Dot) - Dot;
495   std::vector<OutputSectionBase *> Sections =
496       findSections<ELFT>(Cmd->Name, *OutputSections);
497   if (Sections.empty())
498     return;
499   switchTo(Sections[0]);
500   // Find the last section output location. We will output orphan sections
501   // there so that end symbols point to the correct location.
502   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
503                         [](const std::unique_ptr<BaseCommand> &Cmd) {
504                           return !isa<SymbolAssignment>(*Cmd);
505                         })
506                .base();
507   for (auto I = Cmd->Commands.begin(); I != E; ++I)
508     process(**I);
509   for (OutputSectionBase *Base : Sections)
510     switchTo(Base);
511   flush();
512   std::for_each(E, Cmd->Commands.end(),
513                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
514 }
515 
516 template <class ELFT> void LinkerScript<ELFT>::removeEmptyCommands() {
517   // It is common practice to use very generic linker scripts. So for any
518   // given run some of the output sections in the script will be empty.
519   // We could create corresponding empty output sections, but that would
520   // clutter the output.
521   // We instead remove trivially empty sections. The bfd linker seems even
522   // more aggressive at removing them.
523   auto Pos = std::remove_if(
524       Opt.Commands.begin(), Opt.Commands.end(),
525       [&](const std::unique_ptr<BaseCommand> &Base) {
526         auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
527         if (!Cmd)
528           return false;
529         return findSections<ELFT>(Cmd->Name, *OutputSections).empty();
530       });
531   Opt.Commands.erase(Pos, Opt.Commands.end());
532 }
533 
534 static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
535   for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
536     if (!isa<InputSectionDescription>(*I))
537       return false;
538   return true;
539 }
540 
541 template <class ELFT> void LinkerScript<ELFT>::adjustSectionsBeforeSorting() {
542   // If the output section contains only symbol assignments, create a
543   // corresponding output section. The bfd linker seems to only create them if
544   // '.' is assigned to, but creating these section should not have any bad
545   // consequeces and gives us a section to put the symbol in.
546   uintX_t Flags = SHF_ALLOC;
547   uint32_t Type = 0;
548   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
549     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
550     if (!Cmd)
551       continue;
552     std::vector<OutputSectionBase *> Secs =
553         findSections<ELFT>(Cmd->Name, *OutputSections);
554     if (!Secs.empty()) {
555       Flags = Secs[0]->Flags;
556       Type = Secs[0]->Type;
557       continue;
558     }
559 
560     if (isAllSectionDescription(*Cmd))
561       continue;
562 
563     auto *OutSec = make<OutputSection<ELFT>>(Cmd->Name, Type, Flags);
564     OutputSections->push_back(OutSec);
565   }
566 }
567 
568 template <class ELFT> void LinkerScript<ELFT>::adjustSectionsAfterSorting() {
569   placeOrphanSections();
570 
571   // If output section command doesn't specify any segments,
572   // and we haven't previously assigned any section to segment,
573   // then we simply assign section to the very first load segment.
574   // Below is an example of such linker script:
575   // PHDRS { seg PT_LOAD; }
576   // SECTIONS { .aaa : { *(.aaa) } }
577   std::vector<StringRef> DefPhdrs;
578   auto FirstPtLoad =
579       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
580                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
581   if (FirstPtLoad != Opt.PhdrsCommands.end())
582     DefPhdrs.push_back(FirstPtLoad->Name);
583 
584   // Walk the commands and propagate the program headers to commands that don't
585   // explicitly specify them.
586   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
587     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
588     if (!Cmd)
589       continue;
590     if (Cmd->Phdrs.empty())
591       Cmd->Phdrs = DefPhdrs;
592     else
593       DefPhdrs = Cmd->Phdrs;
594   }
595 
596   removeEmptyCommands();
597 }
598 
599 // When placing orphan sections, we want to place them after symbol assignments
600 // so that an orphan after
601 //   begin_foo = .;
602 //   foo : { *(foo) }
603 //   end_foo = .;
604 // doesn't break the intended meaning of the begin/end symbols.
605 // We don't want to go over sections since Writer<ELFT>::sortSections is the
606 // one in charge of deciding the order of the sections.
607 // We don't want to go over alignments, since doing so in
608 //  rx_sec : { *(rx_sec) }
609 //  . = ALIGN(0x1000);
610 //  /* The RW PT_LOAD starts here*/
611 //  rw_sec : { *(rw_sec) }
612 // would mean that the RW PT_LOAD would become unaligned.
613 static bool shouldSkip(const BaseCommand &Cmd) {
614   if (isa<OutputSectionCommand>(Cmd))
615     return false;
616   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
617   if (!Assign)
618     return true;
619   return Assign->Name != ".";
620 }
621 
622 // Orphan sections are sections present in the input files which are not
623 // explicitly placed into the output file by the linker script. This just
624 // places them in the order already decided in OutputSections.
625 template <class ELFT>
626 void LinkerScript<ELFT>::placeOrphanSections() {
627   // The OutputSections are already in the correct order.
628   // This loops creates or moves commands as needed so that they are in the
629   // correct order.
630   int CmdIndex = 0;
631   for (OutputSectionBase *Sec : *OutputSections) {
632     StringRef Name = Sec->getName();
633 
634     // Find the last spot where we can insert a command and still get the
635     // correct result.
636     auto CmdIter = Opt.Commands.begin() + CmdIndex;
637     auto E = Opt.Commands.end();
638     while (CmdIter != E && shouldSkip(**CmdIter)) {
639       ++CmdIter;
640       ++CmdIndex;
641     }
642 
643     auto Pos =
644         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
645           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
646           return Cmd && Cmd->Name == Name;
647         });
648     if (Pos == E) {
649       Opt.Commands.insert(CmdIter,
650                           llvm::make_unique<OutputSectionCommand>(Name));
651       ++CmdIndex;
652       continue;
653     }
654 
655     // Continue from where we found it.
656     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
657   }
658 }
659 
660 template <class ELFT>
661 void LinkerScript<ELFT>::assignAddresses(std::vector<PhdrEntry<ELFT>> &Phdrs) {
662   // Assign addresses as instructed by linker script SECTIONS sub-commands.
663   Dot = 0;
664 
665   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
666     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
667       if (Cmd->Name == ".") {
668         Dot = Cmd->Expression(Dot);
669       } else if (Cmd->Sym) {
670         assignSectionSymbol<ELFT>(
671             Cmd, CurOutSec ? CurOutSec : (*OutputSections)[0], Dot);
672       }
673       continue;
674     }
675 
676     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
677       Cmd->Expression(Dot);
678       continue;
679     }
680 
681     auto *Cmd = cast<OutputSectionCommand>(Base.get());
682 
683     if (Cmd->AddrExpr)
684       Dot = Cmd->AddrExpr(Dot);
685 
686     assignOffsets(Cmd);
687   }
688 
689   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
690   for (OutputSectionBase *Sec : *OutputSections) {
691     if (Sec->Flags & SHF_ALLOC)
692       MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
693     else
694       Sec->Addr = 0;
695   }
696 
697   uintX_t HeaderSize = getHeaderSize();
698   auto FirstPTLoad =
699       std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry<ELFT> &E) {
700         return E.H.p_type == PT_LOAD;
701       });
702 
703   if (HeaderSize <= MinVA && FirstPTLoad != Phdrs.end()) {
704     // If linker script specifies program headers and first PT_LOAD doesn't
705     // have both PHDRS and FILEHDR attributes then do nothing
706     if (!Opt.PhdrsCommands.empty()) {
707       size_t SegNum = std::distance(Phdrs.begin(), FirstPTLoad);
708       if (!Opt.PhdrsCommands[SegNum].HasPhdrs ||
709           !Opt.PhdrsCommands[SegNum].HasFilehdr)
710         return;
711     }
712     // ELF and Program headers need to be right before the first section in
713     // memory. Set their addresses accordingly.
714     MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
715     Out<ELFT>::ElfHeader->Addr = MinVA;
716     Out<ELFT>::ProgramHeaders->Addr = Out<ELFT>::ElfHeader->Size + MinVA;
717     FirstPTLoad->First = Out<ELFT>::ElfHeader;
718     if (!FirstPTLoad->Last)
719       FirstPTLoad->Last = Out<ELFT>::ProgramHeaders;
720   } else if (!FirstPTLoad->First) {
721     // Sometimes the very first PT_LOAD segment can be empty.
722     // This happens if (all conditions met):
723     //  - Linker script is used
724     //  - First section in ELF image is not RO
725     //  - Not enough space for program headers.
726     // The code below removes empty PT_LOAD segment and updates
727     // program headers size.
728     Phdrs.erase(FirstPTLoad);
729     Out<ELFT>::ProgramHeaders->Size =
730         sizeof(typename ELFT::Phdr) * Phdrs.size();
731   }
732 }
733 
734 // Creates program headers as instructed by PHDRS linker script command.
735 template <class ELFT>
736 std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
737   std::vector<PhdrEntry<ELFT>> Ret;
738 
739   // Process PHDRS and FILEHDR keywords because they are not
740   // real output sections and cannot be added in the following loop.
741   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
742     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
743     PhdrEntry<ELFT> &Phdr = Ret.back();
744 
745     if (Cmd.HasFilehdr)
746       Phdr.add(Out<ELFT>::ElfHeader);
747     if (Cmd.HasPhdrs)
748       Phdr.add(Out<ELFT>::ProgramHeaders);
749 
750     if (Cmd.LMAExpr) {
751       Phdr.H.p_paddr = Cmd.LMAExpr(0);
752       Phdr.HasLMA = true;
753     }
754   }
755 
756   // Add output sections to program headers.
757   for (OutputSectionBase *Sec : *OutputSections) {
758     if (!(Sec->Flags & SHF_ALLOC))
759       break;
760 
761     // Assign headers specified by linker script
762     for (size_t Id : getPhdrIndices(Sec->getName())) {
763       Ret[Id].add(Sec);
764       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
765         Ret[Id].H.p_flags |= Sec->getPhdrFlags();
766     }
767   }
768   return Ret;
769 }
770 
771 template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
772   // Ignore .interp section in case we have PHDRS specification
773   // and PT_INTERP isn't listed.
774   return !Opt.PhdrsCommands.empty() &&
775          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
776            return Cmd.Type == PT_INTERP;
777          }) == Opt.PhdrsCommands.end();
778 }
779 
780 template <class ELFT>
781 ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
782   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
783     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
784       if (Cmd->Name == Name)
785         return Cmd->Filler;
786   return {};
787 }
788 
789 template <class ELFT>
790 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
791   const endianness E = ELFT::TargetEndianness;
792 
793   switch (Size) {
794   case 1:
795     *Buf = (uint8_t)Data;
796     break;
797   case 2:
798     write16<E>(Buf, Data);
799     break;
800   case 4:
801     write32<E>(Buf, Data);
802     break;
803   case 8:
804     write64<E>(Buf, Data);
805     break;
806   default:
807     llvm_unreachable("unsupported Size argument");
808   }
809 }
810 
811 template <class ELFT>
812 void LinkerScript<ELFT>::writeDataBytes(StringRef Name, uint8_t *Buf) {
813   int I = getSectionIndex(Name);
814   if (I == INT_MAX)
815     return;
816 
817   OutputSectionCommand *Cmd =
818       dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
819   for (const std::unique_ptr<BaseCommand> &Base2 : Cmd->Commands)
820     if (auto *DataCmd = dyn_cast<BytesDataCommand>(Base2.get()))
821       writeInt<ELFT>(&Buf[DataCmd->Offset], DataCmd->Data, DataCmd->Size);
822 }
823 
824 template <class ELFT> bool LinkerScript<ELFT>::hasLMA(StringRef Name) {
825   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
826     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
827       if (Cmd->LMAExpr && Cmd->Name == Name)
828         return true;
829   return false;
830 }
831 
832 // Returns the index of the given section name in linker script
833 // SECTIONS commands. Sections are laid out as the same order as they
834 // were in the script. If a given name did not appear in the script,
835 // it returns INT_MAX, so that it will be laid out at end of file.
836 template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
837   int I = 0;
838   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
839     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
840       if (Cmd->Name == Name)
841         return I;
842     ++I;
843   }
844   return INT_MAX;
845 }
846 
847 template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
848   return !Opt.PhdrsCommands.empty();
849 }
850 
851 template <class ELFT>
852 uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
853   for (OutputSectionBase *Sec : *OutputSections)
854     if (Sec->getName() == Name)
855       return Sec->Addr;
856   error("undefined section " + Name);
857   return 0;
858 }
859 
860 template <class ELFT>
861 uint64_t LinkerScript<ELFT>::getOutputSectionLMA(StringRef Name) {
862   for (OutputSectionBase *Sec : *OutputSections)
863     if (Sec->getName() == Name)
864       return Sec->getLMA();
865   error("undefined section " + Name);
866   return 0;
867 }
868 
869 template <class ELFT>
870 uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
871   for (OutputSectionBase *Sec : *OutputSections)
872     if (Sec->getName() == Name)
873       return Sec->Size;
874   error("undefined section " + Name);
875   return 0;
876 }
877 
878 template <class ELFT>
879 uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
880   for (OutputSectionBase *Sec : *OutputSections)
881     if (Sec->getName() == Name)
882       return Sec->Addralign;
883   error("undefined section " + Name);
884   return 0;
885 }
886 
887 template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
888   return elf::getHeaderSize<ELFT>();
889 }
890 
891 template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
892   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
893     return B->getVA<ELFT>();
894   error("symbol not found: " + S);
895   return 0;
896 }
897 
898 template <class ELFT> bool LinkerScript<ELFT>::isDefined(StringRef S) {
899   return Symtab<ELFT>::X->find(S) != nullptr;
900 }
901 
902 template <class ELFT> bool LinkerScript<ELFT>::isAbsolute(StringRef S) {
903   SymbolBody *Sym = Symtab<ELFT>::X->find(S);
904   auto *DR = dyn_cast_or_null<DefinedRegular<ELFT>>(Sym);
905   return DR && !DR->Section;
906 }
907 
908 // Returns indices of ELF headers containing specific section, identified
909 // by Name. Each index is a zero based number of ELF header listed within
910 // PHDRS {} script block.
911 template <class ELFT>
912 std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
913   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
914     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
915     if (!Cmd || Cmd->Name != SectionName)
916       continue;
917 
918     std::vector<size_t> Ret;
919     for (StringRef PhdrName : Cmd->Phdrs)
920       Ret.push_back(getPhdrIndex(PhdrName));
921     return Ret;
922   }
923   return {};
924 }
925 
926 template <class ELFT>
927 size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
928   size_t I = 0;
929   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
930     if (Cmd.Name == PhdrName)
931       return I;
932     ++I;
933   }
934   error("section header '" + PhdrName + "' is not listed in PHDRS");
935   return 0;
936 }
937 
938 class elf::ScriptParser : public ScriptParserBase {
939   typedef void (ScriptParser::*Handler)();
940 
941 public:
942   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
943 
944   void readLinkerScript();
945   void readVersionScript();
946 
947 private:
948   void addFile(StringRef Path);
949 
950   void readAsNeeded();
951   void readEntry();
952   void readExtern();
953   void readGroup();
954   void readInclude();
955   void readOutput();
956   void readOutputArch();
957   void readOutputFormat();
958   void readPhdrs();
959   void readSearchDir();
960   void readSections();
961   void readVersion();
962   void readVersionScriptCommand();
963 
964   SymbolAssignment *readAssignment(StringRef Name);
965   BytesDataCommand *readBytesDataCommand(StringRef Tok);
966   std::vector<uint8_t> readFill();
967   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
968   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
969   std::vector<StringRef> readOutputSectionPhdrs();
970   InputSectionDescription *readInputSectionDescription(StringRef Tok);
971   StringMatcher readFilePatterns();
972   std::vector<SectionPattern> readInputSectionsList();
973   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
974   unsigned readPhdrType();
975   SortSectionPolicy readSortKind();
976   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
977   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
978   void readSort();
979   Expr readAssert();
980 
981   Expr readExpr();
982   Expr readExpr1(Expr Lhs, int MinPrec);
983   StringRef readParenLiteral();
984   Expr readPrimary();
985   Expr readTernary(Expr Cond);
986   Expr readParenExpr();
987 
988   // For parsing version script.
989   void readExtern(std::vector<SymbolVersion> *Globals);
990   void readVersionDeclaration(StringRef VerStr);
991   void readGlobal(StringRef VerStr);
992   void readLocal(StringRef VerStr);
993 
994   ScriptConfiguration &Opt = *ScriptConfig;
995   bool IsUnderSysroot;
996 };
997 
998 void ScriptParser::readVersionScript() {
999   readVersionScriptCommand();
1000   if (!atEOF())
1001     setError("EOF expected, but got " + next());
1002 }
1003 
1004 void ScriptParser::readVersionScriptCommand() {
1005   if (consume("{")) {
1006     readVersionDeclaration("");
1007     return;
1008   }
1009 
1010   while (!atEOF() && !Error && peek() != "}") {
1011     StringRef VerStr = next();
1012     if (VerStr == "{") {
1013       setError("anonymous version definition is used in "
1014                "combination with other version definitions");
1015       return;
1016     }
1017     expect("{");
1018     readVersionDeclaration(VerStr);
1019   }
1020 }
1021 
1022 void ScriptParser::readVersion() {
1023   expect("{");
1024   readVersionScriptCommand();
1025   expect("}");
1026 }
1027 
1028 void ScriptParser::readLinkerScript() {
1029   while (!atEOF()) {
1030     StringRef Tok = next();
1031     if (Tok == ";")
1032       continue;
1033 
1034     if (Tok == "ASSERT") {
1035       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1036     } else if (Tok == "ENTRY") {
1037       readEntry();
1038     } else if (Tok == "EXTERN") {
1039       readExtern();
1040     } else if (Tok == "GROUP" || Tok == "INPUT") {
1041       readGroup();
1042     } else if (Tok == "INCLUDE") {
1043       readInclude();
1044     } else if (Tok == "OUTPUT") {
1045       readOutput();
1046     } else if (Tok == "OUTPUT_ARCH") {
1047       readOutputArch();
1048     } else if (Tok == "OUTPUT_FORMAT") {
1049       readOutputFormat();
1050     } else if (Tok == "PHDRS") {
1051       readPhdrs();
1052     } else if (Tok == "SEARCH_DIR") {
1053       readSearchDir();
1054     } else if (Tok == "SECTIONS") {
1055       readSections();
1056     } else if (Tok == "VERSION") {
1057       readVersion();
1058     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
1059       Opt.Commands.emplace_back(Cmd);
1060     } else {
1061       setError("unknown directive: " + Tok);
1062     }
1063   }
1064 }
1065 
1066 void ScriptParser::addFile(StringRef S) {
1067   if (IsUnderSysroot && S.startswith("/")) {
1068     SmallString<128> PathData;
1069     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
1070     if (sys::fs::exists(Path)) {
1071       Driver->addFile(Saver.save(Path));
1072       return;
1073     }
1074   }
1075 
1076   if (sys::path::is_absolute(S)) {
1077     Driver->addFile(S);
1078   } else if (S.startswith("=")) {
1079     if (Config->Sysroot.empty())
1080       Driver->addFile(S.substr(1));
1081     else
1082       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1083   } else if (S.startswith("-l")) {
1084     Driver->addLibrary(S.substr(2));
1085   } else if (sys::fs::exists(S)) {
1086     Driver->addFile(S);
1087   } else {
1088     std::string Path = findFromSearchPaths(S);
1089     if (Path.empty())
1090       setError("unable to find " + S);
1091     else
1092       Driver->addFile(Saver.save(Path));
1093   }
1094 }
1095 
1096 void ScriptParser::readAsNeeded() {
1097   expect("(");
1098   bool Orig = Config->AsNeeded;
1099   Config->AsNeeded = true;
1100   while (!Error && !consume(")"))
1101     addFile(unquote(next()));
1102   Config->AsNeeded = Orig;
1103 }
1104 
1105 void ScriptParser::readEntry() {
1106   // -e <symbol> takes predecence over ENTRY(<symbol>).
1107   expect("(");
1108   StringRef Tok = next();
1109   if (Config->Entry.empty())
1110     Config->Entry = Tok;
1111   expect(")");
1112 }
1113 
1114 void ScriptParser::readExtern() {
1115   expect("(");
1116   while (!Error && !consume(")"))
1117     Config->Undefined.push_back(next());
1118 }
1119 
1120 void ScriptParser::readGroup() {
1121   expect("(");
1122   while (!Error && !consume(")")) {
1123     StringRef Tok = next();
1124     if (Tok == "AS_NEEDED")
1125       readAsNeeded();
1126     else
1127       addFile(unquote(Tok));
1128   }
1129 }
1130 
1131 void ScriptParser::readInclude() {
1132   StringRef Tok = next();
1133   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
1134   if (!MBOrErr) {
1135     setError("cannot open " + Tok);
1136     return;
1137   }
1138   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
1139   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
1140   std::vector<StringRef> V = tokenize(S);
1141   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
1142 }
1143 
1144 void ScriptParser::readOutput() {
1145   // -o <file> takes predecence over OUTPUT(<file>).
1146   expect("(");
1147   StringRef Tok = next();
1148   if (Config->OutputFile.empty())
1149     Config->OutputFile = unquote(Tok);
1150   expect(")");
1151 }
1152 
1153 void ScriptParser::readOutputArch() {
1154   // Error checking only for now.
1155   expect("(");
1156   skip();
1157   expect(")");
1158 }
1159 
1160 void ScriptParser::readOutputFormat() {
1161   // Error checking only for now.
1162   expect("(");
1163   skip();
1164   StringRef Tok = next();
1165   if (Tok == ")")
1166     return;
1167   if (Tok != ",") {
1168     setError("unexpected token: " + Tok);
1169     return;
1170   }
1171   skip();
1172   expect(",");
1173   skip();
1174   expect(")");
1175 }
1176 
1177 void ScriptParser::readPhdrs() {
1178   expect("{");
1179   while (!Error && !consume("}")) {
1180     StringRef Tok = next();
1181     Opt.PhdrsCommands.push_back(
1182         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1183     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1184 
1185     PhdrCmd.Type = readPhdrType();
1186     do {
1187       Tok = next();
1188       if (Tok == ";")
1189         break;
1190       if (Tok == "FILEHDR")
1191         PhdrCmd.HasFilehdr = true;
1192       else if (Tok == "PHDRS")
1193         PhdrCmd.HasPhdrs = true;
1194       else if (Tok == "AT")
1195         PhdrCmd.LMAExpr = readParenExpr();
1196       else if (Tok == "FLAGS") {
1197         expect("(");
1198         // Passing 0 for the value of dot is a bit of a hack. It means that
1199         // we accept expressions like ".|1".
1200         PhdrCmd.Flags = readExpr()(0);
1201         expect(")");
1202       } else
1203         setError("unexpected header attribute: " + Tok);
1204     } while (!Error);
1205   }
1206 }
1207 
1208 void ScriptParser::readSearchDir() {
1209   expect("(");
1210   StringRef Tok = next();
1211   if (!Config->Nostdlib)
1212     Config->SearchPaths.push_back(unquote(Tok));
1213   expect(")");
1214 }
1215 
1216 void ScriptParser::readSections() {
1217   Opt.HasSections = true;
1218   expect("{");
1219   while (!Error && !consume("}")) {
1220     StringRef Tok = next();
1221     BaseCommand *Cmd = readProvideOrAssignment(Tok);
1222     if (!Cmd) {
1223       if (Tok == "ASSERT")
1224         Cmd = new AssertCommand(readAssert());
1225       else
1226         Cmd = readOutputSectionDescription(Tok);
1227     }
1228     Opt.Commands.emplace_back(Cmd);
1229   }
1230 }
1231 
1232 static int precedence(StringRef Op) {
1233   return StringSwitch<int>(Op)
1234       .Cases("*", "/", 5)
1235       .Cases("+", "-", 4)
1236       .Cases("<<", ">>", 3)
1237       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
1238       .Cases("&", "|", 1)
1239       .Default(-1);
1240 }
1241 
1242 StringMatcher ScriptParser::readFilePatterns() {
1243   std::vector<StringRef> V;
1244   while (!Error && !consume(")"))
1245     V.push_back(next());
1246   return StringMatcher(V);
1247 }
1248 
1249 SortSectionPolicy ScriptParser::readSortKind() {
1250   if (consume("SORT") || consume("SORT_BY_NAME"))
1251     return SortSectionPolicy::Name;
1252   if (consume("SORT_BY_ALIGNMENT"))
1253     return SortSectionPolicy::Alignment;
1254   if (consume("SORT_BY_INIT_PRIORITY"))
1255     return SortSectionPolicy::Priority;
1256   if (consume("SORT_NONE"))
1257     return SortSectionPolicy::None;
1258   return SortSectionPolicy::Default;
1259 }
1260 
1261 // Method reads a list of sequence of excluded files and section globs given in
1262 // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1263 // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1264 // The semantics of that is next:
1265 // * Include .foo.1 from every file.
1266 // * Include .foo.2 from every file but a.o
1267 // * Include .foo.3 from every file but b.o
1268 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1269   std::vector<SectionPattern> Ret;
1270   while (!Error && peek() != ")") {
1271     StringMatcher ExcludeFilePat;
1272     if (consume("EXCLUDE_FILE")) {
1273       expect("(");
1274       ExcludeFilePat = readFilePatterns();
1275     }
1276 
1277     std::vector<StringRef> V;
1278     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1279       V.push_back(next());
1280 
1281     if (!V.empty())
1282       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
1283     else
1284       setError("section pattern is expected");
1285   }
1286   return Ret;
1287 }
1288 
1289 // Section pattern grammar can have complex expressions, for example:
1290 // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1291 // Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1292 // commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1293 // This methods handles wrapping sequences of excluded files and section globs
1294 // into SORT() if that needed and reads them all.
1295 InputSectionDescription *
1296 ScriptParser::readInputSectionRules(StringRef FilePattern) {
1297   auto *Cmd = new InputSectionDescription(FilePattern);
1298   expect("(");
1299   while (!HasError && !consume(")")) {
1300     SortSectionPolicy Outer = readSortKind();
1301     SortSectionPolicy Inner = SortSectionPolicy::Default;
1302     std::vector<SectionPattern> V;
1303     if (Outer != SortSectionPolicy::Default) {
1304       expect("(");
1305       Inner = readSortKind();
1306       if (Inner != SortSectionPolicy::Default) {
1307         expect("(");
1308         V = readInputSectionsList();
1309         expect(")");
1310       } else {
1311         V = readInputSectionsList();
1312       }
1313       expect(")");
1314     } else {
1315       V = readInputSectionsList();
1316     }
1317 
1318     for (SectionPattern &Pat : V) {
1319       Pat.SortInner = Inner;
1320       Pat.SortOuter = Outer;
1321     }
1322 
1323     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1324   }
1325   return Cmd;
1326 }
1327 
1328 InputSectionDescription *
1329 ScriptParser::readInputSectionDescription(StringRef Tok) {
1330   // Input section wildcard can be surrounded by KEEP.
1331   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1332   if (Tok == "KEEP") {
1333     expect("(");
1334     StringRef FilePattern = next();
1335     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
1336     expect(")");
1337     Opt.KeptSections.push_back(Cmd);
1338     return Cmd;
1339   }
1340   return readInputSectionRules(Tok);
1341 }
1342 
1343 void ScriptParser::readSort() {
1344   expect("(");
1345   expect("CONSTRUCTORS");
1346   expect(")");
1347 }
1348 
1349 Expr ScriptParser::readAssert() {
1350   expect("(");
1351   Expr E = readExpr();
1352   expect(",");
1353   StringRef Msg = unquote(next());
1354   expect(")");
1355   return [=](uint64_t Dot) {
1356     uint64_t V = E(Dot);
1357     if (!V)
1358       error(Msg);
1359     return V;
1360   };
1361 }
1362 
1363 // Reads a FILL(expr) command. We handle the FILL command as an
1364 // alias for =fillexp section attribute, which is different from
1365 // what GNU linkers do.
1366 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1367 std::vector<uint8_t> ScriptParser::readFill() {
1368   expect("(");
1369   std::vector<uint8_t> V = readOutputSectionFiller(next());
1370   expect(")");
1371   expect(";");
1372   return V;
1373 }
1374 
1375 OutputSectionCommand *
1376 ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1377   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
1378 
1379   // Read an address expression.
1380   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1381   if (peek() != ":")
1382     Cmd->AddrExpr = readExpr();
1383 
1384   expect(":");
1385 
1386   if (consume("AT"))
1387     Cmd->LMAExpr = readParenExpr();
1388   if (consume("ALIGN"))
1389     Cmd->AlignExpr = readParenExpr();
1390   if (consume("SUBALIGN"))
1391     Cmd->SubalignExpr = readParenExpr();
1392 
1393   // Parse constraints.
1394   if (consume("ONLY_IF_RO"))
1395     Cmd->Constraint = ConstraintKind::ReadOnly;
1396   if (consume("ONLY_IF_RW"))
1397     Cmd->Constraint = ConstraintKind::ReadWrite;
1398   expect("{");
1399 
1400   while (!Error && !consume("}")) {
1401     StringRef Tok = next();
1402     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok))
1403       Cmd->Commands.emplace_back(Assignment);
1404     else if (BytesDataCommand *Data = readBytesDataCommand(Tok))
1405       Cmd->Commands.emplace_back(Data);
1406     else if (Tok == "FILL")
1407       Cmd->Filler = readFill();
1408     else if (Tok == "SORT")
1409       readSort();
1410     else if (peek() == "(")
1411       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1412     else
1413       setError("unknown command " + Tok);
1414   }
1415   Cmd->Phdrs = readOutputSectionPhdrs();
1416 
1417   if (consume("="))
1418     Cmd->Filler = readOutputSectionFiller(next());
1419   else if (peek().startswith("="))
1420     Cmd->Filler = readOutputSectionFiller(next().drop_front());
1421 
1422   return Cmd;
1423 }
1424 
1425 // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1426 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1427 //
1428 // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1429 // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1430 // as 32-bit big-endian values. We will do the same as ld.gold does
1431 // because it's simpler than what ld.bfd does.
1432 std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1433   uint32_t V;
1434   if (Tok.getAsInteger(0, V)) {
1435     setError("invalid filler expression: " + Tok);
1436     return {};
1437   }
1438   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
1439 }
1440 
1441 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1442   expect("(");
1443   SymbolAssignment *Cmd = readAssignment(next());
1444   Cmd->Provide = Provide;
1445   Cmd->Hidden = Hidden;
1446   expect(")");
1447   expect(";");
1448   return Cmd;
1449 }
1450 
1451 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1452   SymbolAssignment *Cmd = nullptr;
1453   if (peek() == "=" || peek() == "+=") {
1454     Cmd = readAssignment(Tok);
1455     expect(";");
1456   } else if (Tok == "PROVIDE") {
1457     Cmd = readProvideHidden(true, false);
1458   } else if (Tok == "HIDDEN") {
1459     Cmd = readProvideHidden(false, true);
1460   } else if (Tok == "PROVIDE_HIDDEN") {
1461     Cmd = readProvideHidden(true, true);
1462   }
1463   return Cmd;
1464 }
1465 
1466 static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1467   if (S == ".")
1468     return Dot;
1469   return ScriptBase->getSymbolValue(S);
1470 }
1471 
1472 static bool isAbsolute(StringRef S) {
1473   if (S == ".")
1474     return false;
1475   return ScriptBase->isAbsolute(S);
1476 }
1477 
1478 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1479   StringRef Op = next();
1480   Expr E;
1481   assert(Op == "=" || Op == "+=");
1482   if (consume("ABSOLUTE")) {
1483     // The RHS may be something like "ABSOLUTE(.) & 0xff".
1484     // Call readExpr1 to read the whole expression.
1485     E = readExpr1(readParenExpr(), 0);
1486     E.IsAbsolute = []() { return true; };
1487   } else {
1488     E = readExpr();
1489   }
1490   if (Op == "+=")
1491     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1492   return new SymbolAssignment(Name, E);
1493 }
1494 
1495 // This is an operator-precedence parser to parse a linker
1496 // script expression.
1497 Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1498 
1499 static Expr combine(StringRef Op, Expr L, Expr R) {
1500   if (Op == "*")
1501     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1502   if (Op == "/") {
1503     return [=](uint64_t Dot) -> uint64_t {
1504       uint64_t RHS = R(Dot);
1505       if (RHS == 0) {
1506         error("division by zero");
1507         return 0;
1508       }
1509       return L(Dot) / RHS;
1510     };
1511   }
1512   if (Op == "+")
1513     return {[=](uint64_t Dot) { return L(Dot) + R(Dot); },
1514             [=]() { return L.IsAbsolute() && R.IsAbsolute(); }};
1515   if (Op == "-")
1516     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1517   if (Op == "<<")
1518     return [=](uint64_t Dot) { return L(Dot) << R(Dot); };
1519   if (Op == ">>")
1520     return [=](uint64_t Dot) { return L(Dot) >> R(Dot); };
1521   if (Op == "<")
1522     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1523   if (Op == ">")
1524     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1525   if (Op == ">=")
1526     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1527   if (Op == "<=")
1528     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1529   if (Op == "==")
1530     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1531   if (Op == "!=")
1532     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1533   if (Op == "&")
1534     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1535   if (Op == "|")
1536     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
1537   llvm_unreachable("invalid operator");
1538 }
1539 
1540 // This is a part of the operator-precedence parser. This function
1541 // assumes that the remaining token stream starts with an operator.
1542 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1543   while (!atEOF() && !Error) {
1544     // Read an operator and an expression.
1545     StringRef Op1 = peek();
1546     if (Op1 == "?")
1547       return readTernary(Lhs);
1548     if (precedence(Op1) < MinPrec)
1549       break;
1550     skip();
1551     Expr Rhs = readPrimary();
1552 
1553     // Evaluate the remaining part of the expression first if the
1554     // next operator has greater precedence than the previous one.
1555     // For example, if we have read "+" and "3", and if the next
1556     // operator is "*", then we'll evaluate 3 * ... part first.
1557     while (!atEOF()) {
1558       StringRef Op2 = peek();
1559       if (precedence(Op2) <= precedence(Op1))
1560         break;
1561       Rhs = readExpr1(Rhs, precedence(Op2));
1562     }
1563 
1564     Lhs = combine(Op1, Lhs, Rhs);
1565   }
1566   return Lhs;
1567 }
1568 
1569 uint64_t static getConstant(StringRef S) {
1570   if (S == "COMMONPAGESIZE")
1571     return Target->PageSize;
1572   if (S == "MAXPAGESIZE")
1573     return Config->MaxPageSize;
1574   error("unknown constant: " + S);
1575   return 0;
1576 }
1577 
1578 // Parses Tok as an integer. Returns true if successful.
1579 // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1580 // and decimal numbers. Decimal numbers may have "K" (kilo) or
1581 // "M" (mega) prefixes.
1582 static bool readInteger(StringRef Tok, uint64_t &Result) {
1583   if (Tok.startswith("-")) {
1584     if (!readInteger(Tok.substr(1), Result))
1585       return false;
1586     Result = -Result;
1587     return true;
1588   }
1589   if (Tok.startswith_lower("0x"))
1590     return !Tok.substr(2).getAsInteger(16, Result);
1591   if (Tok.endswith_lower("H"))
1592     return !Tok.drop_back().getAsInteger(16, Result);
1593 
1594   int Suffix = 1;
1595   if (Tok.endswith_lower("K")) {
1596     Suffix = 1024;
1597     Tok = Tok.drop_back();
1598   } else if (Tok.endswith_lower("M")) {
1599     Suffix = 1024 * 1024;
1600     Tok = Tok.drop_back();
1601   }
1602   if (Tok.getAsInteger(10, Result))
1603     return false;
1604   Result *= Suffix;
1605   return true;
1606 }
1607 
1608 BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1609   int Size = StringSwitch<unsigned>(Tok)
1610                  .Case("BYTE", 1)
1611                  .Case("SHORT", 2)
1612                  .Case("LONG", 4)
1613                  .Case("QUAD", 8)
1614                  .Default(-1);
1615   if (Size == -1)
1616     return nullptr;
1617 
1618   expect("(");
1619   uint64_t Val = 0;
1620   StringRef S = next();
1621   if (!readInteger(S, Val))
1622     setError("unexpected value: " + S);
1623   expect(")");
1624   return new BytesDataCommand(Val, Size);
1625 }
1626 
1627 StringRef ScriptParser::readParenLiteral() {
1628   expect("(");
1629   StringRef Tok = next();
1630   expect(")");
1631   return Tok;
1632 }
1633 
1634 Expr ScriptParser::readPrimary() {
1635   if (peek() == "(")
1636     return readParenExpr();
1637 
1638   StringRef Tok = next();
1639 
1640   if (Tok == "~") {
1641     Expr E = readPrimary();
1642     return [=](uint64_t Dot) { return ~E(Dot); };
1643   }
1644   if (Tok == "-") {
1645     Expr E = readPrimary();
1646     return [=](uint64_t Dot) { return -E(Dot); };
1647   }
1648 
1649   // Built-in functions are parsed here.
1650   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1651   if (Tok == "ADDR") {
1652     StringRef Name = readParenLiteral();
1653     return
1654         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
1655   }
1656   if (Tok == "LOADADDR") {
1657     StringRef Name = readParenLiteral();
1658     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionLMA(Name); };
1659   }
1660   if (Tok == "ASSERT")
1661     return readAssert();
1662   if (Tok == "ALIGN") {
1663     Expr E = readParenExpr();
1664     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1665   }
1666   if (Tok == "CONSTANT") {
1667     StringRef Name = readParenLiteral();
1668     return [=](uint64_t Dot) { return getConstant(Name); };
1669   }
1670   if (Tok == "DEFINED") {
1671     expect("(");
1672     StringRef Tok = next();
1673     expect(")");
1674     return [=](uint64_t Dot) { return ScriptBase->isDefined(Tok) ? 1 : 0; };
1675   }
1676   if (Tok == "SEGMENT_START") {
1677     expect("(");
1678     skip();
1679     expect(",");
1680     Expr E = readExpr();
1681     expect(")");
1682     return [=](uint64_t Dot) { return E(Dot); };
1683   }
1684   if (Tok == "DATA_SEGMENT_ALIGN") {
1685     expect("(");
1686     Expr E = readExpr();
1687     expect(",");
1688     readExpr();
1689     expect(")");
1690     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1691   }
1692   if (Tok == "DATA_SEGMENT_END") {
1693     expect("(");
1694     expect(".");
1695     expect(")");
1696     return [](uint64_t Dot) { return Dot; };
1697   }
1698   // GNU linkers implements more complicated logic to handle
1699   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1700   // the next page boundary for simplicity.
1701   if (Tok == "DATA_SEGMENT_RELRO_END") {
1702     expect("(");
1703     readExpr();
1704     expect(",");
1705     readExpr();
1706     expect(")");
1707     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1708   }
1709   if (Tok == "SIZEOF") {
1710     StringRef Name = readParenLiteral();
1711     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
1712   }
1713   if (Tok == "ALIGNOF") {
1714     StringRef Name = readParenLiteral();
1715     return
1716         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1717   }
1718   if (Tok == "SIZEOF_HEADERS")
1719     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1720 
1721   // Tok is a literal number.
1722   uint64_t V;
1723   if (readInteger(Tok, V))
1724     return [=](uint64_t Dot) { return V; };
1725 
1726   // Tok is a symbol name.
1727   if (Tok != "." && !isValidCIdentifier(Tok))
1728     setError("malformed number: " + Tok);
1729   return {[=](uint64_t Dot) { return getSymbolValue(Tok, Dot); },
1730           [=]() { return isAbsolute(Tok); }};
1731 }
1732 
1733 Expr ScriptParser::readTernary(Expr Cond) {
1734   skip();
1735   Expr L = readExpr();
1736   expect(":");
1737   Expr R = readExpr();
1738   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1739 }
1740 
1741 Expr ScriptParser::readParenExpr() {
1742   expect("(");
1743   Expr E = readExpr();
1744   expect(")");
1745   return E;
1746 }
1747 
1748 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1749   std::vector<StringRef> Phdrs;
1750   while (!Error && peek().startswith(":")) {
1751     StringRef Tok = next();
1752     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1753   }
1754   return Phdrs;
1755 }
1756 
1757 // Read a program header type name. The next token must be a
1758 // name of a program header type or a constant (e.g. "0x3").
1759 unsigned ScriptParser::readPhdrType() {
1760   StringRef Tok = next();
1761   uint64_t Val;
1762   if (readInteger(Tok, Val))
1763     return Val;
1764 
1765   unsigned Ret = StringSwitch<unsigned>(Tok)
1766                      .Case("PT_NULL", PT_NULL)
1767                      .Case("PT_LOAD", PT_LOAD)
1768                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1769                      .Case("PT_INTERP", PT_INTERP)
1770                      .Case("PT_NOTE", PT_NOTE)
1771                      .Case("PT_SHLIB", PT_SHLIB)
1772                      .Case("PT_PHDR", PT_PHDR)
1773                      .Case("PT_TLS", PT_TLS)
1774                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1775                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1776                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1777                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1778                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1779                      .Default(-1);
1780 
1781   if (Ret == (unsigned)-1) {
1782     setError("invalid program header type: " + Tok);
1783     return PT_NULL;
1784   }
1785   return Ret;
1786 }
1787 
1788 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1789   // Identifiers start at 2 because 0 and 1 are reserved
1790   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1791   size_t VersionId = Config->VersionDefinitions.size() + 2;
1792   Config->VersionDefinitions.push_back({VerStr, VersionId});
1793 
1794   if (consume("global:") || peek() != "local:")
1795     readGlobal(VerStr);
1796   if (consume("local:"))
1797     readLocal(VerStr);
1798   expect("}");
1799 
1800   // Each version may have a parent version. For example, "Ver2" defined as
1801   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1802   // version hierarchy is, probably against your instinct, purely for human; the
1803   // runtime doesn't care about them at all. In LLD, we simply skip the token.
1804   if (!VerStr.empty() && peek() != ";")
1805     skip();
1806   expect(";");
1807 }
1808 
1809 void ScriptParser::readLocal(StringRef VerStr) {
1810   if (consume("*")) {
1811     Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1812     expect(";");
1813     return;
1814   }
1815 
1816   if (VerStr.empty())
1817     setError("locals list for anonymous version is not supported");
1818 
1819   std::vector<SymbolVersion> &Locals = Config->VersionDefinitions.back().Locals;
1820   while (!Error && peek() != "}") {
1821     StringRef Tok = next();
1822     Locals.push_back({unquote(Tok), false, hasWildcard(Tok)});
1823     expect(";");
1824   }
1825 }
1826 
1827 void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1828   expect("\"C++\"");
1829   expect("{");
1830 
1831   for (;;) {
1832     if (peek() == "}" || Error)
1833       break;
1834     bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1835     Globals->push_back({unquote(next()), true, HasWildcard});
1836     expect(";");
1837   }
1838 
1839   expect("}");
1840   expect(";");
1841 }
1842 
1843 void ScriptParser::readGlobal(StringRef VerStr) {
1844   std::vector<SymbolVersion> *Globals;
1845   if (VerStr.empty())
1846     Globals = &Config->VersionScriptGlobals;
1847   else
1848     Globals = &Config->VersionDefinitions.back().Globals;
1849 
1850   for (;;) {
1851     if (consume("extern"))
1852       readExtern(Globals);
1853 
1854     StringRef Cur = peek();
1855     if (Cur == "}" || Cur == "local:" || Error)
1856       return;
1857     skip();
1858     Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
1859     expect(";");
1860   }
1861 }
1862 
1863 static bool isUnderSysroot(StringRef Path) {
1864   if (Config->Sysroot == "")
1865     return false;
1866   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1867     if (sys::fs::equivalent(Config->Sysroot, Path))
1868       return true;
1869   return false;
1870 }
1871 
1872 void elf::readLinkerScript(MemoryBufferRef MB) {
1873   StringRef Path = MB.getBufferIdentifier();
1874   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1875 }
1876 
1877 void elf::readVersionScript(MemoryBufferRef MB) {
1878   ScriptParser(MB.getBuffer(), false).readVersionScript();
1879 }
1880 
1881 template class elf::LinkerScript<ELF32LE>;
1882 template class elf::LinkerScript<ELF32BE>;
1883 template class elf::LinkerScript<ELF64LE>;
1884 template class elf::LinkerScript<ELF64BE>;
1885