12ec34544SRui Ueyama //===- ScriptParser.cpp ---------------------------------------------------===//
22ec34544SRui Ueyama //
32ec34544SRui Ueyama //                             The LLVM Linker
42ec34544SRui Ueyama //
52ec34544SRui Ueyama // This file is distributed under the University of Illinois Open Source
62ec34544SRui Ueyama // License. See LICENSE.TXT for details.
72ec34544SRui Ueyama //
82ec34544SRui Ueyama //===----------------------------------------------------------------------===//
905f6b852SRui Ueyama //
1005f6b852SRui Ueyama // This file contains a recursive-descendent parser for linker scripts.
1105f6b852SRui Ueyama // Parsed results are stored to Config and Script global objects.
1205f6b852SRui Ueyama //
1305f6b852SRui Ueyama //===----------------------------------------------------------------------===//
142ec34544SRui Ueyama 
152ec34544SRui Ueyama #include "ScriptParser.h"
162ec34544SRui Ueyama #include "Config.h"
172ec34544SRui Ueyama #include "Driver.h"
182ec34544SRui Ueyama #include "InputSection.h"
192ec34544SRui Ueyama #include "LinkerScript.h"
202ec34544SRui Ueyama #include "Memory.h"
212ec34544SRui Ueyama #include "OutputSections.h"
222ec34544SRui Ueyama #include "ScriptLexer.h"
232ec34544SRui Ueyama #include "Symbols.h"
242ec34544SRui Ueyama #include "Target.h"
252ec34544SRui Ueyama #include "llvm/ADT/SmallString.h"
262ec34544SRui Ueyama #include "llvm/ADT/StringRef.h"
270440be4aSRui Ueyama #include "llvm/ADT/StringSet.h"
282ec34544SRui Ueyama #include "llvm/ADT/StringSwitch.h"
29264b5d9eSZachary Turner #include "llvm/BinaryFormat/ELF.h"
302ec34544SRui Ueyama #include "llvm/Support/Casting.h"
312ec34544SRui Ueyama #include "llvm/Support/ErrorHandling.h"
322ec34544SRui Ueyama #include "llvm/Support/FileSystem.h"
332ec34544SRui Ueyama #include "llvm/Support/Path.h"
342ec34544SRui Ueyama #include <cassert>
352ec34544SRui Ueyama #include <limits>
362ec34544SRui Ueyama #include <vector>
372ec34544SRui Ueyama 
382ec34544SRui Ueyama using namespace llvm;
392ec34544SRui Ueyama using namespace llvm::ELF;
40b58079d4SRui Ueyama using namespace llvm::support::endian;
412ec34544SRui Ueyama using namespace lld;
422ec34544SRui Ueyama using namespace lld::elf;
432ec34544SRui Ueyama 
442ec34544SRui Ueyama static bool isUnderSysroot(StringRef Path);
452ec34544SRui Ueyama 
4696b3fe02SRui Ueyama namespace {
4796b3fe02SRui Ueyama class ScriptParser final : ScriptLexer {
482ec34544SRui Ueyama public:
492ec34544SRui Ueyama   ScriptParser(MemoryBufferRef MB)
502ec34544SRui Ueyama       : ScriptLexer(MB),
512ec34544SRui Ueyama         IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
522ec34544SRui Ueyama 
532ec34544SRui Ueyama   void readLinkerScript();
542ec34544SRui Ueyama   void readVersionScript();
552ec34544SRui Ueyama   void readDynamicList();
562ec34544SRui Ueyama 
572ec34544SRui Ueyama private:
582ec34544SRui Ueyama   void addFile(StringRef Path);
598c022ca7SRafael Espindola   OutputSection *checkSection(OutputSection *Cmd, StringRef Loccation);
602ec34544SRui Ueyama 
612ec34544SRui Ueyama   void readAsNeeded();
622ec34544SRui Ueyama   void readEntry();
632ec34544SRui Ueyama   void readExtern();
642ec34544SRui Ueyama   void readGroup();
652ec34544SRui Ueyama   void readInclude();
662ec34544SRui Ueyama   void readMemory();
672ec34544SRui Ueyama   void readOutput();
682ec34544SRui Ueyama   void readOutputArch();
692ec34544SRui Ueyama   void readOutputFormat();
702ec34544SRui Ueyama   void readPhdrs();
715f37541cSGeorge Rimar   void readRegionAlias();
722ec34544SRui Ueyama   void readSearchDir();
732ec34544SRui Ueyama   void readSections();
742ec34544SRui Ueyama   void readVersion();
752ec34544SRui Ueyama   void readVersionScriptCommand();
762ec34544SRui Ueyama 
772ec34544SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
782ec34544SRui Ueyama   BytesDataCommand *readBytesDataCommand(StringRef Tok);
792ec34544SRui Ueyama   uint32_t readFill();
808acbf1ccSRui Ueyama   uint32_t parseFill(StringRef Tok);
818c022ca7SRafael Espindola   void readSectionAddressType(OutputSection *Cmd);
828c022ca7SRafael Espindola   OutputSection *readOutputSectionDescription(StringRef OutSec);
832ec34544SRui Ueyama   std::vector<StringRef> readOutputSectionPhdrs();
842ec34544SRui Ueyama   InputSectionDescription *readInputSectionDescription(StringRef Tok);
852ec34544SRui Ueyama   StringMatcher readFilePatterns();
862ec34544SRui Ueyama   std::vector<SectionPattern> readInputSectionsList();
872ec34544SRui Ueyama   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
882ec34544SRui Ueyama   unsigned readPhdrType();
892ec34544SRui Ueyama   SortSectionPolicy readSortKind();
902ec34544SRui Ueyama   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
912ec34544SRui Ueyama   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
922ec34544SRui Ueyama   void readSort();
9323af89ccSRui Ueyama   AssertCommand *readAssert();
9423af89ccSRui Ueyama   Expr readAssertExpr();
955fb17128SGeorge Rimar   Expr readConstant();
965fb17128SGeorge Rimar   Expr getPageSize();
972ec34544SRui Ueyama 
982ec34544SRui Ueyama   uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
992ec34544SRui Ueyama   std::pair<uint32_t, uint32_t> readMemoryAttributes();
1002ec34544SRui Ueyama 
1012ec34544SRui Ueyama   Expr readExpr();
1022ec34544SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
1032ec34544SRui Ueyama   StringRef readParenLiteral();
1042ec34544SRui Ueyama   Expr readPrimary();
1052ec34544SRui Ueyama   Expr readTernary(Expr Cond);
1062ec34544SRui Ueyama   Expr readParenExpr();
1072ec34544SRui Ueyama 
1082ec34544SRui Ueyama   // For parsing version script.
1092ec34544SRui Ueyama   std::vector<SymbolVersion> readVersionExtern();
1102ec34544SRui Ueyama   void readAnonymousDeclaration();
1112ec34544SRui Ueyama   void readVersionDeclaration(StringRef VerStr);
1122ec34544SRui Ueyama 
1132ec34544SRui Ueyama   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1142ec34544SRui Ueyama   readSymbols();
1152ec34544SRui Ueyama 
116fd06b025SRui Ueyama   // True if a script being read is in a subdirectory specified by -sysroot.
1172ec34544SRui Ueyama   bool IsUnderSysroot;
1180440be4aSRui Ueyama 
1190440be4aSRui Ueyama   // A set to detect an INCLUDE() cycle.
1200440be4aSRui Ueyama   StringSet<> Seen;
1212ec34544SRui Ueyama };
12296b3fe02SRui Ueyama } // namespace
1232ec34544SRui Ueyama 
1241e77ad14SRui Ueyama static StringRef unquote(StringRef S) {
1251e77ad14SRui Ueyama   if (S.startswith("\""))
1261e77ad14SRui Ueyama     return S.substr(1, S.size() - 2);
1271e77ad14SRui Ueyama   return S;
1281e77ad14SRui Ueyama }
1291e77ad14SRui Ueyama 
1302ec34544SRui Ueyama static bool isUnderSysroot(StringRef Path) {
1312ec34544SRui Ueyama   if (Config->Sysroot == "")
1322ec34544SRui Ueyama     return false;
1332ec34544SRui Ueyama   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1342ec34544SRui Ueyama     if (sys::fs::equivalent(Config->Sysroot, Path))
1352ec34544SRui Ueyama       return true;
1362ec34544SRui Ueyama   return false;
1372ec34544SRui Ueyama }
1382ec34544SRui Ueyama 
1392ec34544SRui Ueyama // Some operations only support one non absolute value. Move the
1402ec34544SRui Ueyama // absolute one to the right hand side for convenience.
1412ec34544SRui Ueyama static void moveAbsRight(ExprValue &A, ExprValue &B) {
1422ec34544SRui Ueyama   if (A.isAbsolute())
1432ec34544SRui Ueyama     std::swap(A, B);
1442ec34544SRui Ueyama   if (!B.isAbsolute())
14541c7ab4aSGeorge Rimar     error(A.Loc + ": at least one side of the expression must be absolute");
1462ec34544SRui Ueyama }
1472ec34544SRui Ueyama 
1482ec34544SRui Ueyama static ExprValue add(ExprValue A, ExprValue B) {
1492ec34544SRui Ueyama   moveAbsRight(A, B);
150039fb8c2SPetr Hosek   uint64_t Val = alignTo(A.Val, A.Alignment) + B.getValue();
151039fb8c2SPetr Hosek   return {A.Sec, A.ForceAbsolute, Val, A.Loc};
1522ec34544SRui Ueyama }
1532ec34544SRui Ueyama 
1542ec34544SRui Ueyama static ExprValue sub(ExprValue A, ExprValue B) {
155039fb8c2SPetr Hosek   uint64_t Val = alignTo(A.Val, A.Alignment) - B.getValue();
156039fb8c2SPetr Hosek   return {A.Sec, Val, A.Loc};
1572ec34544SRui Ueyama }
1582ec34544SRui Ueyama 
1592ec34544SRui Ueyama static ExprValue mul(ExprValue A, ExprValue B) {
1602ec34544SRui Ueyama   return A.getValue() * B.getValue();
1612ec34544SRui Ueyama }
1622ec34544SRui Ueyama 
1632ec34544SRui Ueyama static ExprValue div(ExprValue A, ExprValue B) {
1642ec34544SRui Ueyama   if (uint64_t BV = B.getValue())
1652ec34544SRui Ueyama     return A.getValue() / BV;
1662ec34544SRui Ueyama   error("division by zero");
1672ec34544SRui Ueyama   return 0;
1682ec34544SRui Ueyama }
1692ec34544SRui Ueyama 
1702ec34544SRui Ueyama static ExprValue bitAnd(ExprValue A, ExprValue B) {
1712ec34544SRui Ueyama   moveAbsRight(A, B);
1722ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
17341c7ab4aSGeorge Rimar           (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc};
1742ec34544SRui Ueyama }
1752ec34544SRui Ueyama 
1762ec34544SRui Ueyama static ExprValue bitOr(ExprValue A, ExprValue B) {
1772ec34544SRui Ueyama   moveAbsRight(A, B);
1782ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
17941c7ab4aSGeorge Rimar           (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc};
1802ec34544SRui Ueyama }
1812ec34544SRui Ueyama 
1822ec34544SRui Ueyama void ScriptParser::readDynamicList() {
183*8016bdfdSRafael Espindola   Config->HasDynamicList = true;
1842ec34544SRui Ueyama   expect("{");
185d72d97b3SRafael Espindola   std::vector<SymbolVersion> Locals;
186d72d97b3SRafael Espindola   std::vector<SymbolVersion> Globals;
187d72d97b3SRafael Espindola   std::tie(Locals, Globals) = readSymbols();
188d72d97b3SRafael Espindola   expect(";");
189d72d97b3SRafael Espindola 
190d72d97b3SRafael Espindola   if (!atEOF()) {
1912ec34544SRui Ueyama     setError("EOF expected, but got " + next());
192d72d97b3SRafael Espindola     return;
193d72d97b3SRafael Espindola   }
194d72d97b3SRafael Espindola   if (!Locals.empty()) {
195d72d97b3SRafael Espindola     setError("\"local:\" scope not supported in --dynamic-list");
196d72d97b3SRafael Espindola     return;
197d72d97b3SRafael Espindola   }
198d72d97b3SRafael Espindola 
199d72d97b3SRafael Espindola   for (SymbolVersion V : Globals)
200d72d97b3SRafael Espindola     Config->DynamicList.push_back(V);
2012ec34544SRui Ueyama }
2022ec34544SRui Ueyama 
2032ec34544SRui Ueyama void ScriptParser::readVersionScript() {
2042ec34544SRui Ueyama   readVersionScriptCommand();
2052ec34544SRui Ueyama   if (!atEOF())
2062ec34544SRui Ueyama     setError("EOF expected, but got " + next());
2072ec34544SRui Ueyama }
2082ec34544SRui Ueyama 
2092ec34544SRui Ueyama void ScriptParser::readVersionScriptCommand() {
2102ec34544SRui Ueyama   if (consume("{")) {
2112ec34544SRui Ueyama     readAnonymousDeclaration();
2122ec34544SRui Ueyama     return;
2132ec34544SRui Ueyama   }
2142ec34544SRui Ueyama 
215ce608081SGeorge Rimar   while (!atEOF() && !ErrorCount && peek() != "}") {
2162ec34544SRui Ueyama     StringRef VerStr = next();
2172ec34544SRui Ueyama     if (VerStr == "{") {
2182ec34544SRui Ueyama       setError("anonymous version definition is used in "
2192ec34544SRui Ueyama                "combination with other version definitions");
2202ec34544SRui Ueyama       return;
2212ec34544SRui Ueyama     }
2222ec34544SRui Ueyama     expect("{");
2232ec34544SRui Ueyama     readVersionDeclaration(VerStr);
2242ec34544SRui Ueyama   }
2252ec34544SRui Ueyama }
2262ec34544SRui Ueyama 
2272ec34544SRui Ueyama void ScriptParser::readVersion() {
2282ec34544SRui Ueyama   expect("{");
2292ec34544SRui Ueyama   readVersionScriptCommand();
2302ec34544SRui Ueyama   expect("}");
2312ec34544SRui Ueyama }
2322ec34544SRui Ueyama 
2332ec34544SRui Ueyama void ScriptParser::readLinkerScript() {
2342ec34544SRui Ueyama   while (!atEOF()) {
2352ec34544SRui Ueyama     StringRef Tok = next();
2362ec34544SRui Ueyama     if (Tok == ";")
2372ec34544SRui Ueyama       continue;
2382ec34544SRui Ueyama 
2392ec34544SRui Ueyama     if (Tok == "ASSERT") {
24023af89ccSRui Ueyama       Script->Opt.Commands.push_back(readAssert());
2412ec34544SRui Ueyama     } else if (Tok == "ENTRY") {
2422ec34544SRui Ueyama       readEntry();
2432ec34544SRui Ueyama     } else if (Tok == "EXTERN") {
2442ec34544SRui Ueyama       readExtern();
2452ec34544SRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
2462ec34544SRui Ueyama       readGroup();
2472ec34544SRui Ueyama     } else if (Tok == "INCLUDE") {
2482ec34544SRui Ueyama       readInclude();
2492ec34544SRui Ueyama     } else if (Tok == "MEMORY") {
2502ec34544SRui Ueyama       readMemory();
2512ec34544SRui Ueyama     } else if (Tok == "OUTPUT") {
2522ec34544SRui Ueyama       readOutput();
2532ec34544SRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
2542ec34544SRui Ueyama       readOutputArch();
2552ec34544SRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
2562ec34544SRui Ueyama       readOutputFormat();
2572ec34544SRui Ueyama     } else if (Tok == "PHDRS") {
2582ec34544SRui Ueyama       readPhdrs();
2595f37541cSGeorge Rimar     } else if (Tok == "REGION_ALIAS") {
2605f37541cSGeorge Rimar       readRegionAlias();
2612ec34544SRui Ueyama     } else if (Tok == "SEARCH_DIR") {
2622ec34544SRui Ueyama       readSearchDir();
2632ec34544SRui Ueyama     } else if (Tok == "SECTIONS") {
2642ec34544SRui Ueyama       readSections();
2652ec34544SRui Ueyama     } else if (Tok == "VERSION") {
2662ec34544SRui Ueyama       readVersion();
2672ec34544SRui Ueyama     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
2682ec34544SRui Ueyama       Script->Opt.Commands.push_back(Cmd);
2692ec34544SRui Ueyama     } else {
2702ec34544SRui Ueyama       setError("unknown directive: " + Tok);
2712ec34544SRui Ueyama     }
2722ec34544SRui Ueyama   }
2732ec34544SRui Ueyama }
2742ec34544SRui Ueyama 
2752ec34544SRui Ueyama void ScriptParser::addFile(StringRef S) {
2762ec34544SRui Ueyama   if (IsUnderSysroot && S.startswith("/")) {
2772ec34544SRui Ueyama     SmallString<128> PathData;
2782ec34544SRui Ueyama     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
2792ec34544SRui Ueyama     if (sys::fs::exists(Path)) {
280a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
2812ec34544SRui Ueyama       return;
2822ec34544SRui Ueyama     }
2832ec34544SRui Ueyama   }
2842ec34544SRui Ueyama 
285875ae82bSRui Ueyama   if (S.startswith("/")) {
286a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2872ec34544SRui Ueyama   } else if (S.startswith("=")) {
2882ec34544SRui Ueyama     if (Config->Sysroot.empty())
289a76349bfSEvgeniy Stepanov       Driver->addFile(S.substr(1), /*WithLOption=*/false);
2902ec34544SRui Ueyama     else
291a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
292a76349bfSEvgeniy Stepanov                       /*WithLOption=*/false);
2932ec34544SRui Ueyama   } else if (S.startswith("-l")) {
2942ec34544SRui Ueyama     Driver->addLibrary(S.substr(2));
2952ec34544SRui Ueyama   } else if (sys::fs::exists(S)) {
296a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2972ec34544SRui Ueyama   } else {
2982ec34544SRui Ueyama     if (Optional<std::string> Path = findFromSearchPaths(S))
299a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
3002ec34544SRui Ueyama     else
3012ec34544SRui Ueyama       setError("unable to find " + S);
3022ec34544SRui Ueyama   }
3032ec34544SRui Ueyama }
3042ec34544SRui Ueyama 
3052ec34544SRui Ueyama void ScriptParser::readAsNeeded() {
3062ec34544SRui Ueyama   expect("(");
3072ec34544SRui Ueyama   bool Orig = Config->AsNeeded;
3082ec34544SRui Ueyama   Config->AsNeeded = true;
309ce608081SGeorge Rimar   while (!ErrorCount && !consume(")"))
3102ec34544SRui Ueyama     addFile(unquote(next()));
3112ec34544SRui Ueyama   Config->AsNeeded = Orig;
3122ec34544SRui Ueyama }
3132ec34544SRui Ueyama 
3142ec34544SRui Ueyama void ScriptParser::readEntry() {
3152ec34544SRui Ueyama   // -e <symbol> takes predecence over ENTRY(<symbol>).
3162ec34544SRui Ueyama   expect("(");
3172ec34544SRui Ueyama   StringRef Tok = next();
3182ec34544SRui Ueyama   if (Config->Entry.empty())
3192ec34544SRui Ueyama     Config->Entry = Tok;
3202ec34544SRui Ueyama   expect(")");
3212ec34544SRui Ueyama }
3222ec34544SRui Ueyama 
3232ec34544SRui Ueyama void ScriptParser::readExtern() {
3242ec34544SRui Ueyama   expect("(");
325ce608081SGeorge Rimar   while (!ErrorCount && !consume(")"))
3262ec34544SRui Ueyama     Config->Undefined.push_back(next());
3272ec34544SRui Ueyama }
3282ec34544SRui Ueyama 
3292ec34544SRui Ueyama void ScriptParser::readGroup() {
3302ec34544SRui Ueyama   expect("(");
331ce608081SGeorge Rimar   while (!ErrorCount && !consume(")")) {
332b579c439SRui Ueyama     if (consume("AS_NEEDED"))
3332ec34544SRui Ueyama       readAsNeeded();
3342ec34544SRui Ueyama     else
335b579c439SRui Ueyama       addFile(unquote(next()));
3362ec34544SRui Ueyama   }
3372ec34544SRui Ueyama }
3382ec34544SRui Ueyama 
3392ec34544SRui Ueyama void ScriptParser::readInclude() {
3402ec34544SRui Ueyama   StringRef Tok = unquote(next());
3412ec34544SRui Ueyama 
3420440be4aSRui Ueyama   if (!Seen.insert(Tok).second) {
3430440be4aSRui Ueyama     setError("there is a cycle in linker script INCLUDEs");
3440440be4aSRui Ueyama     return;
3450440be4aSRui Ueyama   }
3460440be4aSRui Ueyama 
3472ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/File-Commands.html:
3482ec34544SRui Ueyama   // The file will be searched for in the current directory, and in any
3492ec34544SRui Ueyama   // directory specified with the -L option.
3502ec34544SRui Ueyama   if (sys::fs::exists(Tok)) {
3512ec34544SRui Ueyama     if (Optional<MemoryBufferRef> MB = readFile(Tok))
3522ec34544SRui Ueyama       tokenize(*MB);
3532ec34544SRui Ueyama     return;
3542ec34544SRui Ueyama   }
3552ec34544SRui Ueyama   if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
3562ec34544SRui Ueyama     if (Optional<MemoryBufferRef> MB = readFile(*Path))
3572ec34544SRui Ueyama       tokenize(*MB);
3582ec34544SRui Ueyama     return;
3592ec34544SRui Ueyama   }
3602ec34544SRui Ueyama   setError("cannot open " + Tok);
3612ec34544SRui Ueyama }
3622ec34544SRui Ueyama 
3632ec34544SRui Ueyama void ScriptParser::readOutput() {
3642ec34544SRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
3652ec34544SRui Ueyama   expect("(");
3662ec34544SRui Ueyama   StringRef Tok = next();
3672ec34544SRui Ueyama   if (Config->OutputFile.empty())
3682ec34544SRui Ueyama     Config->OutputFile = unquote(Tok);
3692ec34544SRui Ueyama   expect(")");
3702ec34544SRui Ueyama }
3712ec34544SRui Ueyama 
3722ec34544SRui Ueyama void ScriptParser::readOutputArch() {
3732ec34544SRui Ueyama   // OUTPUT_ARCH is ignored for now.
3742ec34544SRui Ueyama   expect("(");
375ce608081SGeorge Rimar   while (!ErrorCount && !consume(")"))
3762ec34544SRui Ueyama     skip();
3772ec34544SRui Ueyama }
3782ec34544SRui Ueyama 
3792ec34544SRui Ueyama void ScriptParser::readOutputFormat() {
3802ec34544SRui Ueyama   // Error checking only for now.
3812ec34544SRui Ueyama   expect("(");
3822ec34544SRui Ueyama   skip();
383b579c439SRui Ueyama   if (consume(")"))
3842ec34544SRui Ueyama     return;
385b579c439SRui Ueyama   expect(",");
3862ec34544SRui Ueyama   skip();
3872ec34544SRui Ueyama   expect(",");
3882ec34544SRui Ueyama   skip();
3892ec34544SRui Ueyama   expect(")");
3902ec34544SRui Ueyama }
3912ec34544SRui Ueyama 
3922ec34544SRui Ueyama void ScriptParser::readPhdrs() {
3932ec34544SRui Ueyama   expect("{");
394ce608081SGeorge Rimar   while (!ErrorCount && !consume("}")) {
3952ec34544SRui Ueyama     Script->Opt.PhdrsCommands.push_back(
396b579c439SRui Ueyama         {next(), PT_NULL, false, false, UINT_MAX, nullptr});
3972ec34544SRui Ueyama 
398b579c439SRui Ueyama     PhdrsCommand &PhdrCmd = Script->Opt.PhdrsCommands.back();
3992ec34544SRui Ueyama     PhdrCmd.Type = readPhdrType();
400b579c439SRui Ueyama 
401ce608081SGeorge Rimar     while (!ErrorCount && !consume(";")) {
402b579c439SRui Ueyama       if (consume("FILEHDR"))
4032ec34544SRui Ueyama         PhdrCmd.HasFilehdr = true;
404b579c439SRui Ueyama       else if (consume("PHDRS"))
4052ec34544SRui Ueyama         PhdrCmd.HasPhdrs = true;
406b579c439SRui Ueyama       else if (consume("AT"))
4072ec34544SRui Ueyama         PhdrCmd.LMAExpr = readParenExpr();
408b579c439SRui Ueyama       else if (consume("FLAGS"))
409b579c439SRui Ueyama         PhdrCmd.Flags = readParenExpr()().getValue();
410b579c439SRui Ueyama       else
411b579c439SRui Ueyama         setError("unexpected header attribute: " + next());
412b579c439SRui Ueyama     }
4132ec34544SRui Ueyama   }
4142ec34544SRui Ueyama }
4152ec34544SRui Ueyama 
4165f37541cSGeorge Rimar void ScriptParser::readRegionAlias() {
4175f37541cSGeorge Rimar   expect("(");
4185f37541cSGeorge Rimar   StringRef Alias = unquote(next());
4195f37541cSGeorge Rimar   expect(",");
4205f37541cSGeorge Rimar   StringRef Name = next();
4215f37541cSGeorge Rimar   expect(")");
4225f37541cSGeorge Rimar 
4235f37541cSGeorge Rimar   if (Script->Opt.MemoryRegions.count(Alias))
4245f37541cSGeorge Rimar     setError("redefinition of memory region '" + Alias + "'");
4255f37541cSGeorge Rimar   if (!Script->Opt.MemoryRegions.count(Name))
4265f37541cSGeorge Rimar     setError("memory region '" + Name + "' is not defined");
4275f37541cSGeorge Rimar   Script->Opt.MemoryRegions[Alias] = Script->Opt.MemoryRegions[Name];
4285f37541cSGeorge Rimar }
4295f37541cSGeorge Rimar 
4302ec34544SRui Ueyama void ScriptParser::readSearchDir() {
4312ec34544SRui Ueyama   expect("(");
4322ec34544SRui Ueyama   StringRef Tok = next();
4332ec34544SRui Ueyama   if (!Config->Nostdlib)
4342ec34544SRui Ueyama     Config->SearchPaths.push_back(unquote(Tok));
4352ec34544SRui Ueyama   expect(")");
4362ec34544SRui Ueyama }
4372ec34544SRui Ueyama 
4382ec34544SRui Ueyama void ScriptParser::readSections() {
4392ec34544SRui Ueyama   Script->Opt.HasSections = true;
440b579c439SRui Ueyama 
4412ec34544SRui Ueyama   // -no-rosegment is used to avoid placing read only non-executable sections in
4422ec34544SRui Ueyama   // their own segment. We do the same if SECTIONS command is present in linker
4432ec34544SRui Ueyama   // script. See comment for computeFlags().
4442ec34544SRui Ueyama   Config->SingleRoRx = true;
4452ec34544SRui Ueyama 
4462ec34544SRui Ueyama   expect("{");
447ce608081SGeorge Rimar   while (!ErrorCount && !consume("}")) {
4482ec34544SRui Ueyama     StringRef Tok = next();
4492ec34544SRui Ueyama     BaseCommand *Cmd = readProvideOrAssignment(Tok);
4502ec34544SRui Ueyama     if (!Cmd) {
4512ec34544SRui Ueyama       if (Tok == "ASSERT")
45223af89ccSRui Ueyama         Cmd = readAssert();
4532ec34544SRui Ueyama       else
4542ec34544SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
4552ec34544SRui Ueyama     }
4562ec34544SRui Ueyama     Script->Opt.Commands.push_back(Cmd);
4572ec34544SRui Ueyama   }
4582ec34544SRui Ueyama }
4592ec34544SRui Ueyama 
4602ec34544SRui Ueyama static int precedence(StringRef Op) {
4612ec34544SRui Ueyama   return StringSwitch<int>(Op)
4622ec34544SRui Ueyama       .Cases("*", "/", 5)
4632ec34544SRui Ueyama       .Cases("+", "-", 4)
4642ec34544SRui Ueyama       .Cases("<<", ">>", 3)
4652ec34544SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
4662ec34544SRui Ueyama       .Cases("&", "|", 1)
4672ec34544SRui Ueyama       .Default(-1);
4682ec34544SRui Ueyama }
4692ec34544SRui Ueyama 
4702ec34544SRui Ueyama StringMatcher ScriptParser::readFilePatterns() {
4712ec34544SRui Ueyama   std::vector<StringRef> V;
472ce608081SGeorge Rimar   while (!ErrorCount && !consume(")"))
4732ec34544SRui Ueyama     V.push_back(next());
4742ec34544SRui Ueyama   return StringMatcher(V);
4752ec34544SRui Ueyama }
4762ec34544SRui Ueyama 
4772ec34544SRui Ueyama SortSectionPolicy ScriptParser::readSortKind() {
4782ec34544SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
4792ec34544SRui Ueyama     return SortSectionPolicy::Name;
4802ec34544SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
4812ec34544SRui Ueyama     return SortSectionPolicy::Alignment;
4822ec34544SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
4832ec34544SRui Ueyama     return SortSectionPolicy::Priority;
4842ec34544SRui Ueyama   if (consume("SORT_NONE"))
4852ec34544SRui Ueyama     return SortSectionPolicy::None;
4862ec34544SRui Ueyama   return SortSectionPolicy::Default;
4872ec34544SRui Ueyama }
4882ec34544SRui Ueyama 
48903fc8d1eSRui Ueyama // Reads SECTIONS command contents in the following form:
49003fc8d1eSRui Ueyama //
49103fc8d1eSRui Ueyama // <contents> ::= <elem>*
49203fc8d1eSRui Ueyama // <elem>     ::= <exclude>? <glob-pattern>
49303fc8d1eSRui Ueyama // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
49403fc8d1eSRui Ueyama //
49503fc8d1eSRui Ueyama // For example,
49603fc8d1eSRui Ueyama //
49703fc8d1eSRui Ueyama // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
49803fc8d1eSRui Ueyama //
49903fc8d1eSRui Ueyama // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
50003fc8d1eSRui Ueyama // The semantics of that is section .foo in any file, section .bar in
50103fc8d1eSRui Ueyama // any file but a.o, and section .baz in any file but b.o.
5022ec34544SRui Ueyama std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
5032ec34544SRui Ueyama   std::vector<SectionPattern> Ret;
504ce608081SGeorge Rimar   while (!ErrorCount && peek() != ")") {
5052ec34544SRui Ueyama     StringMatcher ExcludeFilePat;
5062ec34544SRui Ueyama     if (consume("EXCLUDE_FILE")) {
5072ec34544SRui Ueyama       expect("(");
5082ec34544SRui Ueyama       ExcludeFilePat = readFilePatterns();
5092ec34544SRui Ueyama     }
5102ec34544SRui Ueyama 
5112ec34544SRui Ueyama     std::vector<StringRef> V;
512ce608081SGeorge Rimar     while (!ErrorCount && peek() != ")" && peek() != "EXCLUDE_FILE")
5132ec34544SRui Ueyama       V.push_back(next());
5142ec34544SRui Ueyama 
5152ec34544SRui Ueyama     if (!V.empty())
5162ec34544SRui Ueyama       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
5172ec34544SRui Ueyama     else
5182ec34544SRui Ueyama       setError("section pattern is expected");
5192ec34544SRui Ueyama   }
5202ec34544SRui Ueyama   return Ret;
5212ec34544SRui Ueyama }
5222ec34544SRui Ueyama 
5232ec34544SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a
5242ec34544SRui Ueyama // list of glob patterns for input sections. The grammar is as follows.
5252ec34544SRui Ueyama //
5262ec34544SRui Ueyama // <patterns> ::= <section-list>
5272ec34544SRui Ueyama //              | <sort> "(" <section-list> ")"
5282ec34544SRui Ueyama //              | <sort> "(" <sort> "(" <section-list> ")" ")"
5292ec34544SRui Ueyama //
5302ec34544SRui Ueyama // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
5312ec34544SRui Ueyama //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
5322ec34544SRui Ueyama //
5332ec34544SRui Ueyama // <section-list> is parsed by readInputSectionsList().
5342ec34544SRui Ueyama InputSectionDescription *
5352ec34544SRui Ueyama ScriptParser::readInputSectionRules(StringRef FilePattern) {
5362ec34544SRui Ueyama   auto *Cmd = make<InputSectionDescription>(FilePattern);
5372ec34544SRui Ueyama   expect("(");
5382ec34544SRui Ueyama 
539ce608081SGeorge Rimar   while (!ErrorCount && !consume(")")) {
5402ec34544SRui Ueyama     SortSectionPolicy Outer = readSortKind();
5412ec34544SRui Ueyama     SortSectionPolicy Inner = SortSectionPolicy::Default;
5422ec34544SRui Ueyama     std::vector<SectionPattern> V;
5432ec34544SRui Ueyama     if (Outer != SortSectionPolicy::Default) {
5442ec34544SRui Ueyama       expect("(");
5452ec34544SRui Ueyama       Inner = readSortKind();
5462ec34544SRui Ueyama       if (Inner != SortSectionPolicy::Default) {
5472ec34544SRui Ueyama         expect("(");
5482ec34544SRui Ueyama         V = readInputSectionsList();
5492ec34544SRui Ueyama         expect(")");
5502ec34544SRui Ueyama       } else {
5512ec34544SRui Ueyama         V = readInputSectionsList();
5522ec34544SRui Ueyama       }
5532ec34544SRui Ueyama       expect(")");
5542ec34544SRui Ueyama     } else {
5552ec34544SRui Ueyama       V = readInputSectionsList();
5562ec34544SRui Ueyama     }
5572ec34544SRui Ueyama 
5582ec34544SRui Ueyama     for (SectionPattern &Pat : V) {
5592ec34544SRui Ueyama       Pat.SortInner = Inner;
5602ec34544SRui Ueyama       Pat.SortOuter = Outer;
5612ec34544SRui Ueyama     }
5622ec34544SRui Ueyama 
5632ec34544SRui Ueyama     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
5642ec34544SRui Ueyama   }
5652ec34544SRui Ueyama   return Cmd;
5662ec34544SRui Ueyama }
5672ec34544SRui Ueyama 
5682ec34544SRui Ueyama InputSectionDescription *
5692ec34544SRui Ueyama ScriptParser::readInputSectionDescription(StringRef Tok) {
5702ec34544SRui Ueyama   // Input section wildcard can be surrounded by KEEP.
5712ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
5722ec34544SRui Ueyama   if (Tok == "KEEP") {
5732ec34544SRui Ueyama     expect("(");
5742ec34544SRui Ueyama     StringRef FilePattern = next();
5752ec34544SRui Ueyama     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
5762ec34544SRui Ueyama     expect(")");
5772ec34544SRui Ueyama     Script->Opt.KeptSections.push_back(Cmd);
5782ec34544SRui Ueyama     return Cmd;
5792ec34544SRui Ueyama   }
5802ec34544SRui Ueyama   return readInputSectionRules(Tok);
5812ec34544SRui Ueyama }
5822ec34544SRui Ueyama 
5832ec34544SRui Ueyama void ScriptParser::readSort() {
5842ec34544SRui Ueyama   expect("(");
5852ec34544SRui Ueyama   expect("CONSTRUCTORS");
5862ec34544SRui Ueyama   expect(")");
5872ec34544SRui Ueyama }
5882ec34544SRui Ueyama 
58923af89ccSRui Ueyama AssertCommand *ScriptParser::readAssert() {
59023af89ccSRui Ueyama   return make<AssertCommand>(readAssertExpr());
59123af89ccSRui Ueyama }
59223af89ccSRui Ueyama 
59323af89ccSRui Ueyama Expr ScriptParser::readAssertExpr() {
5942ec34544SRui Ueyama   expect("(");
5952ec34544SRui Ueyama   Expr E = readExpr();
5962ec34544SRui Ueyama   expect(",");
5972ec34544SRui Ueyama   StringRef Msg = unquote(next());
5982ec34544SRui Ueyama   expect(")");
599b579c439SRui Ueyama 
6002ec34544SRui Ueyama   return [=] {
6012ec34544SRui Ueyama     if (!E().getValue())
6022ec34544SRui Ueyama       error(Msg);
6032ec34544SRui Ueyama     return Script->getDot();
6042ec34544SRui Ueyama   };
6052ec34544SRui Ueyama }
6062ec34544SRui Ueyama 
6072ec34544SRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
6082ec34544SRui Ueyama // alias for =fillexp section attribute, which is different from
6092ec34544SRui Ueyama // what GNU linkers do.
6102ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
6112ec34544SRui Ueyama uint32_t ScriptParser::readFill() {
6122ec34544SRui Ueyama   expect("(");
6138acbf1ccSRui Ueyama   uint32_t V = parseFill(next());
6142ec34544SRui Ueyama   expect(")");
6152ec34544SRui Ueyama   return V;
6162ec34544SRui Ueyama }
6172ec34544SRui Ueyama 
6183271d370SRui Ueyama // Reads an expression and/or the special directive "(NOLOAD)" for an
6193271d370SRui Ueyama // output section definition.
6203271d370SRui Ueyama //
6213271d370SRui Ueyama // An output section name can be followed by an address expression
6223271d370SRui Ueyama // and/or by "(NOLOAD)". This grammar is not LL(1) because "(" can be
6233271d370SRui Ueyama // interpreted as either the beginning of some expression or "(NOLOAD)".
6243271d370SRui Ueyama //
625b579c439SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
626fbb0463fSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
6278c022ca7SRafael Espindola void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
6283271d370SRui Ueyama   if (consume("(")) {
6293271d370SRui Ueyama     if (consume("NOLOAD")) {
6303271d370SRui Ueyama       expect(")");
6313271d370SRui Ueyama       Cmd->Noload = true;
6323271d370SRui Ueyama       return;
6333271d370SRui Ueyama     }
6343271d370SRui Ueyama     Cmd->AddrExpr = readExpr();
6353271d370SRui Ueyama     expect(")");
6363271d370SRui Ueyama   } else {
6373271d370SRui Ueyama     Cmd->AddrExpr = readExpr();
6383271d370SRui Ueyama   }
6393271d370SRui Ueyama 
640fbb0463fSGeorge Rimar   if (consume("(")) {
641fbb0463fSGeorge Rimar     expect("NOLOAD");
642fbb0463fSGeorge Rimar     expect(")");
643fbb0463fSGeorge Rimar     Cmd->Noload = true;
644fbb0463fSGeorge Rimar   }
645fbb0463fSGeorge Rimar }
646fbb0463fSGeorge Rimar 
6478c022ca7SRafael Espindola OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
6488c022ca7SRafael Espindola   OutputSection *Cmd =
6498c022ca7SRafael Espindola       Script->createOutputSection(OutSec, getCurrentLocation());
6503271d370SRui Ueyama 
6513271d370SRui Ueyama   if (peek() != ":")
6523271d370SRui Ueyama     readSectionAddressType(Cmd);
6532ec34544SRui Ueyama   expect(":");
6542ec34544SRui Ueyama 
6552ec34544SRui Ueyama   if (consume("AT"))
6562ec34544SRui Ueyama     Cmd->LMAExpr = readParenExpr();
6572ec34544SRui Ueyama   if (consume("ALIGN"))
6582ec34544SRui Ueyama     Cmd->AlignExpr = readParenExpr();
6592ec34544SRui Ueyama   if (consume("SUBALIGN"))
6602ec34544SRui Ueyama     Cmd->SubalignExpr = readParenExpr();
6612ec34544SRui Ueyama 
6622ec34544SRui Ueyama   // Parse constraints.
6632ec34544SRui Ueyama   if (consume("ONLY_IF_RO"))
6642ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
6652ec34544SRui Ueyama   if (consume("ONLY_IF_RW"))
6662ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
6672ec34544SRui Ueyama   expect("{");
6682ec34544SRui Ueyama 
669ce608081SGeorge Rimar   while (!ErrorCount && !consume("}")) {
6702ec34544SRui Ueyama     StringRef Tok = next();
6712ec34544SRui Ueyama     if (Tok == ";") {
6722ec34544SRui Ueyama       // Empty commands are allowed. Do nothing here.
673b579c439SRui Ueyama     } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) {
674b579c439SRui Ueyama       Cmd->Commands.push_back(Assign);
6752ec34544SRui Ueyama     } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
6762ec34544SRui Ueyama       Cmd->Commands.push_back(Data);
6772ec34544SRui Ueyama     } else if (Tok == "ASSERT") {
67823af89ccSRui Ueyama       Cmd->Commands.push_back(readAssert());
6792ec34544SRui Ueyama       expect(";");
6802ec34544SRui Ueyama     } else if (Tok == "CONSTRUCTORS") {
6812ec34544SRui Ueyama       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
6822ec34544SRui Ueyama       // by name. This is for very old file formats such as ECOFF/XCOFF.
6832ec34544SRui Ueyama       // For ELF, we should ignore.
6842ec34544SRui Ueyama     } else if (Tok == "FILL") {
6852ec34544SRui Ueyama       Cmd->Filler = readFill();
6862ec34544SRui Ueyama     } else if (Tok == "SORT") {
6872ec34544SRui Ueyama       readSort();
6882ec34544SRui Ueyama     } else if (peek() == "(") {
6892ec34544SRui Ueyama       Cmd->Commands.push_back(readInputSectionDescription(Tok));
6902ec34544SRui Ueyama     } else {
6912ec34544SRui Ueyama       setError("unknown command " + Tok);
6922ec34544SRui Ueyama     }
6932ec34544SRui Ueyama   }
6942ec34544SRui Ueyama 
6952ec34544SRui Ueyama   if (consume(">"))
6962ec34544SRui Ueyama     Cmd->MemoryRegionName = next();
697b0e62297SMeador Inge   else if (peek().startswith(">"))
698b0e62297SMeador Inge     Cmd->MemoryRegionName = next().drop_front();
6992ec34544SRui Ueyama 
7002ec34544SRui Ueyama   Cmd->Phdrs = readOutputSectionPhdrs();
7012ec34544SRui Ueyama 
7022ec34544SRui Ueyama   if (consume("="))
7038acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next());
7042ec34544SRui Ueyama   else if (peek().startswith("="))
7058acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next().drop_front());
7062ec34544SRui Ueyama 
7072ec34544SRui Ueyama   // Consume optional comma following output section command.
7082ec34544SRui Ueyama   consume(",");
7092ec34544SRui Ueyama 
7102ec34544SRui Ueyama   return Cmd;
7112ec34544SRui Ueyama }
7122ec34544SRui Ueyama 
7138acbf1ccSRui Ueyama // Parses a given string as a octal/decimal/hexadecimal number and
7148acbf1ccSRui Ueyama // returns it as a big-endian number. Used for `=<fillexp>`.
7152ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
7162ec34544SRui Ueyama //
7178acbf1ccSRui Ueyama // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
7188acbf1ccSRui Ueyama // size, while ld.gold always handles it as a 32-bit big-endian number.
7198acbf1ccSRui Ueyama // We are compatible with ld.gold because it's easier to implement.
7208acbf1ccSRui Ueyama uint32_t ScriptParser::parseFill(StringRef Tok) {
721b58079d4SRui Ueyama   uint32_t V = 0;
722ab94768cSGeorge Rimar   if (!to_integer(Tok, V))
7232ec34544SRui Ueyama     setError("invalid filler expression: " + Tok);
724b58079d4SRui Ueyama 
725b58079d4SRui Ueyama   uint32_t Buf;
726b58079d4SRui Ueyama   write32be(&Buf, V);
727b58079d4SRui Ueyama   return Buf;
7282ec34544SRui Ueyama }
7292ec34544SRui Ueyama 
7302ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
7312ec34544SRui Ueyama   expect("(");
7322ec34544SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
7332ec34544SRui Ueyama   Cmd->Provide = Provide;
7342ec34544SRui Ueyama   Cmd->Hidden = Hidden;
7352ec34544SRui Ueyama   expect(")");
7362ec34544SRui Ueyama   expect(";");
7372ec34544SRui Ueyama   return Cmd;
7382ec34544SRui Ueyama }
7392ec34544SRui Ueyama 
7402ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
7412ec34544SRui Ueyama   SymbolAssignment *Cmd = nullptr;
7422ec34544SRui Ueyama   if (peek() == "=" || peek() == "+=") {
7432ec34544SRui Ueyama     Cmd = readAssignment(Tok);
7442ec34544SRui Ueyama     expect(";");
7452ec34544SRui Ueyama   } else if (Tok == "PROVIDE") {
7462ec34544SRui Ueyama     Cmd = readProvideHidden(true, false);
7472ec34544SRui Ueyama   } else if (Tok == "HIDDEN") {
7482ec34544SRui Ueyama     Cmd = readProvideHidden(false, true);
7492ec34544SRui Ueyama   } else if (Tok == "PROVIDE_HIDDEN") {
7502ec34544SRui Ueyama     Cmd = readProvideHidden(true, true);
7512ec34544SRui Ueyama   }
7522ec34544SRui Ueyama   return Cmd;
7532ec34544SRui Ueyama }
7542ec34544SRui Ueyama 
7552ec34544SRui Ueyama SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
7562ec34544SRui Ueyama   StringRef Op = next();
7572ec34544SRui Ueyama   assert(Op == "=" || Op == "+=");
7582ec34544SRui Ueyama   Expr E = readExpr();
7592ec34544SRui Ueyama   if (Op == "+=") {
7602ec34544SRui Ueyama     std::string Loc = getCurrentLocation();
7612ec34544SRui Ueyama     E = [=] { return add(Script->getSymbolValue(Loc, Name), E()); };
7622ec34544SRui Ueyama   }
7632ec34544SRui Ueyama   return make<SymbolAssignment>(Name, E, getCurrentLocation());
7642ec34544SRui Ueyama }
7652ec34544SRui Ueyama 
7662ec34544SRui Ueyama // This is an operator-precedence parser to parse a linker
7672ec34544SRui Ueyama // script expression.
7682ec34544SRui Ueyama Expr ScriptParser::readExpr() {
7692ec34544SRui Ueyama   // Our lexer is context-aware. Set the in-expression bit so that
7702ec34544SRui Ueyama   // they apply different tokenization rules.
7712ec34544SRui Ueyama   bool Orig = InExpr;
7722ec34544SRui Ueyama   InExpr = true;
7732ec34544SRui Ueyama   Expr E = readExpr1(readPrimary(), 0);
7742ec34544SRui Ueyama   InExpr = Orig;
7752ec34544SRui Ueyama   return E;
7762ec34544SRui Ueyama }
7772ec34544SRui Ueyama 
7782ec34544SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
7792ec34544SRui Ueyama   if (Op == "+")
7802ec34544SRui Ueyama     return [=] { return add(L(), R()); };
7812ec34544SRui Ueyama   if (Op == "-")
7822ec34544SRui Ueyama     return [=] { return sub(L(), R()); };
783b579c439SRui Ueyama   if (Op == "*")
784b579c439SRui Ueyama     return [=] { return mul(L(), R()); };
785b579c439SRui Ueyama   if (Op == "/")
786b579c439SRui Ueyama     return [=] { return div(L(), R()); };
7872ec34544SRui Ueyama   if (Op == "<<")
7887e915511SRui Ueyama     return [=] { return L().getValue() << R().getValue(); };
7892ec34544SRui Ueyama   if (Op == ">>")
7907e915511SRui Ueyama     return [=] { return L().getValue() >> R().getValue(); };
7912ec34544SRui Ueyama   if (Op == "<")
7922ec34544SRui Ueyama     return [=] { return L().getValue() < R().getValue(); };
7932ec34544SRui Ueyama   if (Op == ">")
7942ec34544SRui Ueyama     return [=] { return L().getValue() > R().getValue(); };
7952ec34544SRui Ueyama   if (Op == ">=")
7962ec34544SRui Ueyama     return [=] { return L().getValue() >= R().getValue(); };
7972ec34544SRui Ueyama   if (Op == "<=")
7982ec34544SRui Ueyama     return [=] { return L().getValue() <= R().getValue(); };
7992ec34544SRui Ueyama   if (Op == "==")
8002ec34544SRui Ueyama     return [=] { return L().getValue() == R().getValue(); };
8012ec34544SRui Ueyama   if (Op == "!=")
8022ec34544SRui Ueyama     return [=] { return L().getValue() != R().getValue(); };
8032ec34544SRui Ueyama   if (Op == "&")
8042ec34544SRui Ueyama     return [=] { return bitAnd(L(), R()); };
8052ec34544SRui Ueyama   if (Op == "|")
8062ec34544SRui Ueyama     return [=] { return bitOr(L(), R()); };
8072ec34544SRui Ueyama   llvm_unreachable("invalid operator");
8082ec34544SRui Ueyama }
8092ec34544SRui Ueyama 
8102ec34544SRui Ueyama // This is a part of the operator-precedence parser. This function
8112ec34544SRui Ueyama // assumes that the remaining token stream starts with an operator.
8122ec34544SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
813ce608081SGeorge Rimar   while (!atEOF() && !ErrorCount) {
8142ec34544SRui Ueyama     // Read an operator and an expression.
8152ec34544SRui Ueyama     if (consume("?"))
8162ec34544SRui Ueyama       return readTernary(Lhs);
8172ec34544SRui Ueyama     StringRef Op1 = peek();
8182ec34544SRui Ueyama     if (precedence(Op1) < MinPrec)
8192ec34544SRui Ueyama       break;
8202ec34544SRui Ueyama     skip();
8212ec34544SRui Ueyama     Expr Rhs = readPrimary();
8222ec34544SRui Ueyama 
8232ec34544SRui Ueyama     // Evaluate the remaining part of the expression first if the
8242ec34544SRui Ueyama     // next operator has greater precedence than the previous one.
8252ec34544SRui Ueyama     // For example, if we have read "+" and "3", and if the next
8262ec34544SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
8272ec34544SRui Ueyama     while (!atEOF()) {
8282ec34544SRui Ueyama       StringRef Op2 = peek();
8292ec34544SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
8302ec34544SRui Ueyama         break;
8312ec34544SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
8322ec34544SRui Ueyama     }
8332ec34544SRui Ueyama 
8342ec34544SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
8352ec34544SRui Ueyama   }
8362ec34544SRui Ueyama   return Lhs;
8372ec34544SRui Ueyama }
8382ec34544SRui Ueyama 
8395fb17128SGeorge Rimar Expr ScriptParser::getPageSize() {
8405fb17128SGeorge Rimar   std::string Location = getCurrentLocation();
8415fb17128SGeorge Rimar   return [=]() -> uint64_t {
8425fb17128SGeorge Rimar     if (Target)
8432ec34544SRui Ueyama       return Target->PageSize;
8445fb17128SGeorge Rimar     error(Location + ": unable to calculate page size");
8455fb17128SGeorge Rimar     return 4096; // Return a dummy value.
8465fb17128SGeorge Rimar   };
8475fb17128SGeorge Rimar }
8485fb17128SGeorge Rimar 
8495fb17128SGeorge Rimar Expr ScriptParser::readConstant() {
8505fb17128SGeorge Rimar   StringRef S = readParenLiteral();
8515fb17128SGeorge Rimar   if (S == "COMMONPAGESIZE")
8525fb17128SGeorge Rimar     return getPageSize();
8532ec34544SRui Ueyama   if (S == "MAXPAGESIZE")
8545fb17128SGeorge Rimar     return [] { return Config->MaxPageSize; };
8555fb17128SGeorge Rimar   setError("unknown constant: " + S);
8565fb17128SGeorge Rimar   return {};
8572ec34544SRui Ueyama }
8582ec34544SRui Ueyama 
8595c65088fSRui Ueyama // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
8605c65088fSRui Ueyama // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
8615c65088fSRui Ueyama // have "K" (Ki) or "M" (Mi) suffixes.
8625c65088fSRui Ueyama static Optional<uint64_t> parseInt(StringRef Tok) {
8632ec34544SRui Ueyama   // Negative number
8642ec34544SRui Ueyama   if (Tok.startswith("-")) {
8655c65088fSRui Ueyama     if (Optional<uint64_t> Val = parseInt(Tok.substr(1)))
8665c65088fSRui Ueyama       return -*Val;
8675c65088fSRui Ueyama     return None;
8682ec34544SRui Ueyama   }
8692ec34544SRui Ueyama 
8702ec34544SRui Ueyama   // Hexadecimal
8715c65088fSRui Ueyama   uint64_t Val;
872ab94768cSGeorge Rimar   if (Tok.startswith_lower("0x") && to_integer(Tok.substr(2), Val, 16))
8735c65088fSRui Ueyama     return Val;
874ab94768cSGeorge Rimar   if (Tok.endswith_lower("H") && to_integer(Tok.drop_back(), Val, 16))
8755c65088fSRui Ueyama     return Val;
8762ec34544SRui Ueyama 
8772ec34544SRui Ueyama   // Decimal
8782ec34544SRui Ueyama   if (Tok.endswith_lower("K")) {
879ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
8805c65088fSRui Ueyama       return None;
8815c65088fSRui Ueyama     return Val * 1024;
8822ec34544SRui Ueyama   }
8835c65088fSRui Ueyama   if (Tok.endswith_lower("M")) {
884ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
8855c65088fSRui Ueyama       return None;
8865c65088fSRui Ueyama     return Val * 1024 * 1024;
8875c65088fSRui Ueyama   }
888ab94768cSGeorge Rimar   if (!to_integer(Tok, Val, 10))
8895c65088fSRui Ueyama     return None;
8905c65088fSRui Ueyama   return Val;
8912ec34544SRui Ueyama }
8922ec34544SRui Ueyama 
8932ec34544SRui Ueyama BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
894b579c439SRui Ueyama   int Size = StringSwitch<int>(Tok)
8952ec34544SRui Ueyama                  .Case("BYTE", 1)
8962ec34544SRui Ueyama                  .Case("SHORT", 2)
8972ec34544SRui Ueyama                  .Case("LONG", 4)
8982ec34544SRui Ueyama                  .Case("QUAD", 8)
8992ec34544SRui Ueyama                  .Default(-1);
9002ec34544SRui Ueyama   if (Size == -1)
9012ec34544SRui Ueyama     return nullptr;
9022ec34544SRui Ueyama 
9032ec34544SRui Ueyama   return make<BytesDataCommand>(readParenExpr(), Size);
9042ec34544SRui Ueyama }
9052ec34544SRui Ueyama 
9062ec34544SRui Ueyama StringRef ScriptParser::readParenLiteral() {
9072ec34544SRui Ueyama   expect("(");
9082ec34544SRui Ueyama   StringRef Tok = next();
9092ec34544SRui Ueyama   expect(")");
9102ec34544SRui Ueyama   return Tok;
9112ec34544SRui Ueyama }
9122ec34544SRui Ueyama 
9138c022ca7SRafael Espindola OutputSection *ScriptParser::checkSection(OutputSection *Cmd,
91405c4f67cSRafael Espindola                                           StringRef Location) {
91505c4f67cSRafael Espindola   if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
91605c4f67cSRafael Espindola     error(Location + ": undefined section " + Cmd->Name);
9178c022ca7SRafael Espindola   return Cmd;
91805c4f67cSRafael Espindola }
91905c4f67cSRafael Espindola 
9202ec34544SRui Ueyama Expr ScriptParser::readPrimary() {
9212ec34544SRui Ueyama   if (peek() == "(")
9222ec34544SRui Ueyama     return readParenExpr();
9232ec34544SRui Ueyama 
9245c65088fSRui Ueyama   if (consume("~")) {
9252ec34544SRui Ueyama     Expr E = readPrimary();
926b2fb84a1SRui Ueyama     return [=] { return ~E().getValue(); };
9272ec34544SRui Ueyama   }
9286f1d954eSHafiz Abid Qadeer   if (consume("!")) {
9296f1d954eSHafiz Abid Qadeer     Expr E = readPrimary();
9306f1d954eSHafiz Abid Qadeer     return [=] { return !E().getValue(); };
9316f1d954eSHafiz Abid Qadeer   }
9325c65088fSRui Ueyama   if (consume("-")) {
9332ec34544SRui Ueyama     Expr E = readPrimary();
934b2fb84a1SRui Ueyama     return [=] { return -E().getValue(); };
9352ec34544SRui Ueyama   }
9362ec34544SRui Ueyama 
9375c65088fSRui Ueyama   StringRef Tok = next();
9385c65088fSRui Ueyama   std::string Location = getCurrentLocation();
9395c65088fSRui Ueyama 
9402ec34544SRui Ueyama   // Built-in functions are parsed here.
9412ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
9422ec34544SRui Ueyama   if (Tok == "ABSOLUTE") {
9432ec34544SRui Ueyama     Expr Inner = readParenExpr();
9442ec34544SRui Ueyama     return [=] {
9452ec34544SRui Ueyama       ExprValue I = Inner();
9462ec34544SRui Ueyama       I.ForceAbsolute = true;
9472ec34544SRui Ueyama       return I;
9482ec34544SRui Ueyama     };
9492ec34544SRui Ueyama   }
9502ec34544SRui Ueyama   if (Tok == "ADDR") {
9512ec34544SRui Ueyama     StringRef Name = readParenLiteral();
9528c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
95341c7ab4aSGeorge Rimar     return [=]() -> ExprValue {
95441c7ab4aSGeorge Rimar       return {checkSection(Cmd, Location), 0, Location};
95541c7ab4aSGeorge Rimar     };
9562ec34544SRui Ueyama   }
9572ec34544SRui Ueyama   if (Tok == "ALIGN") {
9582ec34544SRui Ueyama     expect("(");
9592ec34544SRui Ueyama     Expr E = readExpr();
960b579c439SRui Ueyama     if (consume(")"))
96160833f6eSGeorge Rimar       return [=] {
96260833f6eSGeorge Rimar         return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
96360833f6eSGeorge Rimar       };
964b579c439SRui Ueyama     expect(",");
9652ec34544SRui Ueyama     Expr E2 = readExpr();
9662ec34544SRui Ueyama     expect(")");
9673c6de1a6SPetr Hosek     return [=] {
9683c6de1a6SPetr Hosek       ExprValue V = E();
96960833f6eSGeorge Rimar       V.Alignment = std::max((uint64_t)1, E2().getValue());
9703c6de1a6SPetr Hosek       return V;
9713c6de1a6SPetr Hosek     };
9722ec34544SRui Ueyama   }
9732ec34544SRui Ueyama   if (Tok == "ALIGNOF") {
9742ec34544SRui Ueyama     StringRef Name = readParenLiteral();
9758c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
97605c4f67cSRafael Espindola     return [=] { return checkSection(Cmd, Location)->Alignment; };
9772ec34544SRui Ueyama   }
9782ec34544SRui Ueyama   if (Tok == "ASSERT")
97923af89ccSRui Ueyama     return readAssertExpr();
9805fb17128SGeorge Rimar   if (Tok == "CONSTANT")
9815fb17128SGeorge Rimar     return readConstant();
9822ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
9832ec34544SRui Ueyama     expect("(");
9842ec34544SRui Ueyama     Expr E = readExpr();
9852ec34544SRui Ueyama     expect(",");
9862ec34544SRui Ueyama     readExpr();
9872ec34544SRui Ueyama     expect(")");
98860833f6eSGeorge Rimar     return [=] {
98960833f6eSGeorge Rimar       return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
99060833f6eSGeorge Rimar     };
9912ec34544SRui Ueyama   }
9922ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
9932ec34544SRui Ueyama     expect("(");
9942ec34544SRui Ueyama     expect(".");
9952ec34544SRui Ueyama     expect(")");
9962ec34544SRui Ueyama     return [] { return Script->getDot(); };
9972ec34544SRui Ueyama   }
9982ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_RELRO_END") {
9992ec34544SRui Ueyama     // GNU linkers implements more complicated logic to handle
10002ec34544SRui Ueyama     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
10012ec34544SRui Ueyama     // just align to the next page boundary for simplicity.
10022ec34544SRui Ueyama     expect("(");
10032ec34544SRui Ueyama     readExpr();
10042ec34544SRui Ueyama     expect(",");
10052ec34544SRui Ueyama     readExpr();
10062ec34544SRui Ueyama     expect(")");
10075fb17128SGeorge Rimar     Expr E = getPageSize();
10085fb17128SGeorge Rimar     return [=] { return alignTo(Script->getDot(), E().getValue()); };
10092ec34544SRui Ueyama   }
10102ec34544SRui Ueyama   if (Tok == "DEFINED") {
10112ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10122ec34544SRui Ueyama     return [=] { return Script->isDefined(Name) ? 1 : 0; };
10132ec34544SRui Ueyama   }
101491b95b61SRui Ueyama   if (Tok == "LENGTH") {
101591b95b61SRui Ueyama     StringRef Name = readParenLiteral();
101691b95b61SRui Ueyama     if (Script->Opt.MemoryRegions.count(Name) == 0)
101791b95b61SRui Ueyama       setError("memory region not defined: " + Name);
10185f37541cSGeorge Rimar     return [=] { return Script->Opt.MemoryRegions[Name]->Length; };
101991b95b61SRui Ueyama   }
10202ec34544SRui Ueyama   if (Tok == "LOADADDR") {
10212ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10228c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
102305c4f67cSRafael Espindola     return [=] { return checkSection(Cmd, Location)->getLMA(); };
10242ec34544SRui Ueyama   }
102591b95b61SRui Ueyama   if (Tok == "ORIGIN") {
102691b95b61SRui Ueyama     StringRef Name = readParenLiteral();
102791b95b61SRui Ueyama     if (Script->Opt.MemoryRegions.count(Name) == 0)
102891b95b61SRui Ueyama       setError("memory region not defined: " + Name);
10295f37541cSGeorge Rimar     return [=] { return Script->Opt.MemoryRegions[Name]->Origin; };
103091b95b61SRui Ueyama   }
10312ec34544SRui Ueyama   if (Tok == "SEGMENT_START") {
10322ec34544SRui Ueyama     expect("(");
10332ec34544SRui Ueyama     skip();
10342ec34544SRui Ueyama     expect(",");
10352ec34544SRui Ueyama     Expr E = readExpr();
10362ec34544SRui Ueyama     expect(")");
10372ec34544SRui Ueyama     return [=] { return E(); };
10382ec34544SRui Ueyama   }
10392ec34544SRui Ueyama   if (Tok == "SIZEOF") {
10402ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10418c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
104205c4f67cSRafael Espindola     // Linker script does not create an output section if its content is empty.
104305c4f67cSRafael Espindola     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
104405c4f67cSRafael Espindola     // be empty.
10458c022ca7SRafael Espindola     return [=] { return Cmd->Size; };
10462ec34544SRui Ueyama   }
10472ec34544SRui Ueyama   if (Tok == "SIZEOF_HEADERS")
10482ec34544SRui Ueyama     return [=] { return elf::getHeaderSize(); };
10492ec34544SRui Ueyama 
10504eb2eccbSRui Ueyama   // Tok is the dot.
10514eb2eccbSRui Ueyama   if (Tok == ".")
10524eb2eccbSRui Ueyama     return [=] { return Script->getSymbolValue(Location, Tok); };
10534eb2eccbSRui Ueyama 
10542ec34544SRui Ueyama   // Tok is a literal number.
10555c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
10565c65088fSRui Ueyama     return [=] { return *Val; };
10572ec34544SRui Ueyama 
10582ec34544SRui Ueyama   // Tok is a symbol name.
10592ec34544SRui Ueyama   if (!isValidCIdentifier(Tok))
10602ec34544SRui Ueyama     setError("malformed number: " + Tok);
10614eb2eccbSRui Ueyama   Script->Opt.ReferencedSymbols.push_back(Tok);
10622ec34544SRui Ueyama   return [=] { return Script->getSymbolValue(Location, Tok); };
10632ec34544SRui Ueyama }
10642ec34544SRui Ueyama 
10652ec34544SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
10662ec34544SRui Ueyama   Expr L = readExpr();
10672ec34544SRui Ueyama   expect(":");
10682ec34544SRui Ueyama   Expr R = readExpr();
10692ec34544SRui Ueyama   return [=] { return Cond().getValue() ? L() : R(); };
10702ec34544SRui Ueyama }
10712ec34544SRui Ueyama 
10722ec34544SRui Ueyama Expr ScriptParser::readParenExpr() {
10732ec34544SRui Ueyama   expect("(");
10742ec34544SRui Ueyama   Expr E = readExpr();
10752ec34544SRui Ueyama   expect(")");
10762ec34544SRui Ueyama   return E;
10772ec34544SRui Ueyama }
10782ec34544SRui Ueyama 
10792ec34544SRui Ueyama std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
10802ec34544SRui Ueyama   std::vector<StringRef> Phdrs;
1081ce608081SGeorge Rimar   while (!ErrorCount && peek().startswith(":")) {
10822ec34544SRui Ueyama     StringRef Tok = next();
10832ec34544SRui Ueyama     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
10842ec34544SRui Ueyama   }
10852ec34544SRui Ueyama   return Phdrs;
10862ec34544SRui Ueyama }
10872ec34544SRui Ueyama 
10882ec34544SRui Ueyama // Read a program header type name. The next token must be a
10892ec34544SRui Ueyama // name of a program header type or a constant (e.g. "0x3").
10902ec34544SRui Ueyama unsigned ScriptParser::readPhdrType() {
10912ec34544SRui Ueyama   StringRef Tok = next();
10925c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
10935c65088fSRui Ueyama     return *Val;
10942ec34544SRui Ueyama 
10952ec34544SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
10962ec34544SRui Ueyama                      .Case("PT_NULL", PT_NULL)
10972ec34544SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
10982ec34544SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
10992ec34544SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
11002ec34544SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
11012ec34544SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
11022ec34544SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
11032ec34544SRui Ueyama                      .Case("PT_TLS", PT_TLS)
11042ec34544SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
11052ec34544SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
11062ec34544SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
11072ec34544SRui Ueyama                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
11082ec34544SRui Ueyama                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
11092ec34544SRui Ueyama                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
11102ec34544SRui Ueyama                      .Default(-1);
11112ec34544SRui Ueyama 
11122ec34544SRui Ueyama   if (Ret == (unsigned)-1) {
11132ec34544SRui Ueyama     setError("invalid program header type: " + Tok);
11142ec34544SRui Ueyama     return PT_NULL;
11152ec34544SRui Ueyama   }
11162ec34544SRui Ueyama   return Ret;
11172ec34544SRui Ueyama }
11182ec34544SRui Ueyama 
11192ec34544SRui Ueyama // Reads an anonymous version declaration.
11202ec34544SRui Ueyama void ScriptParser::readAnonymousDeclaration() {
11212ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
11222ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
11232ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
11242ec34544SRui Ueyama 
11252ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
11262ec34544SRui Ueyama     if (V.Name == "*")
11272ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
11282ec34544SRui Ueyama     else
11292ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
11302ec34544SRui Ueyama   }
11312ec34544SRui Ueyama 
11322ec34544SRui Ueyama   for (SymbolVersion V : Globals)
11332ec34544SRui Ueyama     Config->VersionScriptGlobals.push_back(V);
11342ec34544SRui Ueyama 
11352ec34544SRui Ueyama   expect(";");
11362ec34544SRui Ueyama }
11372ec34544SRui Ueyama 
11382ec34544SRui Ueyama // Reads a non-anonymous version definition,
11392ec34544SRui Ueyama // e.g. "VerStr { global: foo; bar; local: *; };".
11402ec34544SRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
11412ec34544SRui Ueyama   // Read a symbol list.
11422ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
11432ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
11442ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
11452ec34544SRui Ueyama 
11462ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
11472ec34544SRui Ueyama     if (V.Name == "*")
11482ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
11492ec34544SRui Ueyama     else
11502ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
11512ec34544SRui Ueyama   }
11522ec34544SRui Ueyama 
11532ec34544SRui Ueyama   // Create a new version definition and add that to the global symbols.
11542ec34544SRui Ueyama   VersionDefinition Ver;
11552ec34544SRui Ueyama   Ver.Name = VerStr;
11562ec34544SRui Ueyama   Ver.Globals = Globals;
11572ec34544SRui Ueyama 
11582ec34544SRui Ueyama   // User-defined version number starts from 2 because 0 and 1 are
11592ec34544SRui Ueyama   // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
11602ec34544SRui Ueyama   Ver.Id = Config->VersionDefinitions.size() + 2;
11612ec34544SRui Ueyama   Config->VersionDefinitions.push_back(Ver);
11622ec34544SRui Ueyama 
11632ec34544SRui Ueyama   // Each version may have a parent version. For example, "Ver2"
11642ec34544SRui Ueyama   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
11652ec34544SRui Ueyama   // as a parent. This version hierarchy is, probably against your
11662ec34544SRui Ueyama   // instinct, purely for hint; the runtime doesn't care about it
11672ec34544SRui Ueyama   // at all. In LLD, we simply ignore it.
11682ec34544SRui Ueyama   if (peek() != ";")
11692ec34544SRui Ueyama     skip();
11702ec34544SRui Ueyama   expect(";");
11712ec34544SRui Ueyama }
11722ec34544SRui Ueyama 
11731e77ad14SRui Ueyama static bool hasWildcard(StringRef S) {
11741e77ad14SRui Ueyama   return S.find_first_of("?*[") != StringRef::npos;
11751e77ad14SRui Ueyama }
11761e77ad14SRui Ueyama 
11772ec34544SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
11782ec34544SRui Ueyama std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
11792ec34544SRui Ueyama ScriptParser::readSymbols() {
11802ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
11812ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
11822ec34544SRui Ueyama   std::vector<SymbolVersion> *V = &Globals;
11832ec34544SRui Ueyama 
1184ce608081SGeorge Rimar   while (!ErrorCount) {
11852ec34544SRui Ueyama     if (consume("}"))
11862ec34544SRui Ueyama       break;
11872ec34544SRui Ueyama     if (consumeLabel("local")) {
11882ec34544SRui Ueyama       V = &Locals;
11892ec34544SRui Ueyama       continue;
11902ec34544SRui Ueyama     }
11912ec34544SRui Ueyama     if (consumeLabel("global")) {
11922ec34544SRui Ueyama       V = &Globals;
11932ec34544SRui Ueyama       continue;
11942ec34544SRui Ueyama     }
11952ec34544SRui Ueyama 
11962ec34544SRui Ueyama     if (consume("extern")) {
11972ec34544SRui Ueyama       std::vector<SymbolVersion> Ext = readVersionExtern();
11982ec34544SRui Ueyama       V->insert(V->end(), Ext.begin(), Ext.end());
11992ec34544SRui Ueyama     } else {
12002ec34544SRui Ueyama       StringRef Tok = next();
12012ec34544SRui Ueyama       V->push_back({unquote(Tok), false, hasWildcard(Tok)});
12022ec34544SRui Ueyama     }
12032ec34544SRui Ueyama     expect(";");
12042ec34544SRui Ueyama   }
12052ec34544SRui Ueyama   return {Locals, Globals};
12062ec34544SRui Ueyama }
12072ec34544SRui Ueyama 
12082ec34544SRui Ueyama // Reads an "extern C++" directive, e.g.,
12092ec34544SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };"
12102ec34544SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
12112ec34544SRui Ueyama   StringRef Tok = next();
12122ec34544SRui Ueyama   bool IsCXX = Tok == "\"C++\"";
12132ec34544SRui Ueyama   if (!IsCXX && Tok != "\"C\"")
12142ec34544SRui Ueyama     setError("Unknown language");
12152ec34544SRui Ueyama   expect("{");
12162ec34544SRui Ueyama 
12172ec34544SRui Ueyama   std::vector<SymbolVersion> Ret;
1218ce608081SGeorge Rimar   while (!ErrorCount && peek() != "}") {
12192ec34544SRui Ueyama     StringRef Tok = next();
12202ec34544SRui Ueyama     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
12212ec34544SRui Ueyama     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
12222ec34544SRui Ueyama     expect(";");
12232ec34544SRui Ueyama   }
12242ec34544SRui Ueyama 
12252ec34544SRui Ueyama   expect("}");
12262ec34544SRui Ueyama   return Ret;
12272ec34544SRui Ueyama }
12282ec34544SRui Ueyama 
12292ec34544SRui Ueyama uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
12302ec34544SRui Ueyama                                             StringRef S3) {
1231b579c439SRui Ueyama   if (!consume(S1) && !consume(S2) && !consume(S3)) {
12322ec34544SRui Ueyama     setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
12332ec34544SRui Ueyama     return 0;
12342ec34544SRui Ueyama   }
12352ec34544SRui Ueyama   expect("=");
1236040af7deSRui Ueyama   return readExpr()().getValue();
12372ec34544SRui Ueyama }
12382ec34544SRui Ueyama 
12392ec34544SRui Ueyama // Parse the MEMORY command as specified in:
12402ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/MEMORY.html
12412ec34544SRui Ueyama //
12422ec34544SRui Ueyama // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
12432ec34544SRui Ueyama void ScriptParser::readMemory() {
12442ec34544SRui Ueyama   expect("{");
1245ce608081SGeorge Rimar   while (!ErrorCount && !consume("}")) {
12462ec34544SRui Ueyama     StringRef Name = next();
12472ec34544SRui Ueyama 
12482ec34544SRui Ueyama     uint32_t Flags = 0;
12492ec34544SRui Ueyama     uint32_t NegFlags = 0;
12502ec34544SRui Ueyama     if (consume("(")) {
12512ec34544SRui Ueyama       std::tie(Flags, NegFlags) = readMemoryAttributes();
12522ec34544SRui Ueyama       expect(")");
12532ec34544SRui Ueyama     }
12542ec34544SRui Ueyama     expect(":");
12552ec34544SRui Ueyama 
12562ec34544SRui Ueyama     uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
12572ec34544SRui Ueyama     expect(",");
12582ec34544SRui Ueyama     uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
12592ec34544SRui Ueyama 
12605f37541cSGeorge Rimar     // Add the memory region to the region map.
12615f37541cSGeorge Rimar     if (Script->Opt.MemoryRegions.count(Name))
12622ec34544SRui Ueyama       setError("region '" + Name + "' already defined");
12635f37541cSGeorge Rimar     MemoryRegion *MR = make<MemoryRegion>();
12645f37541cSGeorge Rimar     *MR = {Name, Origin, Length, Flags, NegFlags};
12655f37541cSGeorge Rimar     Script->Opt.MemoryRegions[Name] = MR;
12662ec34544SRui Ueyama   }
12672ec34544SRui Ueyama }
12682ec34544SRui Ueyama 
12692ec34544SRui Ueyama // This function parses the attributes used to match against section
12702ec34544SRui Ueyama // flags when placing output sections in a memory region. These flags
12712ec34544SRui Ueyama // are only used when an explicit memory region name is not used.
12722ec34544SRui Ueyama std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
12732ec34544SRui Ueyama   uint32_t Flags = 0;
12742ec34544SRui Ueyama   uint32_t NegFlags = 0;
12752ec34544SRui Ueyama   bool Invert = false;
12762ec34544SRui Ueyama 
12772ec34544SRui Ueyama   for (char C : next().lower()) {
12782ec34544SRui Ueyama     uint32_t Flag = 0;
12792ec34544SRui Ueyama     if (C == '!')
12802ec34544SRui Ueyama       Invert = !Invert;
12812ec34544SRui Ueyama     else if (C == 'w')
12822ec34544SRui Ueyama       Flag = SHF_WRITE;
12832ec34544SRui Ueyama     else if (C == 'x')
12842ec34544SRui Ueyama       Flag = SHF_EXECINSTR;
12852ec34544SRui Ueyama     else if (C == 'a')
12862ec34544SRui Ueyama       Flag = SHF_ALLOC;
12872ec34544SRui Ueyama     else if (C != 'r')
12882ec34544SRui Ueyama       setError("invalid memory region attribute");
12892ec34544SRui Ueyama 
12902ec34544SRui Ueyama     if (Invert)
12912ec34544SRui Ueyama       NegFlags |= Flag;
12922ec34544SRui Ueyama     else
12932ec34544SRui Ueyama       Flags |= Flag;
12942ec34544SRui Ueyama   }
12952ec34544SRui Ueyama   return {Flags, NegFlags};
12962ec34544SRui Ueyama }
12972ec34544SRui Ueyama 
12982ec34544SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
12992ec34544SRui Ueyama   ScriptParser(MB).readLinkerScript();
13002ec34544SRui Ueyama }
13012ec34544SRui Ueyama 
13022ec34544SRui Ueyama void elf::readVersionScript(MemoryBufferRef MB) {
13032ec34544SRui Ueyama   ScriptParser(MB).readVersionScript();
13042ec34544SRui Ueyama }
13052ec34544SRui Ueyama 
13062ec34544SRui Ueyama void elf::readDynamicList(MemoryBufferRef MB) {
13072ec34544SRui Ueyama   ScriptParser(MB).readDynamicList();
13082ec34544SRui Ueyama }
1309