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