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