1 //===- ScriptParser.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a recursive-descendent parser for linker scripts.
10 // Parsed results are stored to Config and Script global objects.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ScriptParser.h"
15 #include "Config.h"
16 #include "Driver.h"
17 #include "InputSection.h"
18 #include "LinkerScript.h"
19 #include "OutputSections.h"
20 #include "ScriptLexer.h"
21 #include "Symbols.h"
22 #include "Target.h"
23 #include "lld/Common/Memory.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/StringSet.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/BinaryFormat/ELF.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/Path.h"
33 #include <cassert>
34 #include <limits>
35 #include <vector>
36 
37 using namespace llvm;
38 using namespace llvm::ELF;
39 using namespace llvm::support::endian;
40 using namespace lld;
41 using namespace lld::elf;
42 
43 static bool isUnderSysroot(StringRef Path);
44 
45 namespace {
46 class ScriptParser final : ScriptLexer {
47 public:
48   ScriptParser(MemoryBufferRef MB)
49       : ScriptLexer(MB),
50         IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
51 
52   void readLinkerScript();
53   void readVersionScript();
54   void readDynamicList();
55   void readDefsym(StringRef Name);
56 
57 private:
58   void addFile(StringRef Path);
59 
60   void readAsNeeded();
61   void readEntry();
62   void readExtern();
63   void readGroup();
64   void readInclude();
65   void readInput();
66   void readMemory();
67   void readOutput();
68   void readOutputArch();
69   void readOutputFormat();
70   void readPhdrs();
71   void readRegionAlias();
72   void readSearchDir();
73   void readSections();
74   void readTarget();
75   void readVersion();
76   void readVersionScriptCommand();
77 
78   SymbolAssignment *readSymbolAssignment(StringRef Name);
79   ByteCommand *readByteCommand(StringRef Tok);
80   std::array<uint8_t, 4> readFill();
81   std::array<uint8_t, 4> parseFill(StringRef Tok);
82   bool readSectionDirective(OutputSection *Cmd, StringRef Tok1, StringRef Tok2);
83   void readSectionAddressType(OutputSection *Cmd);
84   OutputSection *readOverlaySectionDescription();
85   OutputSection *readOutputSectionDescription(StringRef OutSec);
86   std::vector<BaseCommand *> readOverlay();
87   std::vector<StringRef> readOutputSectionPhdrs();
88   InputSectionDescription *readInputSectionDescription(StringRef Tok);
89   StringMatcher readFilePatterns();
90   std::vector<SectionPattern> readInputSectionsList();
91   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
92   unsigned readPhdrType();
93   SortSectionPolicy readSortKind();
94   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
95   SymbolAssignment *readAssignment(StringRef Tok);
96   std::tuple<ELFKind, uint16_t, bool> readBfdName();
97   void readSort();
98   Expr readAssert();
99   Expr readConstant();
100   Expr getPageSize();
101 
102   uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
103   std::pair<uint32_t, uint32_t> readMemoryAttributes();
104 
105   Expr combine(StringRef Op, Expr L, Expr R);
106   Expr readExpr();
107   Expr readExpr1(Expr Lhs, int MinPrec);
108   StringRef readParenLiteral();
109   Expr readPrimary();
110   Expr readTernary(Expr Cond);
111   Expr readParenExpr();
112 
113   // For parsing version script.
114   std::vector<SymbolVersion> readVersionExtern();
115   void readAnonymousDeclaration();
116   void readVersionDeclaration(StringRef VerStr);
117 
118   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
119   readSymbols();
120 
121   // True if a script being read is in a subdirectory specified by -sysroot.
122   bool IsUnderSysroot;
123 
124   // A set to detect an INCLUDE() cycle.
125   StringSet<> Seen;
126 };
127 } // namespace
128 
129 static StringRef unquote(StringRef S) {
130   if (S.startswith("\""))
131     return S.substr(1, S.size() - 2);
132   return S;
133 }
134 
135 static bool isUnderSysroot(StringRef Path) {
136   if (Config->Sysroot == "")
137     return false;
138   for (; !Path.empty(); Path = sys::path::parent_path(Path))
139     if (sys::fs::equivalent(Config->Sysroot, Path))
140       return true;
141   return false;
142 }
143 
144 // Some operations only support one non absolute value. Move the
145 // absolute one to the right hand side for convenience.
146 static void moveAbsRight(ExprValue &A, ExprValue &B) {
147   if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute()))
148     std::swap(A, B);
149   if (!B.isAbsolute())
150     error(A.Loc + ": at least one side of the expression must be absolute");
151 }
152 
153 static ExprValue add(ExprValue A, ExprValue B) {
154   moveAbsRight(A, B);
155   return {A.Sec, A.ForceAbsolute, A.getSectionOffset() + B.getValue(), A.Loc};
156 }
157 
158 static ExprValue sub(ExprValue A, ExprValue B) {
159   // The distance between two symbols in sections is absolute.
160   if (!A.isAbsolute() && !B.isAbsolute())
161     return A.getValue() - B.getValue();
162   return {A.Sec, false, A.getSectionOffset() - B.getValue(), A.Loc};
163 }
164 
165 static ExprValue bitAnd(ExprValue A, ExprValue B) {
166   moveAbsRight(A, B);
167   return {A.Sec, A.ForceAbsolute,
168           (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc};
169 }
170 
171 static ExprValue bitOr(ExprValue A, ExprValue B) {
172   moveAbsRight(A, B);
173   return {A.Sec, A.ForceAbsolute,
174           (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc};
175 }
176 
177 void ScriptParser::readDynamicList() {
178   Config->HasDynamicList = true;
179   expect("{");
180   std::vector<SymbolVersion> Locals;
181   std::vector<SymbolVersion> Globals;
182   std::tie(Locals, Globals) = readSymbols();
183   expect(";");
184 
185   if (!atEOF()) {
186     setError("EOF expected, but got " + next());
187     return;
188   }
189   if (!Locals.empty()) {
190     setError("\"local:\" scope not supported in --dynamic-list");
191     return;
192   }
193 
194   for (SymbolVersion V : Globals)
195     Config->DynamicList.push_back(V);
196 }
197 
198 void ScriptParser::readVersionScript() {
199   readVersionScriptCommand();
200   if (!atEOF())
201     setError("EOF expected, but got " + next());
202 }
203 
204 void ScriptParser::readVersionScriptCommand() {
205   if (consume("{")) {
206     readAnonymousDeclaration();
207     return;
208   }
209 
210   while (!atEOF() && !errorCount() && peek() != "}") {
211     StringRef VerStr = next();
212     if (VerStr == "{") {
213       setError("anonymous version definition is used in "
214                "combination with other version definitions");
215       return;
216     }
217     expect("{");
218     readVersionDeclaration(VerStr);
219   }
220 }
221 
222 void ScriptParser::readVersion() {
223   expect("{");
224   readVersionScriptCommand();
225   expect("}");
226 }
227 
228 void ScriptParser::readLinkerScript() {
229   while (!atEOF()) {
230     StringRef Tok = next();
231     if (Tok == ";")
232       continue;
233 
234     if (Tok == "ENTRY") {
235       readEntry();
236     } else if (Tok == "EXTERN") {
237       readExtern();
238     } else if (Tok == "GROUP") {
239       readGroup();
240     } else if (Tok == "INCLUDE") {
241       readInclude();
242     } else if (Tok == "INPUT") {
243       readInput();
244     } else if (Tok == "MEMORY") {
245       readMemory();
246     } else if (Tok == "OUTPUT") {
247       readOutput();
248     } else if (Tok == "OUTPUT_ARCH") {
249       readOutputArch();
250     } else if (Tok == "OUTPUT_FORMAT") {
251       readOutputFormat();
252     } else if (Tok == "PHDRS") {
253       readPhdrs();
254     } else if (Tok == "REGION_ALIAS") {
255       readRegionAlias();
256     } else if (Tok == "SEARCH_DIR") {
257       readSearchDir();
258     } else if (Tok == "SECTIONS") {
259       readSections();
260     } else if (Tok == "TARGET") {
261       readTarget();
262     } else if (Tok == "VERSION") {
263       readVersion();
264     } else if (SymbolAssignment *Cmd = readAssignment(Tok)) {
265       Script->SectionCommands.push_back(Cmd);
266     } else {
267       setError("unknown directive: " + Tok);
268     }
269   }
270 }
271 
272 void ScriptParser::readDefsym(StringRef Name) {
273   if (errorCount())
274     return;
275   Expr E = readExpr();
276   if (!atEOF())
277     setError("EOF expected, but got " + next());
278   SymbolAssignment *Cmd = make<SymbolAssignment>(Name, E, getCurrentLocation());
279   Script->SectionCommands.push_back(Cmd);
280 }
281 
282 void ScriptParser::addFile(StringRef S) {
283   if (IsUnderSysroot && S.startswith("/")) {
284     SmallString<128> PathData;
285     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
286     if (sys::fs::exists(Path)) {
287       Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
288       return;
289     }
290   }
291 
292   if (S.startswith("/")) {
293     Driver->addFile(S, /*WithLOption=*/false);
294   } else if (S.startswith("=")) {
295     if (Config->Sysroot.empty())
296       Driver->addFile(S.substr(1), /*WithLOption=*/false);
297     else
298       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
299                       /*WithLOption=*/false);
300   } else if (S.startswith("-l")) {
301     Driver->addLibrary(S.substr(2));
302   } else if (sys::fs::exists(S)) {
303     Driver->addFile(S, /*WithLOption=*/false);
304   } else {
305     if (Optional<std::string> Path = findFromSearchPaths(S))
306       Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
307     else
308       setError("unable to find " + S);
309   }
310 }
311 
312 void ScriptParser::readAsNeeded() {
313   expect("(");
314   bool Orig = Config->AsNeeded;
315   Config->AsNeeded = true;
316   while (!errorCount() && !consume(")"))
317     addFile(unquote(next()));
318   Config->AsNeeded = Orig;
319 }
320 
321 void ScriptParser::readEntry() {
322   // -e <symbol> takes predecence over ENTRY(<symbol>).
323   expect("(");
324   StringRef Tok = next();
325   if (Config->Entry.empty())
326     Config->Entry = Tok;
327   expect(")");
328 }
329 
330 void ScriptParser::readExtern() {
331   expect("(");
332   while (!errorCount() && !consume(")"))
333     Config->Undefined.push_back(next());
334 }
335 
336 void ScriptParser::readGroup() {
337   bool Orig = InputFile::IsInGroup;
338   InputFile::IsInGroup = true;
339   readInput();
340   InputFile::IsInGroup = Orig;
341   if (!Orig)
342     ++InputFile::NextGroupId;
343 }
344 
345 void ScriptParser::readInclude() {
346   StringRef Tok = unquote(next());
347 
348   if (!Seen.insert(Tok).second) {
349     setError("there is a cycle in linker script INCLUDEs");
350     return;
351   }
352 
353   if (Optional<std::string> Path = searchScript(Tok)) {
354     if (Optional<MemoryBufferRef> MB = readFile(*Path))
355       tokenize(*MB);
356     return;
357   }
358   setError("cannot find linker script " + Tok);
359 }
360 
361 void ScriptParser::readInput() {
362   expect("(");
363   while (!errorCount() && !consume(")")) {
364     if (consume("AS_NEEDED"))
365       readAsNeeded();
366     else
367       addFile(unquote(next()));
368   }
369 }
370 
371 void ScriptParser::readOutput() {
372   // -o <file> takes predecence over OUTPUT(<file>).
373   expect("(");
374   StringRef Tok = next();
375   if (Config->OutputFile.empty())
376     Config->OutputFile = unquote(Tok);
377   expect(")");
378 }
379 
380 void ScriptParser::readOutputArch() {
381   // OUTPUT_ARCH is ignored for now.
382   expect("(");
383   while (!errorCount() && !consume(")"))
384     skip();
385 }
386 
387 std::tuple<ELFKind, uint16_t, bool> ScriptParser::readBfdName() {
388   StringRef S = unquote(next());
389   if (S == "elf32-i386")
390     return std::make_tuple(ELF32LEKind, EM_386, false);
391   if (S == "elf32-iamcu")
392     return std::make_tuple(ELF32LEKind, EM_IAMCU, false);
393   if (S == "elf32-littlearm")
394     return std::make_tuple(ELF32LEKind, EM_ARM, false);
395   if (S == "elf32-x86-64")
396     return std::make_tuple(ELF32LEKind, EM_X86_64, false);
397   if (S == "elf64-littleaarch64")
398     return std::make_tuple(ELF64LEKind, EM_AARCH64, false);
399   if (S == "elf64-powerpc")
400     return std::make_tuple(ELF64BEKind, EM_PPC64, false);
401   if (S == "elf64-powerpcle")
402     return std::make_tuple(ELF64LEKind, EM_PPC64, false);
403   if (S == "elf64-x86-64")
404     return std::make_tuple(ELF64LEKind, EM_X86_64, false);
405   if (S == "elf32-tradbigmips")
406     return std::make_tuple(ELF32BEKind, EM_MIPS, false);
407   if (S == "elf32-ntradbigmips")
408     return std::make_tuple(ELF32BEKind, EM_MIPS, true);
409   if (S == "elf32-tradlittlemips")
410     return std::make_tuple(ELF32LEKind, EM_MIPS, false);
411   if (S == "elf32-ntradlittlemips")
412     return std::make_tuple(ELF32LEKind, EM_MIPS, true);
413   if (S == "elf64-tradbigmips")
414     return std::make_tuple(ELF64BEKind, EM_MIPS, false);
415   if (S == "elf64-tradlittlemips")
416     return std::make_tuple(ELF64LEKind, EM_MIPS, false);
417 
418   setError("unknown output format name: " + S);
419   return std::make_tuple(ELFNoneKind, EM_NONE, false);
420 }
421 
422 // Parse OUTPUT_FORMAT(bfdname) or OUTPUT_FORMAT(bfdname, big, little).
423 // Currently we ignore big and little parameters.
424 void ScriptParser::readOutputFormat() {
425   expect("(");
426 
427   std::tuple<ELFKind, uint16_t, bool> BfdTuple = readBfdName();
428   if (Config->EKind == ELFNoneKind)
429     std::tie(Config->EKind, Config->EMachine, Config->MipsN32Abi) = BfdTuple;
430 
431   if (consume(")"))
432     return;
433   expect(",");
434   skip();
435   expect(",");
436   skip();
437   expect(")");
438 }
439 
440 void ScriptParser::readPhdrs() {
441   expect("{");
442 
443   while (!errorCount() && !consume("}")) {
444     PhdrsCommand Cmd;
445     Cmd.Name = next();
446     Cmd.Type = readPhdrType();
447 
448     while (!errorCount() && !consume(";")) {
449       if (consume("FILEHDR"))
450         Cmd.HasFilehdr = true;
451       else if (consume("PHDRS"))
452         Cmd.HasPhdrs = true;
453       else if (consume("AT"))
454         Cmd.LMAExpr = readParenExpr();
455       else if (consume("FLAGS"))
456         Cmd.Flags = readParenExpr()().getValue();
457       else
458         setError("unexpected header attribute: " + next());
459     }
460 
461     Script->PhdrsCommands.push_back(Cmd);
462   }
463 }
464 
465 void ScriptParser::readRegionAlias() {
466   expect("(");
467   StringRef Alias = unquote(next());
468   expect(",");
469   StringRef Name = next();
470   expect(")");
471 
472   if (Script->MemoryRegions.count(Alias))
473     setError("redefinition of memory region '" + Alias + "'");
474   if (!Script->MemoryRegions.count(Name))
475     setError("memory region '" + Name + "' is not defined");
476   Script->MemoryRegions.insert({Alias, Script->MemoryRegions[Name]});
477 }
478 
479 void ScriptParser::readSearchDir() {
480   expect("(");
481   StringRef Tok = next();
482   if (!Config->Nostdlib)
483     Config->SearchPaths.push_back(unquote(Tok));
484   expect(")");
485 }
486 
487 // This reads an overlay description. Overlays are used to describe output
488 // sections that use the same virtual memory range and normally would trigger
489 // linker's sections sanity check failures.
490 // https://sourceware.org/binutils/docs/ld/Overlay-Description.html#Overlay-Description
491 std::vector<BaseCommand *> ScriptParser::readOverlay() {
492   // VA and LMA expressions are optional, though for simplicity of
493   // implementation we assume they are not. That is what OVERLAY was designed
494   // for first of all: to allow sections with overlapping VAs at different LMAs.
495   Expr AddrExpr = readExpr();
496   expect(":");
497   expect("AT");
498   Expr LMAExpr = readParenExpr();
499   expect("{");
500 
501   std::vector<BaseCommand *> V;
502   OutputSection *Prev = nullptr;
503   while (!errorCount() && !consume("}")) {
504     // VA is the same for all sections. The LMAs are consecutive in memory
505     // starting from the base load address specified.
506     OutputSection *OS = readOverlaySectionDescription();
507     OS->AddrExpr = AddrExpr;
508     if (Prev)
509       OS->LMAExpr = [=] { return Prev->getLMA() + Prev->Size; };
510     else
511       OS->LMAExpr = LMAExpr;
512     V.push_back(OS);
513     Prev = OS;
514   }
515 
516   // According to the specification, at the end of the overlay, the location
517   // counter should be equal to the overlay base address plus size of the
518   // largest section seen in the overlay.
519   // Here we want to create the Dot assignment command to achieve that.
520   Expr MoveDot = [=] {
521     uint64_t Max = 0;
522     for (BaseCommand *Cmd : V)
523       Max = std::max(Max, cast<OutputSection>(Cmd)->Size);
524     return AddrExpr().getValue() + Max;
525   };
526   V.push_back(make<SymbolAssignment>(".", MoveDot, getCurrentLocation()));
527   return V;
528 }
529 
530 void ScriptParser::readSections() {
531   Script->HasSectionsCommand = true;
532 
533   // -no-rosegment is used to avoid placing read only non-executable sections in
534   // their own segment. We do the same if SECTIONS command is present in linker
535   // script. See comment for computeFlags().
536   Config->SingleRoRx = true;
537 
538   expect("{");
539   std::vector<BaseCommand *> V;
540   while (!errorCount() && !consume("}")) {
541     StringRef Tok = next();
542     if (Tok == "OVERLAY") {
543       for (BaseCommand *Cmd : readOverlay())
544         V.push_back(Cmd);
545       continue;
546     } else if (Tok == "INCLUDE") {
547       readInclude();
548       continue;
549     }
550 
551     if (BaseCommand *Cmd = readAssignment(Tok))
552       V.push_back(Cmd);
553     else
554       V.push_back(readOutputSectionDescription(Tok));
555   }
556 
557   if (!atEOF() && consume("INSERT")) {
558     std::vector<BaseCommand *> *Dest = nullptr;
559     if (consume("AFTER"))
560       Dest = &Script->InsertAfterCommands[next()];
561     else if (consume("BEFORE"))
562       Dest = &Script->InsertBeforeCommands[next()];
563     else
564       setError("expected AFTER/BEFORE, but got '" + next() + "'");
565     if (Dest)
566       Dest->insert(Dest->end(), V.begin(), V.end());
567     return;
568   }
569 
570   Script->SectionCommands.insert(Script->SectionCommands.end(), V.begin(),
571                                  V.end());
572 }
573 
574 void ScriptParser::readTarget() {
575   // TARGET(foo) is an alias for "--format foo". Unlike GNU linkers,
576   // we accept only a limited set of BFD names (i.e. "elf" or "binary")
577   // for --format. We recognize only /^elf/ and "binary" in the linker
578   // script as well.
579   expect("(");
580   StringRef Tok = next();
581   expect(")");
582 
583   if (Tok.startswith("elf"))
584     Config->FormatBinary = false;
585   else if (Tok == "binary")
586     Config->FormatBinary = true;
587   else
588     setError("unknown target: " + Tok);
589 }
590 
591 static int precedence(StringRef Op) {
592   return StringSwitch<int>(Op)
593       .Cases("*", "/", "%", 8)
594       .Cases("+", "-", 7)
595       .Cases("<<", ">>", 6)
596       .Cases("<", "<=", ">", ">=", "==", "!=", 5)
597       .Case("&", 4)
598       .Case("|", 3)
599       .Case("&&", 2)
600       .Case("||", 1)
601       .Default(-1);
602 }
603 
604 StringMatcher ScriptParser::readFilePatterns() {
605   std::vector<StringRef> V;
606   while (!errorCount() && !consume(")"))
607     V.push_back(next());
608   return StringMatcher(V);
609 }
610 
611 SortSectionPolicy ScriptParser::readSortKind() {
612   if (consume("SORT") || consume("SORT_BY_NAME"))
613     return SortSectionPolicy::Name;
614   if (consume("SORT_BY_ALIGNMENT"))
615     return SortSectionPolicy::Alignment;
616   if (consume("SORT_BY_INIT_PRIORITY"))
617     return SortSectionPolicy::Priority;
618   if (consume("SORT_NONE"))
619     return SortSectionPolicy::None;
620   return SortSectionPolicy::Default;
621 }
622 
623 // Reads SECTIONS command contents in the following form:
624 //
625 // <contents> ::= <elem>*
626 // <elem>     ::= <exclude>? <glob-pattern>
627 // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
628 //
629 // For example,
630 //
631 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
632 //
633 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
634 // The semantics of that is section .foo in any file, section .bar in
635 // any file but a.o, and section .baz in any file but b.o.
636 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
637   std::vector<SectionPattern> Ret;
638   while (!errorCount() && peek() != ")") {
639     StringMatcher ExcludeFilePat;
640     if (consume("EXCLUDE_FILE")) {
641       expect("(");
642       ExcludeFilePat = readFilePatterns();
643     }
644 
645     std::vector<StringRef> V;
646     while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE")
647       V.push_back(next());
648 
649     if (!V.empty())
650       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
651     else
652       setError("section pattern is expected");
653   }
654   return Ret;
655 }
656 
657 // Reads contents of "SECTIONS" directive. That directive contains a
658 // list of glob patterns for input sections. The grammar is as follows.
659 //
660 // <patterns> ::= <section-list>
661 //              | <sort> "(" <section-list> ")"
662 //              | <sort> "(" <sort> "(" <section-list> ")" ")"
663 //
664 // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
665 //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
666 //
667 // <section-list> is parsed by readInputSectionsList().
668 InputSectionDescription *
669 ScriptParser::readInputSectionRules(StringRef FilePattern) {
670   auto *Cmd = make<InputSectionDescription>(FilePattern);
671   expect("(");
672 
673   while (!errorCount() && !consume(")")) {
674     SortSectionPolicy Outer = readSortKind();
675     SortSectionPolicy Inner = SortSectionPolicy::Default;
676     std::vector<SectionPattern> V;
677     if (Outer != SortSectionPolicy::Default) {
678       expect("(");
679       Inner = readSortKind();
680       if (Inner != SortSectionPolicy::Default) {
681         expect("(");
682         V = readInputSectionsList();
683         expect(")");
684       } else {
685         V = readInputSectionsList();
686       }
687       expect(")");
688     } else {
689       V = readInputSectionsList();
690     }
691 
692     for (SectionPattern &Pat : V) {
693       Pat.SortInner = Inner;
694       Pat.SortOuter = Outer;
695     }
696 
697     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
698   }
699   return Cmd;
700 }
701 
702 InputSectionDescription *
703 ScriptParser::readInputSectionDescription(StringRef Tok) {
704   // Input section wildcard can be surrounded by KEEP.
705   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
706   if (Tok == "KEEP") {
707     expect("(");
708     StringRef FilePattern = next();
709     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
710     expect(")");
711     Script->KeptSections.push_back(Cmd);
712     return Cmd;
713   }
714   return readInputSectionRules(Tok);
715 }
716 
717 void ScriptParser::readSort() {
718   expect("(");
719   expect("CONSTRUCTORS");
720   expect(")");
721 }
722 
723 Expr ScriptParser::readAssert() {
724   expect("(");
725   Expr E = readExpr();
726   expect(",");
727   StringRef Msg = unquote(next());
728   expect(")");
729 
730   return [=] {
731     if (!E().getValue())
732       error(Msg);
733     return Script->getDot();
734   };
735 }
736 
737 // Reads a FILL(expr) command. We handle the FILL command as an
738 // alias for =fillexp section attribute, which is different from
739 // what GNU linkers do.
740 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
741 std::array<uint8_t, 4> ScriptParser::readFill() {
742   expect("(");
743   std::array<uint8_t, 4> V = parseFill(next());
744   expect(")");
745   return V;
746 }
747 
748 // Tries to read the special directive for an output section definition which
749 // can be one of following: "(NOLOAD)", "(COPY)", "(INFO)" or "(OVERLAY)".
750 // Tok1 and Tok2 are next 2 tokens peeked. See comment for readSectionAddressType below.
751 bool ScriptParser::readSectionDirective(OutputSection *Cmd, StringRef Tok1, StringRef Tok2) {
752   if (Tok1 != "(")
753     return false;
754   if (Tok2 != "NOLOAD" && Tok2 != "COPY" && Tok2 != "INFO" && Tok2 != "OVERLAY")
755     return false;
756 
757   expect("(");
758   if (consume("NOLOAD")) {
759     Cmd->Noload = true;
760   } else {
761     skip(); // This is "COPY", "INFO" or "OVERLAY".
762     Cmd->NonAlloc = true;
763   }
764   expect(")");
765   return true;
766 }
767 
768 // Reads an expression and/or the special directive for an output
769 // section definition. Directive is one of following: "(NOLOAD)",
770 // "(COPY)", "(INFO)" or "(OVERLAY)".
771 //
772 // An output section name can be followed by an address expression
773 // and/or directive. This grammar is not LL(1) because "(" can be
774 // interpreted as either the beginning of some expression or beginning
775 // of directive.
776 //
777 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
778 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
779 void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
780   if (readSectionDirective(Cmd, peek(), peek2()))
781     return;
782 
783   Cmd->AddrExpr = readExpr();
784   if (peek() == "(" && !readSectionDirective(Cmd, "(", peek2()))
785     setError("unknown section directive: " + peek2());
786 }
787 
788 static Expr checkAlignment(Expr E, std::string &Loc) {
789   return [=] {
790     uint64_t Alignment = std::max((uint64_t)1, E().getValue());
791     if (!isPowerOf2_64(Alignment)) {
792       error(Loc + ": alignment must be power of 2");
793       return (uint64_t)1; // Return a dummy value.
794     }
795     return Alignment;
796   };
797 }
798 
799 OutputSection *ScriptParser::readOverlaySectionDescription() {
800   OutputSection *Cmd =
801       Script->createOutputSection(next(), getCurrentLocation());
802   Cmd->InOverlay = true;
803   expect("{");
804   while (!errorCount() && !consume("}"))
805     Cmd->SectionCommands.push_back(readInputSectionRules(next()));
806   Cmd->Phdrs = readOutputSectionPhdrs();
807   return Cmd;
808 }
809 
810 OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
811   OutputSection *Cmd =
812       Script->createOutputSection(OutSec, getCurrentLocation());
813 
814   size_t SymbolsReferenced = Script->ReferencedSymbols.size();
815 
816   if (peek() != ":")
817     readSectionAddressType(Cmd);
818   expect(":");
819 
820   std::string Location = getCurrentLocation();
821   if (consume("AT"))
822     Cmd->LMAExpr = readParenExpr();
823   if (consume("ALIGN"))
824     Cmd->AlignExpr = checkAlignment(readParenExpr(), Location);
825   if (consume("SUBALIGN"))
826     Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location);
827 
828   // Parse constraints.
829   if (consume("ONLY_IF_RO"))
830     Cmd->Constraint = ConstraintKind::ReadOnly;
831   if (consume("ONLY_IF_RW"))
832     Cmd->Constraint = ConstraintKind::ReadWrite;
833   expect("{");
834 
835   while (!errorCount() && !consume("}")) {
836     StringRef Tok = next();
837     if (Tok == ";") {
838       // Empty commands are allowed. Do nothing here.
839     } else if (SymbolAssignment *Assign = readAssignment(Tok)) {
840       Cmd->SectionCommands.push_back(Assign);
841     } else if (ByteCommand *Data = readByteCommand(Tok)) {
842       Cmd->SectionCommands.push_back(Data);
843     } else if (Tok == "CONSTRUCTORS") {
844       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
845       // by name. This is for very old file formats such as ECOFF/XCOFF.
846       // For ELF, we should ignore.
847     } else if (Tok == "FILL") {
848       Cmd->Filler = readFill();
849     } else if (Tok == "SORT") {
850       readSort();
851     } else if (Tok == "INCLUDE") {
852       readInclude();
853     } else if (peek() == "(") {
854       Cmd->SectionCommands.push_back(readInputSectionDescription(Tok));
855     } else {
856       // We have a file name and no input sections description. It is not a
857       // commonly used syntax, but still acceptable. In that case, all sections
858       // from the file will be included.
859       auto *ISD = make<InputSectionDescription>(Tok);
860       ISD->SectionPatterns.push_back({{}, StringMatcher({"*"})});
861       Cmd->SectionCommands.push_back(ISD);
862     }
863   }
864 
865   if (consume(">"))
866     Cmd->MemoryRegionName = next();
867 
868   if (consume("AT")) {
869     expect(">");
870     Cmd->LMARegionName = next();
871   }
872 
873   if (Cmd->LMAExpr && !Cmd->LMARegionName.empty())
874     error("section can't have both LMA and a load region");
875 
876   Cmd->Phdrs = readOutputSectionPhdrs();
877 
878   if (consume("="))
879     Cmd->Filler = parseFill(next());
880   else if (peek().startswith("="))
881     Cmd->Filler = parseFill(next().drop_front());
882 
883   // Consume optional comma following output section command.
884   consume(",");
885 
886   if (Script->ReferencedSymbols.size() > SymbolsReferenced)
887     Cmd->ExpressionsUseSymbols = true;
888   return Cmd;
889 }
890 
891 // Parses a given string as a octal/decimal/hexadecimal number and
892 // returns it as a big-endian number. Used for `=<fillexp>`.
893 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
894 //
895 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
896 // size, while ld.gold always handles it as a 32-bit big-endian number.
897 // We are compatible with ld.gold because it's easier to implement.
898 std::array<uint8_t, 4> ScriptParser::parseFill(StringRef Tok) {
899   uint32_t V = 0;
900   if (!to_integer(Tok, V))
901     setError("invalid filler expression: " + Tok);
902 
903   std::array<uint8_t, 4> Buf;
904   write32be(Buf.data(), V);
905   return Buf;
906 }
907 
908 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
909   expect("(");
910   SymbolAssignment *Cmd = readSymbolAssignment(next());
911   Cmd->Provide = Provide;
912   Cmd->Hidden = Hidden;
913   expect(")");
914   return Cmd;
915 }
916 
917 SymbolAssignment *ScriptParser::readAssignment(StringRef Tok) {
918   // Assert expression returns Dot, so this is equal to ".=."
919   if (Tok == "ASSERT")
920     return make<SymbolAssignment>(".", readAssert(), getCurrentLocation());
921 
922   size_t OldPos = Pos;
923   SymbolAssignment *Cmd = nullptr;
924   if (peek() == "=" || peek() == "+=")
925     Cmd = readSymbolAssignment(Tok);
926   else if (Tok == "PROVIDE")
927     Cmd = readProvideHidden(true, false);
928   else if (Tok == "HIDDEN")
929     Cmd = readProvideHidden(false, true);
930   else if (Tok == "PROVIDE_HIDDEN")
931     Cmd = readProvideHidden(true, true);
932 
933   if (Cmd) {
934     Cmd->CommandString =
935         Tok.str() + " " +
936         llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " ");
937     expect(";");
938   }
939   return Cmd;
940 }
941 
942 SymbolAssignment *ScriptParser::readSymbolAssignment(StringRef Name) {
943   StringRef Op = next();
944   assert(Op == "=" || Op == "+=");
945   Expr E = readExpr();
946   if (Op == "+=") {
947     std::string Loc = getCurrentLocation();
948     E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); };
949   }
950   return make<SymbolAssignment>(Name, E, getCurrentLocation());
951 }
952 
953 // This is an operator-precedence parser to parse a linker
954 // script expression.
955 Expr ScriptParser::readExpr() {
956   // Our lexer is context-aware. Set the in-expression bit so that
957   // they apply different tokenization rules.
958   bool Orig = InExpr;
959   InExpr = true;
960   Expr E = readExpr1(readPrimary(), 0);
961   InExpr = Orig;
962   return E;
963 }
964 
965 Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
966   if (Op == "+")
967     return [=] { return add(L(), R()); };
968   if (Op == "-")
969     return [=] { return sub(L(), R()); };
970   if (Op == "*")
971     return [=] { return L().getValue() * R().getValue(); };
972   if (Op == "/") {
973     std::string Loc = getCurrentLocation();
974     return [=]() -> uint64_t {
975       if (uint64_t RV = R().getValue())
976         return L().getValue() / RV;
977       error(Loc + ": division by zero");
978       return 0;
979     };
980   }
981   if (Op == "%") {
982     std::string Loc = getCurrentLocation();
983     return [=]() -> uint64_t {
984       if (uint64_t RV = R().getValue())
985         return L().getValue() % RV;
986       error(Loc + ": modulo by zero");
987       return 0;
988     };
989   }
990   if (Op == "<<")
991     return [=] { return L().getValue() << R().getValue(); };
992   if (Op == ">>")
993     return [=] { return L().getValue() >> R().getValue(); };
994   if (Op == "<")
995     return [=] { return L().getValue() < R().getValue(); };
996   if (Op == ">")
997     return [=] { return L().getValue() > R().getValue(); };
998   if (Op == ">=")
999     return [=] { return L().getValue() >= R().getValue(); };
1000   if (Op == "<=")
1001     return [=] { return L().getValue() <= R().getValue(); };
1002   if (Op == "==")
1003     return [=] { return L().getValue() == R().getValue(); };
1004   if (Op == "!=")
1005     return [=] { return L().getValue() != R().getValue(); };
1006   if (Op == "||")
1007     return [=] { return L().getValue() || R().getValue(); };
1008   if (Op == "&&")
1009     return [=] { return L().getValue() && R().getValue(); };
1010   if (Op == "&")
1011     return [=] { return bitAnd(L(), R()); };
1012   if (Op == "|")
1013     return [=] { return bitOr(L(), R()); };
1014   llvm_unreachable("invalid operator");
1015 }
1016 
1017 // This is a part of the operator-precedence parser. This function
1018 // assumes that the remaining token stream starts with an operator.
1019 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1020   while (!atEOF() && !errorCount()) {
1021     // Read an operator and an expression.
1022     if (consume("?"))
1023       return readTernary(Lhs);
1024     StringRef Op1 = peek();
1025     if (precedence(Op1) < MinPrec)
1026       break;
1027     skip();
1028     Expr Rhs = readPrimary();
1029 
1030     // Evaluate the remaining part of the expression first if the
1031     // next operator has greater precedence than the previous one.
1032     // For example, if we have read "+" and "3", and if the next
1033     // operator is "*", then we'll evaluate 3 * ... part first.
1034     while (!atEOF()) {
1035       StringRef Op2 = peek();
1036       if (precedence(Op2) <= precedence(Op1))
1037         break;
1038       Rhs = readExpr1(Rhs, precedence(Op2));
1039     }
1040 
1041     Lhs = combine(Op1, Lhs, Rhs);
1042   }
1043   return Lhs;
1044 }
1045 
1046 Expr ScriptParser::getPageSize() {
1047   std::string Location = getCurrentLocation();
1048   return [=]() -> uint64_t {
1049     if (Target)
1050       return Target->PageSize;
1051     error(Location + ": unable to calculate page size");
1052     return 4096; // Return a dummy value.
1053   };
1054 }
1055 
1056 Expr ScriptParser::readConstant() {
1057   StringRef S = readParenLiteral();
1058   if (S == "COMMONPAGESIZE")
1059     return getPageSize();
1060   if (S == "MAXPAGESIZE")
1061     return [] { return Config->MaxPageSize; };
1062   setError("unknown constant: " + S);
1063   return [] { return 0; };
1064 }
1065 
1066 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
1067 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
1068 // have "K" (Ki) or "M" (Mi) suffixes.
1069 static Optional<uint64_t> parseInt(StringRef Tok) {
1070   // Hexadecimal
1071   uint64_t Val;
1072   if (Tok.startswith_lower("0x")) {
1073     if (!to_integer(Tok.substr(2), Val, 16))
1074       return None;
1075     return Val;
1076   }
1077   if (Tok.endswith_lower("H")) {
1078     if (!to_integer(Tok.drop_back(), Val, 16))
1079       return None;
1080     return Val;
1081   }
1082 
1083   // Decimal
1084   if (Tok.endswith_lower("K")) {
1085     if (!to_integer(Tok.drop_back(), Val, 10))
1086       return None;
1087     return Val * 1024;
1088   }
1089   if (Tok.endswith_lower("M")) {
1090     if (!to_integer(Tok.drop_back(), Val, 10))
1091       return None;
1092     return Val * 1024 * 1024;
1093   }
1094   if (!to_integer(Tok, Val, 10))
1095     return None;
1096   return Val;
1097 }
1098 
1099 ByteCommand *ScriptParser::readByteCommand(StringRef Tok) {
1100   int Size = StringSwitch<int>(Tok)
1101                  .Case("BYTE", 1)
1102                  .Case("SHORT", 2)
1103                  .Case("LONG", 4)
1104                  .Case("QUAD", 8)
1105                  .Default(-1);
1106   if (Size == -1)
1107     return nullptr;
1108 
1109   size_t OldPos = Pos;
1110   Expr E = readParenExpr();
1111   std::string CommandString =
1112       Tok.str() + " " +
1113       llvm::join(Tokens.begin() + OldPos, Tokens.begin() + Pos, " ");
1114   return make<ByteCommand>(E, Size, CommandString);
1115 }
1116 
1117 StringRef ScriptParser::readParenLiteral() {
1118   expect("(");
1119   bool Orig = InExpr;
1120   InExpr = false;
1121   StringRef Tok = next();
1122   InExpr = Orig;
1123   expect(")");
1124   return Tok;
1125 }
1126 
1127 static void checkIfExists(OutputSection *Cmd, StringRef Location) {
1128   if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
1129     error(Location + ": undefined section " + Cmd->Name);
1130 }
1131 
1132 Expr ScriptParser::readPrimary() {
1133   if (peek() == "(")
1134     return readParenExpr();
1135 
1136   if (consume("~")) {
1137     Expr E = readPrimary();
1138     return [=] { return ~E().getValue(); };
1139   }
1140   if (consume("!")) {
1141     Expr E = readPrimary();
1142     return [=] { return !E().getValue(); };
1143   }
1144   if (consume("-")) {
1145     Expr E = readPrimary();
1146     return [=] { return -E().getValue(); };
1147   }
1148 
1149   StringRef Tok = next();
1150   std::string Location = getCurrentLocation();
1151 
1152   // Built-in functions are parsed here.
1153   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1154   if (Tok == "ABSOLUTE") {
1155     Expr Inner = readParenExpr();
1156     return [=] {
1157       ExprValue I = Inner();
1158       I.ForceAbsolute = true;
1159       return I;
1160     };
1161   }
1162   if (Tok == "ADDR") {
1163     StringRef Name = readParenLiteral();
1164     OutputSection *Sec = Script->getOrCreateOutputSection(Name);
1165     return [=]() -> ExprValue {
1166       checkIfExists(Sec, Location);
1167       return {Sec, false, 0, Location};
1168     };
1169   }
1170   if (Tok == "ALIGN") {
1171     expect("(");
1172     Expr E = readExpr();
1173     if (consume(")")) {
1174       E = checkAlignment(E, Location);
1175       return [=] { return alignTo(Script->getDot(), E().getValue()); };
1176     }
1177     expect(",");
1178     Expr E2 = checkAlignment(readExpr(), Location);
1179     expect(")");
1180     return [=] {
1181       ExprValue V = E();
1182       V.Alignment = E2().getValue();
1183       return V;
1184     };
1185   }
1186   if (Tok == "ALIGNOF") {
1187     StringRef Name = readParenLiteral();
1188     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1189     return [=] {
1190       checkIfExists(Cmd, Location);
1191       return Cmd->Alignment;
1192     };
1193   }
1194   if (Tok == "ASSERT")
1195     return readAssert();
1196   if (Tok == "CONSTANT")
1197     return readConstant();
1198   if (Tok == "DATA_SEGMENT_ALIGN") {
1199     expect("(");
1200     Expr E = readExpr();
1201     expect(",");
1202     readExpr();
1203     expect(")");
1204     return [=] {
1205       return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
1206     };
1207   }
1208   if (Tok == "DATA_SEGMENT_END") {
1209     expect("(");
1210     expect(".");
1211     expect(")");
1212     return [] { return Script->getDot(); };
1213   }
1214   if (Tok == "DATA_SEGMENT_RELRO_END") {
1215     // GNU linkers implements more complicated logic to handle
1216     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1217     // just align to the next page boundary for simplicity.
1218     expect("(");
1219     readExpr();
1220     expect(",");
1221     readExpr();
1222     expect(")");
1223     Expr E = getPageSize();
1224     return [=] { return alignTo(Script->getDot(), E().getValue()); };
1225   }
1226   if (Tok == "DEFINED") {
1227     StringRef Name = readParenLiteral();
1228     return [=] { return Symtab->find(Name) ? 1 : 0; };
1229   }
1230   if (Tok == "LENGTH") {
1231     StringRef Name = readParenLiteral();
1232     if (Script->MemoryRegions.count(Name) == 0) {
1233       setError("memory region not defined: " + Name);
1234       return [] { return 0; };
1235     }
1236     return [=] { return Script->MemoryRegions[Name]->Length; };
1237   }
1238   if (Tok == "LOADADDR") {
1239     StringRef Name = readParenLiteral();
1240     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1241     return [=] {
1242       checkIfExists(Cmd, Location);
1243       return Cmd->getLMA();
1244     };
1245   }
1246   if (Tok == "MAX" || Tok == "MIN") {
1247     expect("(");
1248     Expr A = readExpr();
1249     expect(",");
1250     Expr B = readExpr();
1251     expect(")");
1252     if (Tok == "MIN")
1253       return [=] { return std::min(A().getValue(), B().getValue()); };
1254     return [=] { return std::max(A().getValue(), B().getValue()); };
1255   }
1256   if (Tok == "ORIGIN") {
1257     StringRef Name = readParenLiteral();
1258     if (Script->MemoryRegions.count(Name) == 0) {
1259       setError("memory region not defined: " + Name);
1260       return [] { return 0; };
1261     }
1262     return [=] { return Script->MemoryRegions[Name]->Origin; };
1263   }
1264   if (Tok == "SEGMENT_START") {
1265     expect("(");
1266     skip();
1267     expect(",");
1268     Expr E = readExpr();
1269     expect(")");
1270     return [=] { return E(); };
1271   }
1272   if (Tok == "SIZEOF") {
1273     StringRef Name = readParenLiteral();
1274     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1275     // Linker script does not create an output section if its content is empty.
1276     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1277     // be empty.
1278     return [=] { return Cmd->Size; };
1279   }
1280   if (Tok == "SIZEOF_HEADERS")
1281     return [=] { return elf::getHeaderSize(); };
1282 
1283   // Tok is the dot.
1284   if (Tok == ".")
1285     return [=] { return Script->getSymbolValue(Tok, Location); };
1286 
1287   // Tok is a literal number.
1288   if (Optional<uint64_t> Val = parseInt(Tok))
1289     return [=] { return *Val; };
1290 
1291   // Tok is a symbol name.
1292   if (!isValidCIdentifier(Tok))
1293     setError("malformed number: " + Tok);
1294   Script->ReferencedSymbols.push_back(Tok);
1295   return [=] { return Script->getSymbolValue(Tok, Location); };
1296 }
1297 
1298 Expr ScriptParser::readTernary(Expr Cond) {
1299   Expr L = readExpr();
1300   expect(":");
1301   Expr R = readExpr();
1302   return [=] { return Cond().getValue() ? L() : R(); };
1303 }
1304 
1305 Expr ScriptParser::readParenExpr() {
1306   expect("(");
1307   Expr E = readExpr();
1308   expect(")");
1309   return E;
1310 }
1311 
1312 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1313   std::vector<StringRef> Phdrs;
1314   while (!errorCount() && peek().startswith(":")) {
1315     StringRef Tok = next();
1316     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1317   }
1318   return Phdrs;
1319 }
1320 
1321 // Read a program header type name. The next token must be a
1322 // name of a program header type or a constant (e.g. "0x3").
1323 unsigned ScriptParser::readPhdrType() {
1324   StringRef Tok = next();
1325   if (Optional<uint64_t> Val = parseInt(Tok))
1326     return *Val;
1327 
1328   unsigned Ret = StringSwitch<unsigned>(Tok)
1329                      .Case("PT_NULL", PT_NULL)
1330                      .Case("PT_LOAD", PT_LOAD)
1331                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1332                      .Case("PT_INTERP", PT_INTERP)
1333                      .Case("PT_NOTE", PT_NOTE)
1334                      .Case("PT_SHLIB", PT_SHLIB)
1335                      .Case("PT_PHDR", PT_PHDR)
1336                      .Case("PT_TLS", PT_TLS)
1337                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1338                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1339                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1340                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1341                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1342                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1343                      .Default(-1);
1344 
1345   if (Ret == (unsigned)-1) {
1346     setError("invalid program header type: " + Tok);
1347     return PT_NULL;
1348   }
1349   return Ret;
1350 }
1351 
1352 // Reads an anonymous version declaration.
1353 void ScriptParser::readAnonymousDeclaration() {
1354   std::vector<SymbolVersion> Locals;
1355   std::vector<SymbolVersion> Globals;
1356   std::tie(Locals, Globals) = readSymbols();
1357 
1358   for (SymbolVersion V : Locals) {
1359     if (V.Name == "*")
1360       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1361     else
1362       Config->VersionScriptLocals.push_back(V);
1363   }
1364 
1365   for (SymbolVersion V : Globals)
1366     Config->VersionScriptGlobals.push_back(V);
1367 
1368   expect(";");
1369 }
1370 
1371 // Reads a non-anonymous version definition,
1372 // e.g. "VerStr { global: foo; bar; local: *; };".
1373 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1374   // Read a symbol list.
1375   std::vector<SymbolVersion> Locals;
1376   std::vector<SymbolVersion> Globals;
1377   std::tie(Locals, Globals) = readSymbols();
1378 
1379   for (SymbolVersion V : Locals) {
1380     if (V.Name == "*")
1381       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1382     else
1383       Config->VersionScriptLocals.push_back(V);
1384   }
1385 
1386   // Create a new version definition and add that to the global symbols.
1387   VersionDefinition Ver;
1388   Ver.Name = VerStr;
1389   Ver.Globals = Globals;
1390 
1391   // User-defined version number starts from 2 because 0 and 1 are
1392   // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1393   Ver.Id = Config->VersionDefinitions.size() + 2;
1394   Config->VersionDefinitions.push_back(Ver);
1395 
1396   // Each version may have a parent version. For example, "Ver2"
1397   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1398   // as a parent. This version hierarchy is, probably against your
1399   // instinct, purely for hint; the runtime doesn't care about it
1400   // at all. In LLD, we simply ignore it.
1401   if (peek() != ";")
1402     skip();
1403   expect(";");
1404 }
1405 
1406 static bool hasWildcard(StringRef S) {
1407   return S.find_first_of("?*[") != StringRef::npos;
1408 }
1409 
1410 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1411 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1412 ScriptParser::readSymbols() {
1413   std::vector<SymbolVersion> Locals;
1414   std::vector<SymbolVersion> Globals;
1415   std::vector<SymbolVersion> *V = &Globals;
1416 
1417   while (!errorCount()) {
1418     if (consume("}"))
1419       break;
1420     if (consumeLabel("local")) {
1421       V = &Locals;
1422       continue;
1423     }
1424     if (consumeLabel("global")) {
1425       V = &Globals;
1426       continue;
1427     }
1428 
1429     if (consume("extern")) {
1430       std::vector<SymbolVersion> Ext = readVersionExtern();
1431       V->insert(V->end(), Ext.begin(), Ext.end());
1432     } else {
1433       StringRef Tok = next();
1434       V->push_back({unquote(Tok), false, hasWildcard(Tok)});
1435     }
1436     expect(";");
1437   }
1438   return {Locals, Globals};
1439 }
1440 
1441 // Reads an "extern C++" directive, e.g.,
1442 // "extern "C++" { ns::*; "f(int, double)"; };"
1443 //
1444 // The last semicolon is optional. E.g. this is OK:
1445 // "extern "C++" { ns::*; "f(int, double)" };"
1446 std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
1447   StringRef Tok = next();
1448   bool IsCXX = Tok == "\"C++\"";
1449   if (!IsCXX && Tok != "\"C\"")
1450     setError("Unknown language");
1451   expect("{");
1452 
1453   std::vector<SymbolVersion> Ret;
1454   while (!errorCount() && peek() != "}") {
1455     StringRef Tok = next();
1456     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
1457     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
1458     if (consume("}"))
1459       return Ret;
1460     expect(";");
1461   }
1462 
1463   expect("}");
1464   return Ret;
1465 }
1466 
1467 uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
1468                                             StringRef S3) {
1469   if (!consume(S1) && !consume(S2) && !consume(S3)) {
1470     setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
1471     return 0;
1472   }
1473   expect("=");
1474   return readExpr()().getValue();
1475 }
1476 
1477 // Parse the MEMORY command as specified in:
1478 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1479 //
1480 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1481 void ScriptParser::readMemory() {
1482   expect("{");
1483   while (!errorCount() && !consume("}")) {
1484     StringRef Tok = next();
1485     if (Tok == "INCLUDE") {
1486       readInclude();
1487       continue;
1488     }
1489 
1490     uint32_t Flags = 0;
1491     uint32_t NegFlags = 0;
1492     if (consume("(")) {
1493       std::tie(Flags, NegFlags) = readMemoryAttributes();
1494       expect(")");
1495     }
1496     expect(":");
1497 
1498     uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
1499     expect(",");
1500     uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
1501 
1502     // Add the memory region to the region map.
1503     MemoryRegion *MR = make<MemoryRegion>(Tok, Origin, Length, Flags, NegFlags);
1504     if (!Script->MemoryRegions.insert({Tok, MR}).second)
1505       setError("region '" + Tok + "' already defined");
1506   }
1507 }
1508 
1509 // This function parses the attributes used to match against section
1510 // flags when placing output sections in a memory region. These flags
1511 // are only used when an explicit memory region name is not used.
1512 std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
1513   uint32_t Flags = 0;
1514   uint32_t NegFlags = 0;
1515   bool Invert = false;
1516 
1517   for (char C : next().lower()) {
1518     uint32_t Flag = 0;
1519     if (C == '!')
1520       Invert = !Invert;
1521     else if (C == 'w')
1522       Flag = SHF_WRITE;
1523     else if (C == 'x')
1524       Flag = SHF_EXECINSTR;
1525     else if (C == 'a')
1526       Flag = SHF_ALLOC;
1527     else if (C != 'r')
1528       setError("invalid memory region attribute");
1529 
1530     if (Invert)
1531       NegFlags |= Flag;
1532     else
1533       Flags |= Flag;
1534   }
1535   return {Flags, NegFlags};
1536 }
1537 
1538 void elf::readLinkerScript(MemoryBufferRef MB) {
1539   ScriptParser(MB).readLinkerScript();
1540 }
1541 
1542 void elf::readVersionScript(MemoryBufferRef MB) {
1543   ScriptParser(MB).readVersionScript();
1544 }
1545 
1546 void elf::readDynamicList(MemoryBufferRef MB) {
1547   ScriptParser(MB).readDynamicList();
1548 }
1549 
1550 void elf::readDefsym(StringRef Name, MemoryBufferRef MB) {
1551   ScriptParser(MB).readDefsym(Name);
1552 }
1553