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   ByteCommand *readByteCommand(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, false, 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->SectionCommands.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->SectionCommands.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->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->MemoryRegions.count(Alias))
422     setError("redefinition of memory region '" + Alias + "'");
423   if (!Script->MemoryRegions.count(Name))
424     setError("memory region '" + Name + "' is not defined");
425   Script->MemoryRegions[Alias] = Script->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->HasSectionsCommand = 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->SectionCommands.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->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 static Expr checkAlignment(Expr E, std::string &Loc) {
646   return [=] {
647     uint64_t Alignment = std::max((uint64_t)1, E().getValue());
648     if (!isPowerOf2_64(Alignment)) {
649       error(Loc + ": alignment must be power of 2");
650       return (uint64_t)1; // Return a dummy value.
651     }
652     return Alignment;
653   };
654 }
655 
656 OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
657   OutputSection *Cmd =
658       Script->createOutputSection(OutSec, getCurrentLocation());
659 
660   if (peek() != ":")
661     readSectionAddressType(Cmd);
662   expect(":");
663 
664   std::string Location = getCurrentLocation();
665   if (consume("AT"))
666     Cmd->LMAExpr = readParenExpr();
667   if (consume("ALIGN"))
668     Cmd->AlignExpr = checkAlignment(readParenExpr(), Location);
669   if (consume("SUBALIGN"))
670     Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location);
671 
672   // Parse constraints.
673   if (consume("ONLY_IF_RO"))
674     Cmd->Constraint = ConstraintKind::ReadOnly;
675   if (consume("ONLY_IF_RW"))
676     Cmd->Constraint = ConstraintKind::ReadWrite;
677   expect("{");
678 
679   while (!ErrorCount && !consume("}")) {
680     StringRef Tok = next();
681     if (Tok == ";") {
682       // Empty commands are allowed. Do nothing here.
683     } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) {
684       Cmd->SectionCommands.push_back(Assign);
685     } else if (ByteCommand *Data = readByteCommand(Tok)) {
686       Cmd->SectionCommands.push_back(Data);
687     } else if (Tok == "ASSERT") {
688       Cmd->SectionCommands.push_back(readAssert());
689       expect(";");
690     } else if (Tok == "CONSTRUCTORS") {
691       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
692       // by name. This is for very old file formats such as ECOFF/XCOFF.
693       // For ELF, we should ignore.
694     } else if (Tok == "FILL") {
695       Cmd->Filler = readFill();
696     } else if (Tok == "SORT") {
697       readSort();
698     } else if (peek() == "(") {
699       Cmd->SectionCommands.push_back(readInputSectionDescription(Tok));
700     } else {
701       setError("unknown command " + Tok);
702     }
703   }
704 
705   if (consume(">"))
706     Cmd->MemoryRegionName = next();
707   else if (peek().startswith(">"))
708     Cmd->MemoryRegionName = next().drop_front();
709 
710   Cmd->Phdrs = readOutputSectionPhdrs();
711 
712   if (consume("="))
713     Cmd->Filler = parseFill(next());
714   else if (peek().startswith("="))
715     Cmd->Filler = parseFill(next().drop_front());
716 
717   // Consume optional comma following output section command.
718   consume(",");
719 
720   return Cmd;
721 }
722 
723 // Parses a given string as a octal/decimal/hexadecimal number and
724 // returns it as a big-endian number. Used for `=<fillexp>`.
725 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
726 //
727 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
728 // size, while ld.gold always handles it as a 32-bit big-endian number.
729 // We are compatible with ld.gold because it's easier to implement.
730 uint32_t ScriptParser::parseFill(StringRef Tok) {
731   uint32_t V = 0;
732   if (!to_integer(Tok, V))
733     setError("invalid filler expression: " + Tok);
734 
735   uint32_t Buf;
736   write32be(&Buf, V);
737   return Buf;
738 }
739 
740 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
741   expect("(");
742   SymbolAssignment *Cmd = readAssignment(next());
743   Cmd->Provide = Provide;
744   Cmd->Hidden = Hidden;
745   expect(")");
746   expect(";");
747   return Cmd;
748 }
749 
750 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
751   SymbolAssignment *Cmd = nullptr;
752   if (peek() == "=" || peek() == "+=") {
753     Cmd = readAssignment(Tok);
754     expect(";");
755   } else if (Tok == "PROVIDE") {
756     Cmd = readProvideHidden(true, false);
757   } else if (Tok == "HIDDEN") {
758     Cmd = readProvideHidden(false, true);
759   } else if (Tok == "PROVIDE_HIDDEN") {
760     Cmd = readProvideHidden(true, true);
761   }
762   return Cmd;
763 }
764 
765 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
766   StringRef Op = next();
767   assert(Op == "=" || Op == "+=");
768   Expr E = readExpr();
769   if (Op == "+=") {
770     std::string Loc = getCurrentLocation();
771     E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); };
772   }
773   return make<SymbolAssignment>(Name, E, getCurrentLocation());
774 }
775 
776 // This is an operator-precedence parser to parse a linker
777 // script expression.
778 Expr ScriptParser::readExpr() {
779   // Our lexer is context-aware. Set the in-expression bit so that
780   // they apply different tokenization rules.
781   bool Orig = InExpr;
782   InExpr = true;
783   Expr E = readExpr1(readPrimary(), 0);
784   InExpr = Orig;
785   return E;
786 }
787 
788 static Expr combine(StringRef Op, Expr L, Expr R) {
789   if (Op == "+")
790     return [=] { return add(L(), R()); };
791   if (Op == "-")
792     return [=] { return sub(L(), R()); };
793   if (Op == "*")
794     return [=] { return mul(L(), R()); };
795   if (Op == "/")
796     return [=] { return div(L(), R()); };
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 L().getValue() < R().getValue(); };
803   if (Op == ">")
804     return [=] { return L().getValue() > R().getValue(); };
805   if (Op == ">=")
806     return [=] { return L().getValue() >= R().getValue(); };
807   if (Op == "<=")
808     return [=] { return L().getValue() <= R().getValue(); };
809   if (Op == "==")
810     return [=] { return L().getValue() == R().getValue(); };
811   if (Op == "!=")
812     return [=] { return L().getValue() != R().getValue(); };
813   if (Op == "&")
814     return [=] { return bitAnd(L(), R()); };
815   if (Op == "|")
816     return [=] { return bitOr(L(), R()); };
817   llvm_unreachable("invalid operator");
818 }
819 
820 // This is a part of the operator-precedence parser. This function
821 // assumes that the remaining token stream starts with an operator.
822 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
823   while (!atEOF() && !ErrorCount) {
824     // Read an operator and an expression.
825     if (consume("?"))
826       return readTernary(Lhs);
827     StringRef Op1 = peek();
828     if (precedence(Op1) < MinPrec)
829       break;
830     skip();
831     Expr Rhs = readPrimary();
832 
833     // Evaluate the remaining part of the expression first if the
834     // next operator has greater precedence than the previous one.
835     // For example, if we have read "+" and "3", and if the next
836     // operator is "*", then we'll evaluate 3 * ... part first.
837     while (!atEOF()) {
838       StringRef Op2 = peek();
839       if (precedence(Op2) <= precedence(Op1))
840         break;
841       Rhs = readExpr1(Rhs, precedence(Op2));
842     }
843 
844     Lhs = combine(Op1, Lhs, Rhs);
845   }
846   return Lhs;
847 }
848 
849 Expr ScriptParser::getPageSize() {
850   std::string Location = getCurrentLocation();
851   return [=]() -> uint64_t {
852     if (Target)
853       return Target->PageSize;
854     error(Location + ": unable to calculate page size");
855     return 4096; // Return a dummy value.
856   };
857 }
858 
859 Expr ScriptParser::readConstant() {
860   StringRef S = readParenLiteral();
861   if (S == "COMMONPAGESIZE")
862     return getPageSize();
863   if (S == "MAXPAGESIZE")
864     return [] { return Config->MaxPageSize; };
865   setError("unknown constant: " + S);
866   return {};
867 }
868 
869 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
870 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
871 // have "K" (Ki) or "M" (Mi) suffixes.
872 static Optional<uint64_t> parseInt(StringRef Tok) {
873   // Negative number
874   if (Tok.startswith("-")) {
875     if (Optional<uint64_t> Val = parseInt(Tok.substr(1)))
876       return -*Val;
877     return None;
878   }
879 
880   // Hexadecimal
881   uint64_t Val;
882   if (Tok.startswith_lower("0x")) {
883     if (!to_integer(Tok.substr(2), Val, 16))
884       return None;
885     return Val;
886   }
887   if (Tok.endswith_lower("H")) {
888     if (!to_integer(Tok.drop_back(), Val, 16))
889       return None;
890     return Val;
891   }
892 
893   // Decimal
894   if (Tok.endswith_lower("K")) {
895     if (!to_integer(Tok.drop_back(), Val, 10))
896       return None;
897     return Val * 1024;
898   }
899   if (Tok.endswith_lower("M")) {
900     if (!to_integer(Tok.drop_back(), Val, 10))
901       return None;
902     return Val * 1024 * 1024;
903   }
904   if (!to_integer(Tok, Val, 10))
905     return None;
906   return Val;
907 }
908 
909 ByteCommand *ScriptParser::readByteCommand(StringRef Tok) {
910   int Size = StringSwitch<int>(Tok)
911                  .Case("BYTE", 1)
912                  .Case("SHORT", 2)
913                  .Case("LONG", 4)
914                  .Case("QUAD", 8)
915                  .Default(-1);
916   if (Size == -1)
917     return nullptr;
918   return make<ByteCommand>(readParenExpr(), Size);
919 }
920 
921 StringRef ScriptParser::readParenLiteral() {
922   expect("(");
923   StringRef Tok = next();
924   expect(")");
925   return Tok;
926 }
927 
928 static void checkIfExists(OutputSection *Cmd, StringRef Location) {
929   if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
930     error(Location + ": undefined section " + Cmd->Name);
931 }
932 
933 Expr ScriptParser::readPrimary() {
934   if (peek() == "(")
935     return readParenExpr();
936 
937   if (consume("~")) {
938     Expr E = readPrimary();
939     return [=] { return ~E().getValue(); };
940   }
941   if (consume("!")) {
942     Expr E = readPrimary();
943     return [=] { return !E().getValue(); };
944   }
945   if (consume("-")) {
946     Expr E = readPrimary();
947     return [=] { return -E().getValue(); };
948   }
949 
950   StringRef Tok = next();
951   std::string Location = getCurrentLocation();
952 
953   // Built-in functions are parsed here.
954   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
955   if (Tok == "ABSOLUTE") {
956     Expr Inner = readParenExpr();
957     return [=] {
958       ExprValue I = Inner();
959       I.ForceAbsolute = true;
960       return I;
961     };
962   }
963   if (Tok == "ADDR") {
964     StringRef Name = readParenLiteral();
965     OutputSection *Sec = Script->getOrCreateOutputSection(Name);
966     return [=]() -> ExprValue {
967       checkIfExists(Sec, Location);
968       return {Sec, false, 0, Location};
969     };
970   }
971   if (Tok == "ALIGN") {
972     expect("(");
973     Expr E = readExpr();
974     if (consume(")")) {
975       E = checkAlignment(E, Location);
976       return [=] { return alignTo(Script->getDot(), E().getValue()); };
977     }
978     expect(",");
979     Expr E2 = checkAlignment(readExpr(), Location);
980     expect(")");
981     return [=] {
982       ExprValue V = E();
983       V.Alignment = E2().getValue();
984       return V;
985     };
986   }
987   if (Tok == "ALIGNOF") {
988     StringRef Name = readParenLiteral();
989     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
990     return [=] {
991       checkIfExists(Cmd, Location);
992       return Cmd->Alignment;
993     };
994   }
995   if (Tok == "ASSERT")
996     return readAssertExpr();
997   if (Tok == "CONSTANT")
998     return readConstant();
999   if (Tok == "DATA_SEGMENT_ALIGN") {
1000     expect("(");
1001     Expr E = readExpr();
1002     expect(",");
1003     readExpr();
1004     expect(")");
1005     return [=] {
1006       return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
1007     };
1008   }
1009   if (Tok == "DATA_SEGMENT_END") {
1010     expect("(");
1011     expect(".");
1012     expect(")");
1013     return [] { return Script->getDot(); };
1014   }
1015   if (Tok == "DATA_SEGMENT_RELRO_END") {
1016     // GNU linkers implements more complicated logic to handle
1017     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
1018     // just align to the next page boundary for simplicity.
1019     expect("(");
1020     readExpr();
1021     expect(",");
1022     readExpr();
1023     expect(")");
1024     Expr E = getPageSize();
1025     return [=] { return alignTo(Script->getDot(), E().getValue()); };
1026   }
1027   if (Tok == "DEFINED") {
1028     StringRef Name = readParenLiteral();
1029     return [=] { return Symtab->find(Name) ? 1 : 0; };
1030   }
1031   if (Tok == "LENGTH") {
1032     StringRef Name = readParenLiteral();
1033     if (Script->MemoryRegions.count(Name) == 0)
1034       setError("memory region not defined: " + Name);
1035     return [=] { return Script->MemoryRegions[Name]->Length; };
1036   }
1037   if (Tok == "LOADADDR") {
1038     StringRef Name = readParenLiteral();
1039     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1040     return [=] {
1041       checkIfExists(Cmd, Location);
1042       return Cmd->getLMA();
1043     };
1044   }
1045   if (Tok == "ORIGIN") {
1046     StringRef Name = readParenLiteral();
1047     if (Script->MemoryRegions.count(Name) == 0)
1048       setError("memory region not defined: " + Name);
1049     return [=] { return Script->MemoryRegions[Name]->Origin; };
1050   }
1051   if (Tok == "SEGMENT_START") {
1052     expect("(");
1053     skip();
1054     expect(",");
1055     Expr E = readExpr();
1056     expect(")");
1057     return [=] { return E(); };
1058   }
1059   if (Tok == "SIZEOF") {
1060     StringRef Name = readParenLiteral();
1061     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1062     // Linker script does not create an output section if its content is empty.
1063     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1064     // be empty.
1065     return [=] { return Cmd->Size; };
1066   }
1067   if (Tok == "SIZEOF_HEADERS")
1068     return [=] { return elf::getHeaderSize(); };
1069 
1070   // Tok is the dot.
1071   if (Tok == ".")
1072     return [=] { return Script->getSymbolValue(Tok, Location); };
1073 
1074   // Tok is a literal number.
1075   if (Optional<uint64_t> Val = parseInt(Tok))
1076     return [=] { return *Val; };
1077 
1078   // Tok is a symbol name.
1079   if (!isValidCIdentifier(Tok))
1080     setError("malformed number: " + Tok);
1081   Script->ReferencedSymbols.push_back(Tok);
1082   return [=] { return Script->getSymbolValue(Tok, Location); };
1083 }
1084 
1085 Expr ScriptParser::readTernary(Expr Cond) {
1086   Expr L = readExpr();
1087   expect(":");
1088   Expr R = readExpr();
1089   return [=] { return Cond().getValue() ? L() : R(); };
1090 }
1091 
1092 Expr ScriptParser::readParenExpr() {
1093   expect("(");
1094   Expr E = readExpr();
1095   expect(")");
1096   return E;
1097 }
1098 
1099 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1100   std::vector<StringRef> Phdrs;
1101   while (!ErrorCount && peek().startswith(":")) {
1102     StringRef Tok = next();
1103     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1104   }
1105   return Phdrs;
1106 }
1107 
1108 // Read a program header type name. The next token must be a
1109 // name of a program header type or a constant (e.g. "0x3").
1110 unsigned ScriptParser::readPhdrType() {
1111   StringRef Tok = next();
1112   if (Optional<uint64_t> Val = parseInt(Tok))
1113     return *Val;
1114 
1115   unsigned Ret = StringSwitch<unsigned>(Tok)
1116                      .Case("PT_NULL", PT_NULL)
1117                      .Case("PT_LOAD", PT_LOAD)
1118                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1119                      .Case("PT_INTERP", PT_INTERP)
1120                      .Case("PT_NOTE", PT_NOTE)
1121                      .Case("PT_SHLIB", PT_SHLIB)
1122                      .Case("PT_PHDR", PT_PHDR)
1123                      .Case("PT_TLS", PT_TLS)
1124                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1125                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1126                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1127                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1128                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1129                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1130                      .Default(-1);
1131 
1132   if (Ret == (unsigned)-1) {
1133     setError("invalid program header type: " + Tok);
1134     return PT_NULL;
1135   }
1136   return Ret;
1137 }
1138 
1139 // Reads an anonymous version declaration.
1140 void ScriptParser::readAnonymousDeclaration() {
1141   std::vector<SymbolVersion> Locals;
1142   std::vector<SymbolVersion> Globals;
1143   std::tie(Locals, Globals) = readSymbols();
1144 
1145   for (SymbolVersion V : Locals) {
1146     if (V.Name == "*")
1147       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1148     else
1149       Config->VersionScriptLocals.push_back(V);
1150   }
1151 
1152   for (SymbolVersion V : Globals)
1153     Config->VersionScriptGlobals.push_back(V);
1154 
1155   expect(";");
1156 }
1157 
1158 // Reads a non-anonymous version definition,
1159 // e.g. "VerStr { global: foo; bar; local: *; };".
1160 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1161   // Read a symbol list.
1162   std::vector<SymbolVersion> Locals;
1163   std::vector<SymbolVersion> Globals;
1164   std::tie(Locals, Globals) = readSymbols();
1165 
1166   for (SymbolVersion V : Locals) {
1167     if (V.Name == "*")
1168       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1169     else
1170       Config->VersionScriptLocals.push_back(V);
1171   }
1172 
1173   // Create a new version definition and add that to the global symbols.
1174   VersionDefinition Ver;
1175   Ver.Name = VerStr;
1176   Ver.Globals = Globals;
1177 
1178   // User-defined version number starts from 2 because 0 and 1 are
1179   // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1180   Ver.Id = Config->VersionDefinitions.size() + 2;
1181   Config->VersionDefinitions.push_back(Ver);
1182 
1183   // Each version may have a parent version. For example, "Ver2"
1184   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1185   // as a parent. This version hierarchy is, probably against your
1186   // instinct, purely for hint; the runtime doesn't care about it
1187   // at all. In LLD, we simply ignore it.
1188   if (peek() != ";")
1189     skip();
1190   expect(";");
1191 }
1192 
1193 static bool hasWildcard(StringRef S) {
1194   return S.find_first_of("?*[") != StringRef::npos;
1195 }
1196 
1197 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1198 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1199 ScriptParser::readSymbols() {
1200   std::vector<SymbolVersion> Locals;
1201   std::vector<SymbolVersion> Globals;
1202   std::vector<SymbolVersion> *V = &Globals;
1203 
1204   while (!ErrorCount) {
1205     if (consume("}"))
1206       break;
1207     if (consumeLabel("local")) {
1208       V = &Locals;
1209       continue;
1210     }
1211     if (consumeLabel("global")) {
1212       V = &Globals;
1213       continue;
1214     }
1215 
1216     if (consume("extern")) {
1217       std::vector<SymbolVersion> Ext = readVersionExtern();
1218       V->insert(V->end(), Ext.begin(), Ext.end());
1219     } else {
1220       StringRef Tok = next();
1221       V->push_back({unquote(Tok), false, hasWildcard(Tok)});
1222     }
1223     expect(";");
1224   }
1225   return {Locals, Globals};
1226 }
1227 
1228 // Reads an "extern C++" directive, e.g.,
1229 // "extern "C++" { ns::*; "f(int, double)"; };"
1230 std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
1231   StringRef Tok = next();
1232   bool IsCXX = Tok == "\"C++\"";
1233   if (!IsCXX && Tok != "\"C\"")
1234     setError("Unknown language");
1235   expect("{");
1236 
1237   std::vector<SymbolVersion> Ret;
1238   while (!ErrorCount && peek() != "}") {
1239     StringRef Tok = next();
1240     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
1241     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
1242     expect(";");
1243   }
1244 
1245   expect("}");
1246   return Ret;
1247 }
1248 
1249 uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
1250                                             StringRef S3) {
1251   if (!consume(S1) && !consume(S2) && !consume(S3)) {
1252     setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
1253     return 0;
1254   }
1255   expect("=");
1256   return readExpr()().getValue();
1257 }
1258 
1259 // Parse the MEMORY command as specified in:
1260 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1261 //
1262 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1263 void ScriptParser::readMemory() {
1264   expect("{");
1265   while (!ErrorCount && !consume("}")) {
1266     StringRef Name = next();
1267 
1268     uint32_t Flags = 0;
1269     uint32_t NegFlags = 0;
1270     if (consume("(")) {
1271       std::tie(Flags, NegFlags) = readMemoryAttributes();
1272       expect(")");
1273     }
1274     expect(":");
1275 
1276     uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
1277     expect(",");
1278     uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
1279 
1280     // Add the memory region to the region map.
1281     if (Script->MemoryRegions.count(Name))
1282       setError("region '" + Name + "' already defined");
1283     MemoryRegion *MR = make<MemoryRegion>();
1284     *MR = {Name, Origin, Length, Flags, NegFlags};
1285     Script->MemoryRegions[Name] = MR;
1286   }
1287 }
1288 
1289 // This function parses the attributes used to match against section
1290 // flags when placing output sections in a memory region. These flags
1291 // are only used when an explicit memory region name is not used.
1292 std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
1293   uint32_t Flags = 0;
1294   uint32_t NegFlags = 0;
1295   bool Invert = false;
1296 
1297   for (char C : next().lower()) {
1298     uint32_t Flag = 0;
1299     if (C == '!')
1300       Invert = !Invert;
1301     else if (C == 'w')
1302       Flag = SHF_WRITE;
1303     else if (C == 'x')
1304       Flag = SHF_EXECINSTR;
1305     else if (C == 'a')
1306       Flag = SHF_ALLOC;
1307     else if (C != 'r')
1308       setError("invalid memory region attribute");
1309 
1310     if (Invert)
1311       NegFlags |= Flag;
1312     else
1313       Flags |= Flag;
1314   }
1315   return {Flags, NegFlags};
1316 }
1317 
1318 void elf::readLinkerScript(MemoryBufferRef MB) {
1319   ScriptParser(MB).readLinkerScript();
1320 }
1321 
1322 void elf::readVersionScript(MemoryBufferRef MB) {
1323   ScriptParser(MB).readVersionScript();
1324 }
1325 
1326 void elf::readDynamicList(MemoryBufferRef MB) {
1327   ScriptParser(MB).readDynamicList();
1328 }
1329