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