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