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