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