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