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);
592ec34544SRui Ueyama 
602ec34544SRui Ueyama   void readAsNeeded();
612ec34544SRui Ueyama   void readEntry();
622ec34544SRui Ueyama   void readExtern();
632ec34544SRui Ueyama   void readGroup();
642ec34544SRui Ueyama   void readInclude();
652ec34544SRui Ueyama   void readMemory();
662ec34544SRui Ueyama   void readOutput();
672ec34544SRui Ueyama   void readOutputArch();
682ec34544SRui Ueyama   void readOutputFormat();
692ec34544SRui Ueyama   void readPhdrs();
705f37541cSGeorge Rimar   void readRegionAlias();
712ec34544SRui Ueyama   void readSearchDir();
722ec34544SRui Ueyama   void readSections();
732ec34544SRui Ueyama   void readVersion();
742ec34544SRui Ueyama   void readVersionScriptCommand();
752ec34544SRui Ueyama 
762ec34544SRui Ueyama   SymbolAssignment *readAssignment(StringRef Name);
77f0403c60SRui Ueyama   ByteCommand *readByteCommand(StringRef Tok);
782ec34544SRui Ueyama   uint32_t readFill();
798acbf1ccSRui Ueyama   uint32_t parseFill(StringRef Tok);
808c022ca7SRafael Espindola   void readSectionAddressType(OutputSection *Cmd);
818c022ca7SRafael Espindola   OutputSection *readOutputSectionDescription(StringRef OutSec);
822ec34544SRui Ueyama   std::vector<StringRef> readOutputSectionPhdrs();
832ec34544SRui Ueyama   InputSectionDescription *readInputSectionDescription(StringRef Tok);
842ec34544SRui Ueyama   StringMatcher readFilePatterns();
852ec34544SRui Ueyama   std::vector<SectionPattern> readInputSectionsList();
862ec34544SRui Ueyama   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
872ec34544SRui Ueyama   unsigned readPhdrType();
882ec34544SRui Ueyama   SortSectionPolicy readSortKind();
892ec34544SRui Ueyama   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
902ec34544SRui Ueyama   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
912ec34544SRui Ueyama   void readSort();
9223af89ccSRui Ueyama   AssertCommand *readAssert();
9323af89ccSRui Ueyama   Expr readAssertExpr();
945fb17128SGeorge Rimar   Expr readConstant();
955fb17128SGeorge Rimar   Expr getPageSize();
962ec34544SRui Ueyama 
972ec34544SRui Ueyama   uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
982ec34544SRui Ueyama   std::pair<uint32_t, uint32_t> readMemoryAttributes();
992ec34544SRui Ueyama 
1002ec34544SRui Ueyama   Expr readExpr();
1012ec34544SRui Ueyama   Expr readExpr1(Expr Lhs, int MinPrec);
1022ec34544SRui Ueyama   StringRef readParenLiteral();
1032ec34544SRui Ueyama   Expr readPrimary();
1042ec34544SRui Ueyama   Expr readTernary(Expr Cond);
1052ec34544SRui Ueyama   Expr readParenExpr();
1062ec34544SRui Ueyama 
1072ec34544SRui Ueyama   // For parsing version script.
1082ec34544SRui Ueyama   std::vector<SymbolVersion> readVersionExtern();
1092ec34544SRui Ueyama   void readAnonymousDeclaration();
1102ec34544SRui Ueyama   void readVersionDeclaration(StringRef VerStr);
1112ec34544SRui Ueyama 
1122ec34544SRui Ueyama   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1132ec34544SRui Ueyama   readSymbols();
1142ec34544SRui Ueyama 
115fd06b025SRui Ueyama   // True if a script being read is in a subdirectory specified by -sysroot.
1162ec34544SRui Ueyama   bool IsUnderSysroot;
1170440be4aSRui Ueyama 
1180440be4aSRui Ueyama   // A set to detect an INCLUDE() cycle.
1190440be4aSRui Ueyama   StringSet<> Seen;
1202ec34544SRui Ueyama };
12196b3fe02SRui Ueyama } // namespace
1222ec34544SRui Ueyama 
1231e77ad14SRui Ueyama static StringRef unquote(StringRef S) {
1241e77ad14SRui Ueyama   if (S.startswith("\""))
1251e77ad14SRui Ueyama     return S.substr(1, S.size() - 2);
1261e77ad14SRui Ueyama   return S;
1271e77ad14SRui Ueyama }
1281e77ad14SRui Ueyama 
1292ec34544SRui Ueyama static bool isUnderSysroot(StringRef Path) {
1302ec34544SRui Ueyama   if (Config->Sysroot == "")
1312ec34544SRui Ueyama     return false;
1322ec34544SRui Ueyama   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1332ec34544SRui Ueyama     if (sys::fs::equivalent(Config->Sysroot, Path))
1342ec34544SRui Ueyama       return true;
1352ec34544SRui Ueyama   return false;
1362ec34544SRui Ueyama }
1372ec34544SRui Ueyama 
1382ec34544SRui Ueyama // Some operations only support one non absolute value. Move the
1392ec34544SRui Ueyama // absolute one to the right hand side for convenience.
1402ec34544SRui Ueyama static void moveAbsRight(ExprValue &A, ExprValue &B) {
14123be5e8dSRafael Espindola   if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute()))
1422ec34544SRui Ueyama     std::swap(A, B);
1432ec34544SRui Ueyama   if (!B.isAbsolute())
14441c7ab4aSGeorge Rimar     error(A.Loc + ": at least one side of the expression must be absolute");
1452ec34544SRui Ueyama }
1462ec34544SRui Ueyama 
1472ec34544SRui Ueyama static ExprValue add(ExprValue A, ExprValue B) {
1482ec34544SRui Ueyama   moveAbsRight(A, B);
149a6acd23cSRafael Espindola   return {A.Sec, A.ForceAbsolute, A.getSectionOffset() + B.getValue(), A.Loc};
1502ec34544SRui Ueyama }
1512ec34544SRui Ueyama 
1522ec34544SRui Ueyama static ExprValue sub(ExprValue A, ExprValue B) {
1534fbe3518SRui Ueyama   return {A.Sec, false, A.getSectionOffset() - B.getValue(), A.Loc};
1542ec34544SRui Ueyama }
1552ec34544SRui Ueyama 
1562ec34544SRui Ueyama static ExprValue mul(ExprValue A, ExprValue B) {
1572ec34544SRui Ueyama   return A.getValue() * B.getValue();
1582ec34544SRui Ueyama }
1592ec34544SRui Ueyama 
1602ec34544SRui Ueyama static ExprValue div(ExprValue A, ExprValue B) {
1612ec34544SRui Ueyama   if (uint64_t BV = B.getValue())
1622ec34544SRui Ueyama     return A.getValue() / BV;
1632ec34544SRui Ueyama   error("division by zero");
1642ec34544SRui Ueyama   return 0;
1652ec34544SRui Ueyama }
1662ec34544SRui Ueyama 
1672ec34544SRui Ueyama static ExprValue bitAnd(ExprValue A, ExprValue B) {
1682ec34544SRui Ueyama   moveAbsRight(A, B);
1692ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
17041c7ab4aSGeorge Rimar           (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc};
1712ec34544SRui Ueyama }
1722ec34544SRui Ueyama 
1732ec34544SRui Ueyama static ExprValue bitOr(ExprValue A, ExprValue B) {
1742ec34544SRui Ueyama   moveAbsRight(A, B);
1752ec34544SRui Ueyama   return {A.Sec, A.ForceAbsolute,
17641c7ab4aSGeorge Rimar           (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc};
1772ec34544SRui Ueyama }
1782ec34544SRui Ueyama 
1792ec34544SRui Ueyama void ScriptParser::readDynamicList() {
1808016bdfdSRafael Espindola   Config->HasDynamicList = true;
1812ec34544SRui Ueyama   expect("{");
182d72d97b3SRafael Espindola   std::vector<SymbolVersion> Locals;
183d72d97b3SRafael Espindola   std::vector<SymbolVersion> Globals;
184d72d97b3SRafael Espindola   std::tie(Locals, Globals) = readSymbols();
185d72d97b3SRafael Espindola   expect(";");
186d72d97b3SRafael Espindola 
187d72d97b3SRafael Espindola   if (!atEOF()) {
1882ec34544SRui Ueyama     setError("EOF expected, but got " + next());
189d72d97b3SRafael Espindola     return;
190d72d97b3SRafael Espindola   }
191d72d97b3SRafael Espindola   if (!Locals.empty()) {
192d72d97b3SRafael Espindola     setError("\"local:\" scope not supported in --dynamic-list");
193d72d97b3SRafael Espindola     return;
194d72d97b3SRafael Espindola   }
195d72d97b3SRafael Espindola 
196d72d97b3SRafael Espindola   for (SymbolVersion V : Globals)
197d72d97b3SRafael Espindola     Config->DynamicList.push_back(V);
1982ec34544SRui Ueyama }
1992ec34544SRui Ueyama 
2002ec34544SRui Ueyama void ScriptParser::readVersionScript() {
2012ec34544SRui Ueyama   readVersionScriptCommand();
2022ec34544SRui Ueyama   if (!atEOF())
2032ec34544SRui Ueyama     setError("EOF expected, but got " + next());
2042ec34544SRui Ueyama }
2052ec34544SRui Ueyama 
2062ec34544SRui Ueyama void ScriptParser::readVersionScriptCommand() {
2072ec34544SRui Ueyama   if (consume("{")) {
2082ec34544SRui Ueyama     readAnonymousDeclaration();
2092ec34544SRui Ueyama     return;
2102ec34544SRui Ueyama   }
2112ec34544SRui Ueyama 
212*b8a59c8aSBob Haarman   while (!atEOF() && !errorCount() && peek() != "}") {
2132ec34544SRui Ueyama     StringRef VerStr = next();
2142ec34544SRui Ueyama     if (VerStr == "{") {
2152ec34544SRui Ueyama       setError("anonymous version definition is used in "
2162ec34544SRui Ueyama                "combination with other version definitions");
2172ec34544SRui Ueyama       return;
2182ec34544SRui Ueyama     }
2192ec34544SRui Ueyama     expect("{");
2202ec34544SRui Ueyama     readVersionDeclaration(VerStr);
2212ec34544SRui Ueyama   }
2222ec34544SRui Ueyama }
2232ec34544SRui Ueyama 
2242ec34544SRui Ueyama void ScriptParser::readVersion() {
2252ec34544SRui Ueyama   expect("{");
2262ec34544SRui Ueyama   readVersionScriptCommand();
2272ec34544SRui Ueyama   expect("}");
2282ec34544SRui Ueyama }
2292ec34544SRui Ueyama 
2302ec34544SRui Ueyama void ScriptParser::readLinkerScript() {
2312ec34544SRui Ueyama   while (!atEOF()) {
2322ec34544SRui Ueyama     StringRef Tok = next();
2332ec34544SRui Ueyama     if (Tok == ";")
2342ec34544SRui Ueyama       continue;
2352ec34544SRui Ueyama 
2362ec34544SRui Ueyama     if (Tok == "ASSERT") {
2376b394caaSRui Ueyama       Script->SectionCommands.push_back(readAssert());
2382ec34544SRui Ueyama     } else if (Tok == "ENTRY") {
2392ec34544SRui Ueyama       readEntry();
2402ec34544SRui Ueyama     } else if (Tok == "EXTERN") {
2412ec34544SRui Ueyama       readExtern();
2422ec34544SRui Ueyama     } else if (Tok == "GROUP" || Tok == "INPUT") {
2432ec34544SRui Ueyama       readGroup();
2442ec34544SRui Ueyama     } else if (Tok == "INCLUDE") {
2452ec34544SRui Ueyama       readInclude();
2462ec34544SRui Ueyama     } else if (Tok == "MEMORY") {
2472ec34544SRui Ueyama       readMemory();
2482ec34544SRui Ueyama     } else if (Tok == "OUTPUT") {
2492ec34544SRui Ueyama       readOutput();
2502ec34544SRui Ueyama     } else if (Tok == "OUTPUT_ARCH") {
2512ec34544SRui Ueyama       readOutputArch();
2522ec34544SRui Ueyama     } else if (Tok == "OUTPUT_FORMAT") {
2532ec34544SRui Ueyama       readOutputFormat();
2542ec34544SRui Ueyama     } else if (Tok == "PHDRS") {
2552ec34544SRui Ueyama       readPhdrs();
2565f37541cSGeorge Rimar     } else if (Tok == "REGION_ALIAS") {
2575f37541cSGeorge Rimar       readRegionAlias();
2582ec34544SRui Ueyama     } else if (Tok == "SEARCH_DIR") {
2592ec34544SRui Ueyama       readSearchDir();
2602ec34544SRui Ueyama     } else if (Tok == "SECTIONS") {
2612ec34544SRui Ueyama       readSections();
2622ec34544SRui Ueyama     } else if (Tok == "VERSION") {
2632ec34544SRui Ueyama       readVersion();
2642ec34544SRui Ueyama     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
2656b394caaSRui Ueyama       Script->SectionCommands.push_back(Cmd);
2662ec34544SRui Ueyama     } else {
2672ec34544SRui Ueyama       setError("unknown directive: " + Tok);
2682ec34544SRui Ueyama     }
2692ec34544SRui Ueyama   }
2702ec34544SRui Ueyama }
2712ec34544SRui Ueyama 
2722ec34544SRui Ueyama void ScriptParser::addFile(StringRef S) {
2732ec34544SRui Ueyama   if (IsUnderSysroot && S.startswith("/")) {
2742ec34544SRui Ueyama     SmallString<128> PathData;
2752ec34544SRui Ueyama     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
2762ec34544SRui Ueyama     if (sys::fs::exists(Path)) {
277a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
2782ec34544SRui Ueyama       return;
2792ec34544SRui Ueyama     }
2802ec34544SRui Ueyama   }
2812ec34544SRui Ueyama 
282875ae82bSRui Ueyama   if (S.startswith("/")) {
283a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2842ec34544SRui Ueyama   } else if (S.startswith("=")) {
2852ec34544SRui Ueyama     if (Config->Sysroot.empty())
286a76349bfSEvgeniy Stepanov       Driver->addFile(S.substr(1), /*WithLOption=*/false);
2872ec34544SRui Ueyama     else
288a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
289a76349bfSEvgeniy Stepanov                       /*WithLOption=*/false);
2902ec34544SRui Ueyama   } else if (S.startswith("-l")) {
2912ec34544SRui Ueyama     Driver->addLibrary(S.substr(2));
2922ec34544SRui Ueyama   } else if (sys::fs::exists(S)) {
293a76349bfSEvgeniy Stepanov     Driver->addFile(S, /*WithLOption=*/false);
2942ec34544SRui Ueyama   } else {
2952ec34544SRui Ueyama     if (Optional<std::string> Path = findFromSearchPaths(S))
296a76349bfSEvgeniy Stepanov       Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
2972ec34544SRui Ueyama     else
2982ec34544SRui Ueyama       setError("unable to find " + S);
2992ec34544SRui Ueyama   }
3002ec34544SRui Ueyama }
3012ec34544SRui Ueyama 
3022ec34544SRui Ueyama void ScriptParser::readAsNeeded() {
3032ec34544SRui Ueyama   expect("(");
3042ec34544SRui Ueyama   bool Orig = Config->AsNeeded;
3052ec34544SRui Ueyama   Config->AsNeeded = true;
306*b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3072ec34544SRui Ueyama     addFile(unquote(next()));
3082ec34544SRui Ueyama   Config->AsNeeded = Orig;
3092ec34544SRui Ueyama }
3102ec34544SRui Ueyama 
3112ec34544SRui Ueyama void ScriptParser::readEntry() {
3122ec34544SRui Ueyama   // -e <symbol> takes predecence over ENTRY(<symbol>).
3132ec34544SRui Ueyama   expect("(");
3142ec34544SRui Ueyama   StringRef Tok = next();
3152ec34544SRui Ueyama   if (Config->Entry.empty())
3162ec34544SRui Ueyama     Config->Entry = Tok;
3172ec34544SRui Ueyama   expect(")");
3182ec34544SRui Ueyama }
3192ec34544SRui Ueyama 
3202ec34544SRui Ueyama void ScriptParser::readExtern() {
3212ec34544SRui Ueyama   expect("(");
322*b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3232ec34544SRui Ueyama     Config->Undefined.push_back(next());
3242ec34544SRui Ueyama }
3252ec34544SRui Ueyama 
3262ec34544SRui Ueyama void ScriptParser::readGroup() {
3272ec34544SRui Ueyama   expect("(");
328*b8a59c8aSBob Haarman   while (!errorCount() && !consume(")")) {
329b579c439SRui Ueyama     if (consume("AS_NEEDED"))
3302ec34544SRui Ueyama       readAsNeeded();
3312ec34544SRui Ueyama     else
332b579c439SRui Ueyama       addFile(unquote(next()));
3332ec34544SRui Ueyama   }
3342ec34544SRui Ueyama }
3352ec34544SRui Ueyama 
3362ec34544SRui Ueyama void ScriptParser::readInclude() {
3372ec34544SRui Ueyama   StringRef Tok = unquote(next());
3382ec34544SRui Ueyama 
3390440be4aSRui Ueyama   if (!Seen.insert(Tok).second) {
3400440be4aSRui Ueyama     setError("there is a cycle in linker script INCLUDEs");
3410440be4aSRui Ueyama     return;
3420440be4aSRui Ueyama   }
3430440be4aSRui Ueyama 
3442ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/File-Commands.html:
3452ec34544SRui Ueyama   // The file will be searched for in the current directory, and in any
3462ec34544SRui Ueyama   // directory specified with the -L option.
3472ec34544SRui Ueyama   if (sys::fs::exists(Tok)) {
3482ec34544SRui Ueyama     if (Optional<MemoryBufferRef> MB = readFile(Tok))
3492ec34544SRui Ueyama       tokenize(*MB);
3502ec34544SRui Ueyama     return;
3512ec34544SRui Ueyama   }
3522ec34544SRui Ueyama   if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
3532ec34544SRui Ueyama     if (Optional<MemoryBufferRef> MB = readFile(*Path))
3542ec34544SRui Ueyama       tokenize(*MB);
3552ec34544SRui Ueyama     return;
3562ec34544SRui Ueyama   }
3572ec34544SRui Ueyama   setError("cannot open " + Tok);
3582ec34544SRui Ueyama }
3592ec34544SRui Ueyama 
3602ec34544SRui Ueyama void ScriptParser::readOutput() {
3612ec34544SRui Ueyama   // -o <file> takes predecence over OUTPUT(<file>).
3622ec34544SRui Ueyama   expect("(");
3632ec34544SRui Ueyama   StringRef Tok = next();
3642ec34544SRui Ueyama   if (Config->OutputFile.empty())
3652ec34544SRui Ueyama     Config->OutputFile = unquote(Tok);
3662ec34544SRui Ueyama   expect(")");
3672ec34544SRui Ueyama }
3682ec34544SRui Ueyama 
3692ec34544SRui Ueyama void ScriptParser::readOutputArch() {
3702ec34544SRui Ueyama   // OUTPUT_ARCH is ignored for now.
3712ec34544SRui Ueyama   expect("(");
372*b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
3732ec34544SRui Ueyama     skip();
3742ec34544SRui Ueyama }
3752ec34544SRui Ueyama 
3762ec34544SRui Ueyama void ScriptParser::readOutputFormat() {
3772ec34544SRui Ueyama   // Error checking only for now.
3782ec34544SRui Ueyama   expect("(");
3792ec34544SRui Ueyama   skip();
380b579c439SRui Ueyama   if (consume(")"))
3812ec34544SRui Ueyama     return;
382b579c439SRui Ueyama   expect(",");
3832ec34544SRui Ueyama   skip();
3842ec34544SRui Ueyama   expect(",");
3852ec34544SRui Ueyama   skip();
3862ec34544SRui Ueyama   expect(")");
3872ec34544SRui Ueyama }
3882ec34544SRui Ueyama 
3892ec34544SRui Ueyama void ScriptParser::readPhdrs() {
3902ec34544SRui Ueyama   expect("{");
3912ec34544SRui Ueyama 
392*b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
3930ae2c24cSRui Ueyama     PhdrsCommand Cmd;
3940ae2c24cSRui Ueyama     Cmd.Name = next();
3950ae2c24cSRui Ueyama     Cmd.Type = readPhdrType();
396b579c439SRui Ueyama 
397*b8a59c8aSBob Haarman     while (!errorCount() && !consume(";")) {
398b579c439SRui Ueyama       if (consume("FILEHDR"))
3990ae2c24cSRui Ueyama         Cmd.HasFilehdr = true;
400b579c439SRui Ueyama       else if (consume("PHDRS"))
4010ae2c24cSRui Ueyama         Cmd.HasPhdrs = true;
402b579c439SRui Ueyama       else if (consume("AT"))
4030ae2c24cSRui Ueyama         Cmd.LMAExpr = readParenExpr();
404b579c439SRui Ueyama       else if (consume("FLAGS"))
4050ae2c24cSRui Ueyama         Cmd.Flags = readParenExpr()().getValue();
406b579c439SRui Ueyama       else
407b579c439SRui Ueyama         setError("unexpected header attribute: " + next());
408b579c439SRui Ueyama     }
4090ae2c24cSRui Ueyama 
410ac27de9dSRui Ueyama     Script->PhdrsCommands.push_back(Cmd);
4112ec34544SRui Ueyama   }
4122ec34544SRui Ueyama }
4132ec34544SRui Ueyama 
4145f37541cSGeorge Rimar void ScriptParser::readRegionAlias() {
4155f37541cSGeorge Rimar   expect("(");
4165f37541cSGeorge Rimar   StringRef Alias = unquote(next());
4175f37541cSGeorge Rimar   expect(",");
4185f37541cSGeorge Rimar   StringRef Name = next();
4195f37541cSGeorge Rimar   expect(")");
4205f37541cSGeorge Rimar 
421ac27de9dSRui Ueyama   if (Script->MemoryRegions.count(Alias))
4225f37541cSGeorge Rimar     setError("redefinition of memory region '" + Alias + "'");
423ac27de9dSRui Ueyama   if (!Script->MemoryRegions.count(Name))
4245f37541cSGeorge Rimar     setError("memory region '" + Name + "' is not defined");
425ac27de9dSRui Ueyama   Script->MemoryRegions[Alias] = Script->MemoryRegions[Name];
4265f37541cSGeorge Rimar }
4275f37541cSGeorge Rimar 
4282ec34544SRui Ueyama void ScriptParser::readSearchDir() {
4292ec34544SRui Ueyama   expect("(");
4302ec34544SRui Ueyama   StringRef Tok = next();
4312ec34544SRui Ueyama   if (!Config->Nostdlib)
4322ec34544SRui Ueyama     Config->SearchPaths.push_back(unquote(Tok));
4332ec34544SRui Ueyama   expect(")");
4342ec34544SRui Ueyama }
4352ec34544SRui Ueyama 
4362ec34544SRui Ueyama void ScriptParser::readSections() {
437a323e2a7SRui Ueyama   Script->HasSectionsCommand = true;
438b579c439SRui Ueyama 
4392ec34544SRui Ueyama   // -no-rosegment is used to avoid placing read only non-executable sections in
4402ec34544SRui Ueyama   // their own segment. We do the same if SECTIONS command is present in linker
4412ec34544SRui Ueyama   // script. See comment for computeFlags().
4422ec34544SRui Ueyama   Config->SingleRoRx = true;
4432ec34544SRui Ueyama 
4442ec34544SRui Ueyama   expect("{");
445*b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
4462ec34544SRui Ueyama     StringRef Tok = next();
4472ec34544SRui Ueyama     BaseCommand *Cmd = readProvideOrAssignment(Tok);
4482ec34544SRui Ueyama     if (!Cmd) {
4492ec34544SRui Ueyama       if (Tok == "ASSERT")
45023af89ccSRui Ueyama         Cmd = readAssert();
4512ec34544SRui Ueyama       else
4522ec34544SRui Ueyama         Cmd = readOutputSectionDescription(Tok);
4532ec34544SRui Ueyama     }
4546b394caaSRui Ueyama     Script->SectionCommands.push_back(Cmd);
4552ec34544SRui Ueyama   }
4562ec34544SRui Ueyama }
4572ec34544SRui Ueyama 
4582ec34544SRui Ueyama static int precedence(StringRef Op) {
4592ec34544SRui Ueyama   return StringSwitch<int>(Op)
4602ec34544SRui Ueyama       .Cases("*", "/", 5)
4612ec34544SRui Ueyama       .Cases("+", "-", 4)
4622ec34544SRui Ueyama       .Cases("<<", ">>", 3)
4632ec34544SRui Ueyama       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
4642ec34544SRui Ueyama       .Cases("&", "|", 1)
4652ec34544SRui Ueyama       .Default(-1);
4662ec34544SRui Ueyama }
4672ec34544SRui Ueyama 
4682ec34544SRui Ueyama StringMatcher ScriptParser::readFilePatterns() {
4692ec34544SRui Ueyama   std::vector<StringRef> V;
470*b8a59c8aSBob Haarman   while (!errorCount() && !consume(")"))
4712ec34544SRui Ueyama     V.push_back(next());
4722ec34544SRui Ueyama   return StringMatcher(V);
4732ec34544SRui Ueyama }
4742ec34544SRui Ueyama 
4752ec34544SRui Ueyama SortSectionPolicy ScriptParser::readSortKind() {
4762ec34544SRui Ueyama   if (consume("SORT") || consume("SORT_BY_NAME"))
4772ec34544SRui Ueyama     return SortSectionPolicy::Name;
4782ec34544SRui Ueyama   if (consume("SORT_BY_ALIGNMENT"))
4792ec34544SRui Ueyama     return SortSectionPolicy::Alignment;
4802ec34544SRui Ueyama   if (consume("SORT_BY_INIT_PRIORITY"))
4812ec34544SRui Ueyama     return SortSectionPolicy::Priority;
4822ec34544SRui Ueyama   if (consume("SORT_NONE"))
4832ec34544SRui Ueyama     return SortSectionPolicy::None;
4842ec34544SRui Ueyama   return SortSectionPolicy::Default;
4852ec34544SRui Ueyama }
4862ec34544SRui Ueyama 
48703fc8d1eSRui Ueyama // Reads SECTIONS command contents in the following form:
48803fc8d1eSRui Ueyama //
48903fc8d1eSRui Ueyama // <contents> ::= <elem>*
49003fc8d1eSRui Ueyama // <elem>     ::= <exclude>? <glob-pattern>
49103fc8d1eSRui Ueyama // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
49203fc8d1eSRui Ueyama //
49303fc8d1eSRui Ueyama // For example,
49403fc8d1eSRui Ueyama //
49503fc8d1eSRui Ueyama // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
49603fc8d1eSRui Ueyama //
49703fc8d1eSRui Ueyama // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
49803fc8d1eSRui Ueyama // The semantics of that is section .foo in any file, section .bar in
49903fc8d1eSRui Ueyama // any file but a.o, and section .baz in any file but b.o.
5002ec34544SRui Ueyama std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
5012ec34544SRui Ueyama   std::vector<SectionPattern> Ret;
502*b8a59c8aSBob Haarman   while (!errorCount() && peek() != ")") {
5032ec34544SRui Ueyama     StringMatcher ExcludeFilePat;
5042ec34544SRui Ueyama     if (consume("EXCLUDE_FILE")) {
5052ec34544SRui Ueyama       expect("(");
5062ec34544SRui Ueyama       ExcludeFilePat = readFilePatterns();
5072ec34544SRui Ueyama     }
5082ec34544SRui Ueyama 
5092ec34544SRui Ueyama     std::vector<StringRef> V;
510*b8a59c8aSBob Haarman     while (!errorCount() && peek() != ")" && peek() != "EXCLUDE_FILE")
5112ec34544SRui Ueyama       V.push_back(next());
5122ec34544SRui Ueyama 
5132ec34544SRui Ueyama     if (!V.empty())
5142ec34544SRui Ueyama       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
5152ec34544SRui Ueyama     else
5162ec34544SRui Ueyama       setError("section pattern is expected");
5172ec34544SRui Ueyama   }
5182ec34544SRui Ueyama   return Ret;
5192ec34544SRui Ueyama }
5202ec34544SRui Ueyama 
5212ec34544SRui Ueyama // Reads contents of "SECTIONS" directive. That directive contains a
5222ec34544SRui Ueyama // list of glob patterns for input sections. The grammar is as follows.
5232ec34544SRui Ueyama //
5242ec34544SRui Ueyama // <patterns> ::= <section-list>
5252ec34544SRui Ueyama //              | <sort> "(" <section-list> ")"
5262ec34544SRui Ueyama //              | <sort> "(" <sort> "(" <section-list> ")" ")"
5272ec34544SRui Ueyama //
5282ec34544SRui Ueyama // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
5292ec34544SRui Ueyama //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
5302ec34544SRui Ueyama //
5312ec34544SRui Ueyama // <section-list> is parsed by readInputSectionsList().
5322ec34544SRui Ueyama InputSectionDescription *
5332ec34544SRui Ueyama ScriptParser::readInputSectionRules(StringRef FilePattern) {
5342ec34544SRui Ueyama   auto *Cmd = make<InputSectionDescription>(FilePattern);
5352ec34544SRui Ueyama   expect("(");
5362ec34544SRui Ueyama 
537*b8a59c8aSBob Haarman   while (!errorCount() && !consume(")")) {
5382ec34544SRui Ueyama     SortSectionPolicy Outer = readSortKind();
5392ec34544SRui Ueyama     SortSectionPolicy Inner = SortSectionPolicy::Default;
5402ec34544SRui Ueyama     std::vector<SectionPattern> V;
5412ec34544SRui Ueyama     if (Outer != SortSectionPolicy::Default) {
5422ec34544SRui Ueyama       expect("(");
5432ec34544SRui Ueyama       Inner = readSortKind();
5442ec34544SRui Ueyama       if (Inner != SortSectionPolicy::Default) {
5452ec34544SRui Ueyama         expect("(");
5462ec34544SRui Ueyama         V = readInputSectionsList();
5472ec34544SRui Ueyama         expect(")");
5482ec34544SRui Ueyama       } else {
5492ec34544SRui Ueyama         V = readInputSectionsList();
5502ec34544SRui Ueyama       }
5512ec34544SRui Ueyama       expect(")");
5522ec34544SRui Ueyama     } else {
5532ec34544SRui Ueyama       V = readInputSectionsList();
5542ec34544SRui Ueyama     }
5552ec34544SRui Ueyama 
5562ec34544SRui Ueyama     for (SectionPattern &Pat : V) {
5572ec34544SRui Ueyama       Pat.SortInner = Inner;
5582ec34544SRui Ueyama       Pat.SortOuter = Outer;
5592ec34544SRui Ueyama     }
5602ec34544SRui Ueyama 
5612ec34544SRui Ueyama     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
5622ec34544SRui Ueyama   }
5632ec34544SRui Ueyama   return Cmd;
5642ec34544SRui Ueyama }
5652ec34544SRui Ueyama 
5662ec34544SRui Ueyama InputSectionDescription *
5672ec34544SRui Ueyama ScriptParser::readInputSectionDescription(StringRef Tok) {
5682ec34544SRui Ueyama   // Input section wildcard can be surrounded by KEEP.
5692ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
5702ec34544SRui Ueyama   if (Tok == "KEEP") {
5712ec34544SRui Ueyama     expect("(");
5722ec34544SRui Ueyama     StringRef FilePattern = next();
5732ec34544SRui Ueyama     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
5742ec34544SRui Ueyama     expect(")");
575ac27de9dSRui Ueyama     Script->KeptSections.push_back(Cmd);
5762ec34544SRui Ueyama     return Cmd;
5772ec34544SRui Ueyama   }
5782ec34544SRui Ueyama   return readInputSectionRules(Tok);
5792ec34544SRui Ueyama }
5802ec34544SRui Ueyama 
5812ec34544SRui Ueyama void ScriptParser::readSort() {
5822ec34544SRui Ueyama   expect("(");
5832ec34544SRui Ueyama   expect("CONSTRUCTORS");
5842ec34544SRui Ueyama   expect(")");
5852ec34544SRui Ueyama }
5862ec34544SRui Ueyama 
58723af89ccSRui Ueyama AssertCommand *ScriptParser::readAssert() {
58823af89ccSRui Ueyama   return make<AssertCommand>(readAssertExpr());
58923af89ccSRui Ueyama }
59023af89ccSRui Ueyama 
59123af89ccSRui Ueyama Expr ScriptParser::readAssertExpr() {
5922ec34544SRui Ueyama   expect("(");
5932ec34544SRui Ueyama   Expr E = readExpr();
5942ec34544SRui Ueyama   expect(",");
5952ec34544SRui Ueyama   StringRef Msg = unquote(next());
5962ec34544SRui Ueyama   expect(")");
597b579c439SRui Ueyama 
5982ec34544SRui Ueyama   return [=] {
5992ec34544SRui Ueyama     if (!E().getValue())
6002ec34544SRui Ueyama       error(Msg);
6012ec34544SRui Ueyama     return Script->getDot();
6022ec34544SRui Ueyama   };
6032ec34544SRui Ueyama }
6042ec34544SRui Ueyama 
6052ec34544SRui Ueyama // Reads a FILL(expr) command. We handle the FILL command as an
6062ec34544SRui Ueyama // alias for =fillexp section attribute, which is different from
6072ec34544SRui Ueyama // what GNU linkers do.
6082ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
6092ec34544SRui Ueyama uint32_t ScriptParser::readFill() {
6102ec34544SRui Ueyama   expect("(");
6118acbf1ccSRui Ueyama   uint32_t V = parseFill(next());
6122ec34544SRui Ueyama   expect(")");
6132ec34544SRui Ueyama   return V;
6142ec34544SRui Ueyama }
6152ec34544SRui Ueyama 
6163271d370SRui Ueyama // Reads an expression and/or the special directive "(NOLOAD)" for an
6173271d370SRui Ueyama // output section definition.
6183271d370SRui Ueyama //
6193271d370SRui Ueyama // An output section name can be followed by an address expression
6203271d370SRui Ueyama // and/or by "(NOLOAD)". This grammar is not LL(1) because "(" can be
6213271d370SRui Ueyama // interpreted as either the beginning of some expression or "(NOLOAD)".
6223271d370SRui Ueyama //
623b579c439SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
624fbb0463fSGeorge Rimar // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
6258c022ca7SRafael Espindola void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
6263271d370SRui Ueyama   if (consume("(")) {
6273271d370SRui Ueyama     if (consume("NOLOAD")) {
6283271d370SRui Ueyama       expect(")");
6293271d370SRui Ueyama       Cmd->Noload = true;
6303271d370SRui Ueyama       return;
6313271d370SRui Ueyama     }
6323271d370SRui Ueyama     Cmd->AddrExpr = readExpr();
6333271d370SRui Ueyama     expect(")");
6343271d370SRui Ueyama   } else {
6353271d370SRui Ueyama     Cmd->AddrExpr = readExpr();
6363271d370SRui Ueyama   }
6373271d370SRui Ueyama 
638fbb0463fSGeorge Rimar   if (consume("(")) {
639fbb0463fSGeorge Rimar     expect("NOLOAD");
640fbb0463fSGeorge Rimar     expect(")");
641fbb0463fSGeorge Rimar     Cmd->Noload = true;
642fbb0463fSGeorge Rimar   }
643fbb0463fSGeorge Rimar }
644fbb0463fSGeorge Rimar 
645f22ec9ddSGeorge Rimar static Expr checkAlignment(Expr E, std::string &Loc) {
646f22ec9ddSGeorge Rimar   return [=] {
647f22ec9ddSGeorge Rimar     uint64_t Alignment = std::max((uint64_t)1, E().getValue());
648f22ec9ddSGeorge Rimar     if (!isPowerOf2_64(Alignment)) {
649f22ec9ddSGeorge Rimar       error(Loc + ": alignment must be power of 2");
650f22ec9ddSGeorge Rimar       return (uint64_t)1; // Return a dummy value.
651f22ec9ddSGeorge Rimar     }
652f22ec9ddSGeorge Rimar     return Alignment;
653f22ec9ddSGeorge Rimar   };
654f22ec9ddSGeorge Rimar }
655f22ec9ddSGeorge Rimar 
6568c022ca7SRafael Espindola OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
6578c022ca7SRafael Espindola   OutputSection *Cmd =
6588c022ca7SRafael Espindola       Script->createOutputSection(OutSec, getCurrentLocation());
6593271d370SRui Ueyama 
6603271d370SRui Ueyama   if (peek() != ":")
6613271d370SRui Ueyama     readSectionAddressType(Cmd);
6622ec34544SRui Ueyama   expect(":");
6632ec34544SRui Ueyama 
664f22ec9ddSGeorge Rimar   std::string Location = getCurrentLocation();
6652ec34544SRui Ueyama   if (consume("AT"))
6662ec34544SRui Ueyama     Cmd->LMAExpr = readParenExpr();
6672ec34544SRui Ueyama   if (consume("ALIGN"))
668f22ec9ddSGeorge Rimar     Cmd->AlignExpr = checkAlignment(readParenExpr(), Location);
6692ec34544SRui Ueyama   if (consume("SUBALIGN"))
670f22ec9ddSGeorge Rimar     Cmd->SubalignExpr = checkAlignment(readParenExpr(), Location);
6712ec34544SRui Ueyama 
6722ec34544SRui Ueyama   // Parse constraints.
6732ec34544SRui Ueyama   if (consume("ONLY_IF_RO"))
6742ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadOnly;
6752ec34544SRui Ueyama   if (consume("ONLY_IF_RW"))
6762ec34544SRui Ueyama     Cmd->Constraint = ConstraintKind::ReadWrite;
6772ec34544SRui Ueyama   expect("{");
6782ec34544SRui Ueyama 
679*b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
6802ec34544SRui Ueyama     StringRef Tok = next();
6812ec34544SRui Ueyama     if (Tok == ";") {
6822ec34544SRui Ueyama       // Empty commands are allowed. Do nothing here.
683b579c439SRui Ueyama     } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) {
6846b394caaSRui Ueyama       Cmd->SectionCommands.push_back(Assign);
685f0403c60SRui Ueyama     } else if (ByteCommand *Data = readByteCommand(Tok)) {
6866b394caaSRui Ueyama       Cmd->SectionCommands.push_back(Data);
6872ec34544SRui Ueyama     } else if (Tok == "ASSERT") {
6886b394caaSRui Ueyama       Cmd->SectionCommands.push_back(readAssert());
6892ec34544SRui Ueyama       expect(";");
6902ec34544SRui Ueyama     } else if (Tok == "CONSTRUCTORS") {
6912ec34544SRui Ueyama       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
6922ec34544SRui Ueyama       // by name. This is for very old file formats such as ECOFF/XCOFF.
6932ec34544SRui Ueyama       // For ELF, we should ignore.
6942ec34544SRui Ueyama     } else if (Tok == "FILL") {
6952ec34544SRui Ueyama       Cmd->Filler = readFill();
6962ec34544SRui Ueyama     } else if (Tok == "SORT") {
6972ec34544SRui Ueyama       readSort();
6982ec34544SRui Ueyama     } else if (peek() == "(") {
6996b394caaSRui Ueyama       Cmd->SectionCommands.push_back(readInputSectionDescription(Tok));
7002ec34544SRui Ueyama     } else {
7012ec34544SRui Ueyama       setError("unknown command " + Tok);
7022ec34544SRui Ueyama     }
7032ec34544SRui Ueyama   }
7042ec34544SRui Ueyama 
7052ec34544SRui Ueyama   if (consume(">"))
7062ec34544SRui Ueyama     Cmd->MemoryRegionName = next();
707b0e62297SMeador Inge   else if (peek().startswith(">"))
708b0e62297SMeador Inge     Cmd->MemoryRegionName = next().drop_front();
7092ec34544SRui Ueyama 
7102ec34544SRui Ueyama   Cmd->Phdrs = readOutputSectionPhdrs();
7112ec34544SRui Ueyama 
7122ec34544SRui Ueyama   if (consume("="))
7138acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next());
7142ec34544SRui Ueyama   else if (peek().startswith("="))
7158acbf1ccSRui Ueyama     Cmd->Filler = parseFill(next().drop_front());
7162ec34544SRui Ueyama 
7172ec34544SRui Ueyama   // Consume optional comma following output section command.
7182ec34544SRui Ueyama   consume(",");
7192ec34544SRui Ueyama 
7202ec34544SRui Ueyama   return Cmd;
7212ec34544SRui Ueyama }
7222ec34544SRui Ueyama 
7238acbf1ccSRui Ueyama // Parses a given string as a octal/decimal/hexadecimal number and
7248acbf1ccSRui Ueyama // returns it as a big-endian number. Used for `=<fillexp>`.
7252ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
7262ec34544SRui Ueyama //
7278acbf1ccSRui Ueyama // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
7288acbf1ccSRui Ueyama // size, while ld.gold always handles it as a 32-bit big-endian number.
7298acbf1ccSRui Ueyama // We are compatible with ld.gold because it's easier to implement.
7308acbf1ccSRui Ueyama uint32_t ScriptParser::parseFill(StringRef Tok) {
731b58079d4SRui Ueyama   uint32_t V = 0;
732ab94768cSGeorge Rimar   if (!to_integer(Tok, V))
7332ec34544SRui Ueyama     setError("invalid filler expression: " + Tok);
734b58079d4SRui Ueyama 
735b58079d4SRui Ueyama   uint32_t Buf;
736b58079d4SRui Ueyama   write32be(&Buf, V);
737b58079d4SRui Ueyama   return Buf;
7382ec34544SRui Ueyama }
7392ec34544SRui Ueyama 
7402ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
7412ec34544SRui Ueyama   expect("(");
7422ec34544SRui Ueyama   SymbolAssignment *Cmd = readAssignment(next());
7432ec34544SRui Ueyama   Cmd->Provide = Provide;
7442ec34544SRui Ueyama   Cmd->Hidden = Hidden;
7452ec34544SRui Ueyama   expect(")");
7462ec34544SRui Ueyama   expect(";");
7472ec34544SRui Ueyama   return Cmd;
7482ec34544SRui Ueyama }
7492ec34544SRui Ueyama 
7502ec34544SRui Ueyama SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
7512ec34544SRui Ueyama   SymbolAssignment *Cmd = nullptr;
7522ec34544SRui Ueyama   if (peek() == "=" || peek() == "+=") {
7532ec34544SRui Ueyama     Cmd = readAssignment(Tok);
7542ec34544SRui Ueyama     expect(";");
7552ec34544SRui Ueyama   } else if (Tok == "PROVIDE") {
7562ec34544SRui Ueyama     Cmd = readProvideHidden(true, false);
7572ec34544SRui Ueyama   } else if (Tok == "HIDDEN") {
7582ec34544SRui Ueyama     Cmd = readProvideHidden(false, true);
7592ec34544SRui Ueyama   } else if (Tok == "PROVIDE_HIDDEN") {
7602ec34544SRui Ueyama     Cmd = readProvideHidden(true, true);
7612ec34544SRui Ueyama   }
7622ec34544SRui Ueyama   return Cmd;
7632ec34544SRui Ueyama }
7642ec34544SRui Ueyama 
7652ec34544SRui Ueyama SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
7662ec34544SRui Ueyama   StringRef Op = next();
7672ec34544SRui Ueyama   assert(Op == "=" || Op == "+=");
7682ec34544SRui Ueyama   Expr E = readExpr();
7692ec34544SRui Ueyama   if (Op == "+=") {
7702ec34544SRui Ueyama     std::string Loc = getCurrentLocation();
771722221f5SRui Ueyama     E = [=] { return add(Script->getSymbolValue(Name, Loc), E()); };
7722ec34544SRui Ueyama   }
7732ec34544SRui Ueyama   return make<SymbolAssignment>(Name, E, getCurrentLocation());
7742ec34544SRui Ueyama }
7752ec34544SRui Ueyama 
7762ec34544SRui Ueyama // This is an operator-precedence parser to parse a linker
7772ec34544SRui Ueyama // script expression.
7782ec34544SRui Ueyama Expr ScriptParser::readExpr() {
7792ec34544SRui Ueyama   // Our lexer is context-aware. Set the in-expression bit so that
7802ec34544SRui Ueyama   // they apply different tokenization rules.
7812ec34544SRui Ueyama   bool Orig = InExpr;
7822ec34544SRui Ueyama   InExpr = true;
7832ec34544SRui Ueyama   Expr E = readExpr1(readPrimary(), 0);
7842ec34544SRui Ueyama   InExpr = Orig;
7852ec34544SRui Ueyama   return E;
7862ec34544SRui Ueyama }
7872ec34544SRui Ueyama 
7882ec34544SRui Ueyama static Expr combine(StringRef Op, Expr L, Expr R) {
7892ec34544SRui Ueyama   if (Op == "+")
7902ec34544SRui Ueyama     return [=] { return add(L(), R()); };
7912ec34544SRui Ueyama   if (Op == "-")
7922ec34544SRui Ueyama     return [=] { return sub(L(), R()); };
793b579c439SRui Ueyama   if (Op == "*")
794b579c439SRui Ueyama     return [=] { return mul(L(), R()); };
795b579c439SRui Ueyama   if (Op == "/")
796b579c439SRui Ueyama     return [=] { return div(L(), R()); };
7972ec34544SRui Ueyama   if (Op == "<<")
7987e915511SRui Ueyama     return [=] { return L().getValue() << R().getValue(); };
7992ec34544SRui Ueyama   if (Op == ">>")
8007e915511SRui 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 L().getValue() > R().getValue(); };
8052ec34544SRui Ueyama   if (Op == ">=")
8062ec34544SRui Ueyama     return [=] { return L().getValue() >= R().getValue(); };
8072ec34544SRui Ueyama   if (Op == "<=")
8082ec34544SRui Ueyama     return [=] { return L().getValue() <= R().getValue(); };
8092ec34544SRui Ueyama   if (Op == "==")
8102ec34544SRui Ueyama     return [=] { return L().getValue() == R().getValue(); };
8112ec34544SRui Ueyama   if (Op == "!=")
8122ec34544SRui Ueyama     return [=] { return L().getValue() != R().getValue(); };
8132ec34544SRui Ueyama   if (Op == "&")
8142ec34544SRui Ueyama     return [=] { return bitAnd(L(), R()); };
8152ec34544SRui Ueyama   if (Op == "|")
8162ec34544SRui Ueyama     return [=] { return bitOr(L(), R()); };
8172ec34544SRui Ueyama   llvm_unreachable("invalid operator");
8182ec34544SRui Ueyama }
8192ec34544SRui Ueyama 
8202ec34544SRui Ueyama // This is a part of the operator-precedence parser. This function
8212ec34544SRui Ueyama // assumes that the remaining token stream starts with an operator.
8222ec34544SRui Ueyama Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
823*b8a59c8aSBob Haarman   while (!atEOF() && !errorCount()) {
8242ec34544SRui Ueyama     // Read an operator and an expression.
8252ec34544SRui Ueyama     if (consume("?"))
8262ec34544SRui Ueyama       return readTernary(Lhs);
8272ec34544SRui Ueyama     StringRef Op1 = peek();
8282ec34544SRui Ueyama     if (precedence(Op1) < MinPrec)
8292ec34544SRui Ueyama       break;
8302ec34544SRui Ueyama     skip();
8312ec34544SRui Ueyama     Expr Rhs = readPrimary();
8322ec34544SRui Ueyama 
8332ec34544SRui Ueyama     // Evaluate the remaining part of the expression first if the
8342ec34544SRui Ueyama     // next operator has greater precedence than the previous one.
8352ec34544SRui Ueyama     // For example, if we have read "+" and "3", and if the next
8362ec34544SRui Ueyama     // operator is "*", then we'll evaluate 3 * ... part first.
8372ec34544SRui Ueyama     while (!atEOF()) {
8382ec34544SRui Ueyama       StringRef Op2 = peek();
8392ec34544SRui Ueyama       if (precedence(Op2) <= precedence(Op1))
8402ec34544SRui Ueyama         break;
8412ec34544SRui Ueyama       Rhs = readExpr1(Rhs, precedence(Op2));
8422ec34544SRui Ueyama     }
8432ec34544SRui Ueyama 
8442ec34544SRui Ueyama     Lhs = combine(Op1, Lhs, Rhs);
8452ec34544SRui Ueyama   }
8462ec34544SRui Ueyama   return Lhs;
8472ec34544SRui Ueyama }
8482ec34544SRui Ueyama 
8495fb17128SGeorge Rimar Expr ScriptParser::getPageSize() {
8505fb17128SGeorge Rimar   std::string Location = getCurrentLocation();
8515fb17128SGeorge Rimar   return [=]() -> uint64_t {
8525fb17128SGeorge Rimar     if (Target)
8532ec34544SRui Ueyama       return Target->PageSize;
8545fb17128SGeorge Rimar     error(Location + ": unable to calculate page size");
8555fb17128SGeorge Rimar     return 4096; // Return a dummy value.
8565fb17128SGeorge Rimar   };
8575fb17128SGeorge Rimar }
8585fb17128SGeorge Rimar 
8595fb17128SGeorge Rimar Expr ScriptParser::readConstant() {
8605fb17128SGeorge Rimar   StringRef S = readParenLiteral();
8615fb17128SGeorge Rimar   if (S == "COMMONPAGESIZE")
8625fb17128SGeorge Rimar     return getPageSize();
8632ec34544SRui Ueyama   if (S == "MAXPAGESIZE")
8645fb17128SGeorge Rimar     return [] { return Config->MaxPageSize; };
8655fb17128SGeorge Rimar   setError("unknown constant: " + S);
8665fb17128SGeorge Rimar   return {};
8672ec34544SRui Ueyama }
8682ec34544SRui Ueyama 
8695c65088fSRui Ueyama // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
8705c65088fSRui Ueyama // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
8715c65088fSRui Ueyama // have "K" (Ki) or "M" (Mi) suffixes.
8725c65088fSRui Ueyama static Optional<uint64_t> parseInt(StringRef Tok) {
8732ec34544SRui Ueyama   // Negative number
8742ec34544SRui Ueyama   if (Tok.startswith("-")) {
8755c65088fSRui Ueyama     if (Optional<uint64_t> Val = parseInt(Tok.substr(1)))
8765c65088fSRui Ueyama       return -*Val;
8775c65088fSRui Ueyama     return None;
8782ec34544SRui Ueyama   }
8792ec34544SRui Ueyama 
8802ec34544SRui Ueyama   // Hexadecimal
8815c65088fSRui Ueyama   uint64_t Val;
8824092016bSRui Ueyama   if (Tok.startswith_lower("0x")) {
8834092016bSRui Ueyama     if (!to_integer(Tok.substr(2), Val, 16))
8844092016bSRui Ueyama       return None;
8855c65088fSRui Ueyama     return Val;
8864092016bSRui Ueyama   }
8874092016bSRui Ueyama   if (Tok.endswith_lower("H")) {
8884092016bSRui Ueyama     if (!to_integer(Tok.drop_back(), Val, 16))
8894092016bSRui Ueyama       return None;
8905c65088fSRui Ueyama     return Val;
8914092016bSRui Ueyama   }
8922ec34544SRui Ueyama 
8932ec34544SRui Ueyama   // Decimal
8942ec34544SRui Ueyama   if (Tok.endswith_lower("K")) {
895ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
8965c65088fSRui Ueyama       return None;
8975c65088fSRui Ueyama     return Val * 1024;
8982ec34544SRui Ueyama   }
8995c65088fSRui Ueyama   if (Tok.endswith_lower("M")) {
900ab94768cSGeorge Rimar     if (!to_integer(Tok.drop_back(), Val, 10))
9015c65088fSRui Ueyama       return None;
9025c65088fSRui Ueyama     return Val * 1024 * 1024;
9035c65088fSRui Ueyama   }
904ab94768cSGeorge Rimar   if (!to_integer(Tok, Val, 10))
9055c65088fSRui Ueyama     return None;
9065c65088fSRui Ueyama   return Val;
9072ec34544SRui Ueyama }
9082ec34544SRui Ueyama 
909f0403c60SRui Ueyama ByteCommand *ScriptParser::readByteCommand(StringRef Tok) {
910b579c439SRui Ueyama   int Size = StringSwitch<int>(Tok)
9112ec34544SRui Ueyama                  .Case("BYTE", 1)
9122ec34544SRui Ueyama                  .Case("SHORT", 2)
9132ec34544SRui Ueyama                  .Case("LONG", 4)
9142ec34544SRui Ueyama                  .Case("QUAD", 8)
9152ec34544SRui Ueyama                  .Default(-1);
9162ec34544SRui Ueyama   if (Size == -1)
9172ec34544SRui Ueyama     return nullptr;
918f0403c60SRui Ueyama   return make<ByteCommand>(readParenExpr(), Size);
9192ec34544SRui Ueyama }
9202ec34544SRui Ueyama 
9212ec34544SRui Ueyama StringRef ScriptParser::readParenLiteral() {
9222ec34544SRui Ueyama   expect("(");
9232ec34544SRui Ueyama   StringRef Tok = next();
9242ec34544SRui Ueyama   expect(")");
9252ec34544SRui Ueyama   return Tok;
9262ec34544SRui Ueyama }
9272ec34544SRui Ueyama 
928617e2f98SRui Ueyama static void checkIfExists(OutputSection *Cmd, StringRef Location) {
92905c4f67cSRafael Espindola   if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
93005c4f67cSRafael Espindola     error(Location + ": undefined section " + Cmd->Name);
93105c4f67cSRafael Espindola }
93205c4f67cSRafael Espindola 
9332ec34544SRui Ueyama Expr ScriptParser::readPrimary() {
9342ec34544SRui Ueyama   if (peek() == "(")
9352ec34544SRui Ueyama     return readParenExpr();
9362ec34544SRui Ueyama 
9375c65088fSRui Ueyama   if (consume("~")) {
9382ec34544SRui Ueyama     Expr E = readPrimary();
939b2fb84a1SRui Ueyama     return [=] { return ~E().getValue(); };
9402ec34544SRui Ueyama   }
9416f1d954eSHafiz Abid Qadeer   if (consume("!")) {
9426f1d954eSHafiz Abid Qadeer     Expr E = readPrimary();
9436f1d954eSHafiz Abid Qadeer     return [=] { return !E().getValue(); };
9446f1d954eSHafiz Abid Qadeer   }
9455c65088fSRui Ueyama   if (consume("-")) {
9462ec34544SRui Ueyama     Expr E = readPrimary();
947b2fb84a1SRui Ueyama     return [=] { return -E().getValue(); };
9482ec34544SRui Ueyama   }
9492ec34544SRui Ueyama 
9505c65088fSRui Ueyama   StringRef Tok = next();
9515c65088fSRui Ueyama   std::string Location = getCurrentLocation();
9525c65088fSRui Ueyama 
9532ec34544SRui Ueyama   // Built-in functions are parsed here.
9542ec34544SRui Ueyama   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
9552ec34544SRui Ueyama   if (Tok == "ABSOLUTE") {
9562ec34544SRui Ueyama     Expr Inner = readParenExpr();
9572ec34544SRui Ueyama     return [=] {
9582ec34544SRui Ueyama       ExprValue I = Inner();
9592ec34544SRui Ueyama       I.ForceAbsolute = true;
9602ec34544SRui Ueyama       return I;
9612ec34544SRui Ueyama     };
9622ec34544SRui Ueyama   }
9632ec34544SRui Ueyama   if (Tok == "ADDR") {
9642ec34544SRui Ueyama     StringRef Name = readParenLiteral();
9654fbe3518SRui Ueyama     OutputSection *Sec = Script->getOrCreateOutputSection(Name);
96641c7ab4aSGeorge Rimar     return [=]() -> ExprValue {
9674fbe3518SRui Ueyama       checkIfExists(Sec, Location);
9684fbe3518SRui Ueyama       return {Sec, false, 0, Location};
96941c7ab4aSGeorge Rimar     };
9702ec34544SRui Ueyama   }
9712ec34544SRui Ueyama   if (Tok == "ALIGN") {
9722ec34544SRui Ueyama     expect("(");
9732ec34544SRui Ueyama     Expr E = readExpr();
974f22ec9ddSGeorge Rimar     if (consume(")")) {
975f22ec9ddSGeorge Rimar       E = checkAlignment(E, Location);
976f22ec9ddSGeorge Rimar       return [=] { return alignTo(Script->getDot(), E().getValue()); };
977f22ec9ddSGeorge Rimar     }
978b579c439SRui Ueyama     expect(",");
979f22ec9ddSGeorge Rimar     Expr E2 = checkAlignment(readExpr(), Location);
9802ec34544SRui Ueyama     expect(")");
9813c6de1a6SPetr Hosek     return [=] {
9823c6de1a6SPetr Hosek       ExprValue V = E();
983f22ec9ddSGeorge Rimar       V.Alignment = E2().getValue();
9843c6de1a6SPetr Hosek       return V;
9853c6de1a6SPetr Hosek     };
9862ec34544SRui Ueyama   }
9872ec34544SRui Ueyama   if (Tok == "ALIGNOF") {
9882ec34544SRui Ueyama     StringRef Name = readParenLiteral();
9898c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
990617e2f98SRui Ueyama     return [=] {
991617e2f98SRui Ueyama       checkIfExists(Cmd, Location);
992617e2f98SRui Ueyama       return Cmd->Alignment;
993617e2f98SRui Ueyama     };
9942ec34544SRui Ueyama   }
9952ec34544SRui Ueyama   if (Tok == "ASSERT")
99623af89ccSRui Ueyama     return readAssertExpr();
9975fb17128SGeorge Rimar   if (Tok == "CONSTANT")
9985fb17128SGeorge Rimar     return readConstant();
9992ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_ALIGN") {
10002ec34544SRui Ueyama     expect("(");
10012ec34544SRui Ueyama     Expr E = readExpr();
10022ec34544SRui Ueyama     expect(",");
10032ec34544SRui Ueyama     readExpr();
10042ec34544SRui Ueyama     expect(")");
100560833f6eSGeorge Rimar     return [=] {
100660833f6eSGeorge Rimar       return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
100760833f6eSGeorge Rimar     };
10082ec34544SRui Ueyama   }
10092ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_END") {
10102ec34544SRui Ueyama     expect("(");
10112ec34544SRui Ueyama     expect(".");
10122ec34544SRui Ueyama     expect(")");
10132ec34544SRui Ueyama     return [] { return Script->getDot(); };
10142ec34544SRui Ueyama   }
10152ec34544SRui Ueyama   if (Tok == "DATA_SEGMENT_RELRO_END") {
10162ec34544SRui Ueyama     // GNU linkers implements more complicated logic to handle
10172ec34544SRui Ueyama     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
10182ec34544SRui Ueyama     // just align to the next page boundary for simplicity.
10192ec34544SRui Ueyama     expect("(");
10202ec34544SRui Ueyama     readExpr();
10212ec34544SRui Ueyama     expect(",");
10222ec34544SRui Ueyama     readExpr();
10232ec34544SRui Ueyama     expect(")");
10245fb17128SGeorge Rimar     Expr E = getPageSize();
10255fb17128SGeorge Rimar     return [=] { return alignTo(Script->getDot(), E().getValue()); };
10262ec34544SRui Ueyama   }
10272ec34544SRui Ueyama   if (Tok == "DEFINED") {
10282ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10299b18f50fSRui Ueyama     return [=] { return Symtab->find(Name) ? 1 : 0; };
10302ec34544SRui Ueyama   }
103191b95b61SRui Ueyama   if (Tok == "LENGTH") {
103291b95b61SRui Ueyama     StringRef Name = readParenLiteral();
1033ac27de9dSRui Ueyama     if (Script->MemoryRegions.count(Name) == 0)
103491b95b61SRui Ueyama       setError("memory region not defined: " + Name);
1035ac27de9dSRui Ueyama     return [=] { return Script->MemoryRegions[Name]->Length; };
103691b95b61SRui Ueyama   }
10372ec34544SRui Ueyama   if (Tok == "LOADADDR") {
10382ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10398c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1040617e2f98SRui Ueyama     return [=] {
1041617e2f98SRui Ueyama       checkIfExists(Cmd, Location);
1042617e2f98SRui Ueyama       return Cmd->getLMA();
1043617e2f98SRui Ueyama     };
10442ec34544SRui Ueyama   }
104591b95b61SRui Ueyama   if (Tok == "ORIGIN") {
104691b95b61SRui Ueyama     StringRef Name = readParenLiteral();
1047ac27de9dSRui Ueyama     if (Script->MemoryRegions.count(Name) == 0)
104891b95b61SRui Ueyama       setError("memory region not defined: " + Name);
1049ac27de9dSRui Ueyama     return [=] { return Script->MemoryRegions[Name]->Origin; };
105091b95b61SRui Ueyama   }
10512ec34544SRui Ueyama   if (Tok == "SEGMENT_START") {
10522ec34544SRui Ueyama     expect("(");
10532ec34544SRui Ueyama     skip();
10542ec34544SRui Ueyama     expect(",");
10552ec34544SRui Ueyama     Expr E = readExpr();
10562ec34544SRui Ueyama     expect(")");
10572ec34544SRui Ueyama     return [=] { return E(); };
10582ec34544SRui Ueyama   }
10592ec34544SRui Ueyama   if (Tok == "SIZEOF") {
10602ec34544SRui Ueyama     StringRef Name = readParenLiteral();
10618c022ca7SRafael Espindola     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
106205c4f67cSRafael Espindola     // Linker script does not create an output section if its content is empty.
106305c4f67cSRafael Espindola     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
106405c4f67cSRafael Espindola     // be empty.
10658c022ca7SRafael Espindola     return [=] { return Cmd->Size; };
10662ec34544SRui Ueyama   }
10672ec34544SRui Ueyama   if (Tok == "SIZEOF_HEADERS")
10682ec34544SRui Ueyama     return [=] { return elf::getHeaderSize(); };
10692ec34544SRui Ueyama 
10704eb2eccbSRui Ueyama   // Tok is the dot.
10714eb2eccbSRui Ueyama   if (Tok == ".")
1072722221f5SRui Ueyama     return [=] { return Script->getSymbolValue(Tok, Location); };
10734eb2eccbSRui Ueyama 
10742ec34544SRui Ueyama   // Tok is a literal number.
10755c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
10765c65088fSRui Ueyama     return [=] { return *Val; };
10772ec34544SRui Ueyama 
10782ec34544SRui Ueyama   // Tok is a symbol name.
10792ec34544SRui Ueyama   if (!isValidCIdentifier(Tok))
10802ec34544SRui Ueyama     setError("malformed number: " + Tok);
1081ac27de9dSRui Ueyama   Script->ReferencedSymbols.push_back(Tok);
1082722221f5SRui Ueyama   return [=] { return Script->getSymbolValue(Tok, Location); };
10832ec34544SRui Ueyama }
10842ec34544SRui Ueyama 
10852ec34544SRui Ueyama Expr ScriptParser::readTernary(Expr Cond) {
10862ec34544SRui Ueyama   Expr L = readExpr();
10872ec34544SRui Ueyama   expect(":");
10882ec34544SRui Ueyama   Expr R = readExpr();
10892ec34544SRui Ueyama   return [=] { return Cond().getValue() ? L() : R(); };
10902ec34544SRui Ueyama }
10912ec34544SRui Ueyama 
10922ec34544SRui Ueyama Expr ScriptParser::readParenExpr() {
10932ec34544SRui Ueyama   expect("(");
10942ec34544SRui Ueyama   Expr E = readExpr();
10952ec34544SRui Ueyama   expect(")");
10962ec34544SRui Ueyama   return E;
10972ec34544SRui Ueyama }
10982ec34544SRui Ueyama 
10992ec34544SRui Ueyama std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
11002ec34544SRui Ueyama   std::vector<StringRef> Phdrs;
1101*b8a59c8aSBob Haarman   while (!errorCount() && peek().startswith(":")) {
11022ec34544SRui Ueyama     StringRef Tok = next();
11032ec34544SRui Ueyama     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
11042ec34544SRui Ueyama   }
11052ec34544SRui Ueyama   return Phdrs;
11062ec34544SRui Ueyama }
11072ec34544SRui Ueyama 
11082ec34544SRui Ueyama // Read a program header type name. The next token must be a
11092ec34544SRui Ueyama // name of a program header type or a constant (e.g. "0x3").
11102ec34544SRui Ueyama unsigned ScriptParser::readPhdrType() {
11112ec34544SRui Ueyama   StringRef Tok = next();
11125c65088fSRui Ueyama   if (Optional<uint64_t> Val = parseInt(Tok))
11135c65088fSRui Ueyama     return *Val;
11142ec34544SRui Ueyama 
11152ec34544SRui Ueyama   unsigned Ret = StringSwitch<unsigned>(Tok)
11162ec34544SRui Ueyama                      .Case("PT_NULL", PT_NULL)
11172ec34544SRui Ueyama                      .Case("PT_LOAD", PT_LOAD)
11182ec34544SRui Ueyama                      .Case("PT_DYNAMIC", PT_DYNAMIC)
11192ec34544SRui Ueyama                      .Case("PT_INTERP", PT_INTERP)
11202ec34544SRui Ueyama                      .Case("PT_NOTE", PT_NOTE)
11212ec34544SRui Ueyama                      .Case("PT_SHLIB", PT_SHLIB)
11222ec34544SRui Ueyama                      .Case("PT_PHDR", PT_PHDR)
11232ec34544SRui Ueyama                      .Case("PT_TLS", PT_TLS)
11242ec34544SRui Ueyama                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
11252ec34544SRui Ueyama                      .Case("PT_GNU_STACK", PT_GNU_STACK)
11262ec34544SRui Ueyama                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
11272ec34544SRui Ueyama                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
11282ec34544SRui Ueyama                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
11292ec34544SRui Ueyama                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
11302ec34544SRui Ueyama                      .Default(-1);
11312ec34544SRui Ueyama 
11322ec34544SRui Ueyama   if (Ret == (unsigned)-1) {
11332ec34544SRui Ueyama     setError("invalid program header type: " + Tok);
11342ec34544SRui Ueyama     return PT_NULL;
11352ec34544SRui Ueyama   }
11362ec34544SRui Ueyama   return Ret;
11372ec34544SRui Ueyama }
11382ec34544SRui Ueyama 
11392ec34544SRui Ueyama // Reads an anonymous version declaration.
11402ec34544SRui Ueyama void ScriptParser::readAnonymousDeclaration() {
11412ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
11422ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
11432ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
11442ec34544SRui Ueyama 
11452ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
11462ec34544SRui Ueyama     if (V.Name == "*")
11472ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
11482ec34544SRui Ueyama     else
11492ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
11502ec34544SRui Ueyama   }
11512ec34544SRui Ueyama 
11522ec34544SRui Ueyama   for (SymbolVersion V : Globals)
11532ec34544SRui Ueyama     Config->VersionScriptGlobals.push_back(V);
11542ec34544SRui Ueyama 
11552ec34544SRui Ueyama   expect(";");
11562ec34544SRui Ueyama }
11572ec34544SRui Ueyama 
11582ec34544SRui Ueyama // Reads a non-anonymous version definition,
11592ec34544SRui Ueyama // e.g. "VerStr { global: foo; bar; local: *; };".
11602ec34544SRui Ueyama void ScriptParser::readVersionDeclaration(StringRef VerStr) {
11612ec34544SRui Ueyama   // Read a symbol list.
11622ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
11632ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
11642ec34544SRui Ueyama   std::tie(Locals, Globals) = readSymbols();
11652ec34544SRui Ueyama 
11662ec34544SRui Ueyama   for (SymbolVersion V : Locals) {
11672ec34544SRui Ueyama     if (V.Name == "*")
11682ec34544SRui Ueyama       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
11692ec34544SRui Ueyama     else
11702ec34544SRui Ueyama       Config->VersionScriptLocals.push_back(V);
11712ec34544SRui Ueyama   }
11722ec34544SRui Ueyama 
11732ec34544SRui Ueyama   // Create a new version definition and add that to the global symbols.
11742ec34544SRui Ueyama   VersionDefinition Ver;
11752ec34544SRui Ueyama   Ver.Name = VerStr;
11762ec34544SRui Ueyama   Ver.Globals = Globals;
11772ec34544SRui Ueyama 
11782ec34544SRui Ueyama   // User-defined version number starts from 2 because 0 and 1 are
11792ec34544SRui Ueyama   // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
11802ec34544SRui Ueyama   Ver.Id = Config->VersionDefinitions.size() + 2;
11812ec34544SRui Ueyama   Config->VersionDefinitions.push_back(Ver);
11822ec34544SRui Ueyama 
11832ec34544SRui Ueyama   // Each version may have a parent version. For example, "Ver2"
11842ec34544SRui Ueyama   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
11852ec34544SRui Ueyama   // as a parent. This version hierarchy is, probably against your
11862ec34544SRui Ueyama   // instinct, purely for hint; the runtime doesn't care about it
11872ec34544SRui Ueyama   // at all. In LLD, we simply ignore it.
11882ec34544SRui Ueyama   if (peek() != ";")
11892ec34544SRui Ueyama     skip();
11902ec34544SRui Ueyama   expect(";");
11912ec34544SRui Ueyama }
11922ec34544SRui Ueyama 
11931e77ad14SRui Ueyama static bool hasWildcard(StringRef S) {
11941e77ad14SRui Ueyama   return S.find_first_of("?*[") != StringRef::npos;
11951e77ad14SRui Ueyama }
11961e77ad14SRui Ueyama 
11972ec34544SRui Ueyama // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
11982ec34544SRui Ueyama std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
11992ec34544SRui Ueyama ScriptParser::readSymbols() {
12002ec34544SRui Ueyama   std::vector<SymbolVersion> Locals;
12012ec34544SRui Ueyama   std::vector<SymbolVersion> Globals;
12022ec34544SRui Ueyama   std::vector<SymbolVersion> *V = &Globals;
12032ec34544SRui Ueyama 
1204*b8a59c8aSBob Haarman   while (!errorCount()) {
12052ec34544SRui Ueyama     if (consume("}"))
12062ec34544SRui Ueyama       break;
12072ec34544SRui Ueyama     if (consumeLabel("local")) {
12082ec34544SRui Ueyama       V = &Locals;
12092ec34544SRui Ueyama       continue;
12102ec34544SRui Ueyama     }
12112ec34544SRui Ueyama     if (consumeLabel("global")) {
12122ec34544SRui Ueyama       V = &Globals;
12132ec34544SRui Ueyama       continue;
12142ec34544SRui Ueyama     }
12152ec34544SRui Ueyama 
12162ec34544SRui Ueyama     if (consume("extern")) {
12172ec34544SRui Ueyama       std::vector<SymbolVersion> Ext = readVersionExtern();
12182ec34544SRui Ueyama       V->insert(V->end(), Ext.begin(), Ext.end());
12192ec34544SRui Ueyama     } else {
12202ec34544SRui Ueyama       StringRef Tok = next();
12212ec34544SRui Ueyama       V->push_back({unquote(Tok), false, hasWildcard(Tok)});
12222ec34544SRui Ueyama     }
12232ec34544SRui Ueyama     expect(";");
12242ec34544SRui Ueyama   }
12252ec34544SRui Ueyama   return {Locals, Globals};
12262ec34544SRui Ueyama }
12272ec34544SRui Ueyama 
12282ec34544SRui Ueyama // Reads an "extern C++" directive, e.g.,
12292ec34544SRui Ueyama // "extern "C++" { ns::*; "f(int, double)"; };"
12302ec34544SRui Ueyama std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
12312ec34544SRui Ueyama   StringRef Tok = next();
12322ec34544SRui Ueyama   bool IsCXX = Tok == "\"C++\"";
12332ec34544SRui Ueyama   if (!IsCXX && Tok != "\"C\"")
12342ec34544SRui Ueyama     setError("Unknown language");
12352ec34544SRui Ueyama   expect("{");
12362ec34544SRui Ueyama 
12372ec34544SRui Ueyama   std::vector<SymbolVersion> Ret;
1238*b8a59c8aSBob Haarman   while (!errorCount() && peek() != "}") {
12392ec34544SRui Ueyama     StringRef Tok = next();
12402ec34544SRui Ueyama     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
12412ec34544SRui Ueyama     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
12422ec34544SRui Ueyama     expect(";");
12432ec34544SRui Ueyama   }
12442ec34544SRui Ueyama 
12452ec34544SRui Ueyama   expect("}");
12462ec34544SRui Ueyama   return Ret;
12472ec34544SRui Ueyama }
12482ec34544SRui Ueyama 
12492ec34544SRui Ueyama uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
12502ec34544SRui Ueyama                                             StringRef S3) {
1251b579c439SRui Ueyama   if (!consume(S1) && !consume(S2) && !consume(S3)) {
12522ec34544SRui Ueyama     setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
12532ec34544SRui Ueyama     return 0;
12542ec34544SRui Ueyama   }
12552ec34544SRui Ueyama   expect("=");
1256040af7deSRui Ueyama   return readExpr()().getValue();
12572ec34544SRui Ueyama }
12582ec34544SRui Ueyama 
12592ec34544SRui Ueyama // Parse the MEMORY command as specified in:
12602ec34544SRui Ueyama // https://sourceware.org/binutils/docs/ld/MEMORY.html
12612ec34544SRui Ueyama //
12622ec34544SRui Ueyama // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
12632ec34544SRui Ueyama void ScriptParser::readMemory() {
12642ec34544SRui Ueyama   expect("{");
1265*b8a59c8aSBob Haarman   while (!errorCount() && !consume("}")) {
12662ec34544SRui Ueyama     StringRef Name = next();
12672ec34544SRui Ueyama 
12682ec34544SRui Ueyama     uint32_t Flags = 0;
12692ec34544SRui Ueyama     uint32_t NegFlags = 0;
12702ec34544SRui Ueyama     if (consume("(")) {
12712ec34544SRui Ueyama       std::tie(Flags, NegFlags) = readMemoryAttributes();
12722ec34544SRui Ueyama       expect(")");
12732ec34544SRui Ueyama     }
12742ec34544SRui Ueyama     expect(":");
12752ec34544SRui Ueyama 
12762ec34544SRui Ueyama     uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
12772ec34544SRui Ueyama     expect(",");
12782ec34544SRui Ueyama     uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
12792ec34544SRui Ueyama 
12805f37541cSGeorge Rimar     // Add the memory region to the region map.
1281ac27de9dSRui Ueyama     if (Script->MemoryRegions.count(Name))
12822ec34544SRui Ueyama       setError("region '" + Name + "' already defined");
12835f37541cSGeorge Rimar     MemoryRegion *MR = make<MemoryRegion>();
12845f37541cSGeorge Rimar     *MR = {Name, Origin, Length, Flags, NegFlags};
1285ac27de9dSRui Ueyama     Script->MemoryRegions[Name] = MR;
12862ec34544SRui Ueyama   }
12872ec34544SRui Ueyama }
12882ec34544SRui Ueyama 
12892ec34544SRui Ueyama // This function parses the attributes used to match against section
12902ec34544SRui Ueyama // flags when placing output sections in a memory region. These flags
12912ec34544SRui Ueyama // are only used when an explicit memory region name is not used.
12922ec34544SRui Ueyama std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
12932ec34544SRui Ueyama   uint32_t Flags = 0;
12942ec34544SRui Ueyama   uint32_t NegFlags = 0;
12952ec34544SRui Ueyama   bool Invert = false;
12962ec34544SRui Ueyama 
12972ec34544SRui Ueyama   for (char C : next().lower()) {
12982ec34544SRui Ueyama     uint32_t Flag = 0;
12992ec34544SRui Ueyama     if (C == '!')
13002ec34544SRui Ueyama       Invert = !Invert;
13012ec34544SRui Ueyama     else if (C == 'w')
13022ec34544SRui Ueyama       Flag = SHF_WRITE;
13032ec34544SRui Ueyama     else if (C == 'x')
13042ec34544SRui Ueyama       Flag = SHF_EXECINSTR;
13052ec34544SRui Ueyama     else if (C == 'a')
13062ec34544SRui Ueyama       Flag = SHF_ALLOC;
13072ec34544SRui Ueyama     else if (C != 'r')
13082ec34544SRui Ueyama       setError("invalid memory region attribute");
13092ec34544SRui Ueyama 
13102ec34544SRui Ueyama     if (Invert)
13112ec34544SRui Ueyama       NegFlags |= Flag;
13122ec34544SRui Ueyama     else
13132ec34544SRui Ueyama       Flags |= Flag;
13142ec34544SRui Ueyama   }
13152ec34544SRui Ueyama   return {Flags, NegFlags};
13162ec34544SRui Ueyama }
13172ec34544SRui Ueyama 
13182ec34544SRui Ueyama void elf::readLinkerScript(MemoryBufferRef MB) {
13192ec34544SRui Ueyama   ScriptParser(MB).readLinkerScript();
13202ec34544SRui Ueyama }
13212ec34544SRui Ueyama 
13222ec34544SRui Ueyama void elf::readVersionScript(MemoryBufferRef MB) {
13232ec34544SRui Ueyama   ScriptParser(MB).readVersionScript();
13242ec34544SRui Ueyama }
13252ec34544SRui Ueyama 
13262ec34544SRui Ueyama void elf::readDynamicList(MemoryBufferRef MB) {
13272ec34544SRui Ueyama   ScriptParser(MB).readDynamicList();
13282ec34544SRui Ueyama }
1329