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