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