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